import React from 'react';
import type { VehicleRecord } from '../types';
import {
  displayText,
  formatHandoverDateTimeMinute,
  formatHandoverMileage,
} from '../utils/vehicle';

interface HandoverSituationCellProps {
  kind: 'delivery' | 'return';
  record: VehicleRecord;
  emptyLabel?: string;
  onClick?: (record: VehicleRecord) => void;
}

const LABELS = {
  delivery: {
    mile: '交车里程',
    person: '交车人',
    time: '交车时间',
  },
  return: {
    mile: '还车里程',
    person: '还车人',
    time: '还车时间',
  },
} as const;

export function HandoverSituationCell({
  kind,
  record,
  emptyLabel = '',
  onClick,
}: HandoverSituationCellProps) {
  const labels = LABELS[kind];
  const mile =
    kind === 'delivery' ? record.lastDeliveryMile : record.lastReturnMile;
  const person =
    kind === 'delivery' ? record.lastDeliveryPerson : record.lastReturnPerson;
  const time =
    kind === 'delivery' ? record.lastDeliveryTime : record.lastReturnTime;

  const mileText = formatHandoverMileage(mile, emptyLabel);
  const personText = displayText(person, emptyLabel);
  const timeText = formatHandoverDateTimeMinute(time, emptyLabel);

  const line1 = mileText;
  const line2 = personText;
  const line3 = timeText;

  if (!line1 && !line2 && !line3) return <>{emptyLabel}</>;

  const title = [
    mileText && `${labels.mile} ${mileText}`,
    personText && `${labels.person} ${personText}`,
    timeText && `${labels.time} ${timeText}`,
  ].filter(Boolean).join(' / ');

  const jumpHint = kind === 'delivery' ? '点击查看交车管理' : '点击查看还车管理';
  const cellTitle = onClick ? `${title} · ${jumpHint}` : title;

  const content = (
    <>
      {line1 ? (
        <div className="vm-handover-situation-line vm-handover-situation-line--mile" title={line1}>
          {line1}
        </div>
      ) : null}
      {line2 ? (
        <div className="vm-handover-situation-line vm-handover-situation-line--person" title={line2}>
          {line2}
        </div>
      ) : null}
      {line3 ? (
        <div className="vm-handover-situation-line vm-handover-situation-line--time" title={line3}>
          {line3}
        </div>
      ) : null}
    </>
  );

  if (onClick) {
    return (
      <button
        type="button"
        className="vm-handover-situation-cell vm-handover-situation-cell--clickable"
        title={cellTitle || undefined}
        onClick={() => onClick(record)}
      >
        {content}
      </button>
    );
  }

  return (
    <div className="vm-handover-situation-cell" title={title || undefined}>
      {content}
    </div>
  );
}
