import React, { useMemo, useState } from 'react';
import type { VehicleRecord } from '../types';
import { ExpireDate } from './ExpireDate';
import { StatusTag } from './StatusTag';
import {
  insuranceStatusTone,
  purchaseTypeTone,
  resolveVehicleInsuranceOverview,
  type InsuranceHistoryRow,
  type InsuranceTypeCoverage,
  type VehicleInsuranceTypeKey,
} from '../utils/vehicleInsuranceRecords';

interface DetailInsuranceRecordsTabProps {
  record: VehicleRecord;
  onOpenInsurancePurchase?: (record: VehicleRecord, insuranceLabel: string) => void;
  onPreviewPolicyFile?: (fileName: string) => void;
  onDownloadPolicyFile?: (fileName: string) => void;
}

function InsuranceTypeSummaryCard({
  coverage,
  active,
  count,
  onClick,
}: {
  coverage: InsuranceTypeCoverage;
  active: boolean;
  count: number;
  onClick: () => void;
}) {
  const isNotPurchased = coverage.status === 'not_purchased';
  const showDateMeta = !isNotPurchased && Boolean(coverage.expireDate);

  return (
    <button
      type="button"
      className={`vm-ins-type-card${active ? ' is-active' : ''}`}
      onClick={onClick}
    >
      <div className="vm-ins-type-card-head">
        <span className="vm-ins-type-card-title">{coverage.label}</span>
        {count > 0 ? <span className="vm-ins-type-card-count">{count}</span> : null}
      </div>
      <div className="vm-ins-type-card-status-row">
        <StatusTag
          label={coverage.statusLabel}
          tone={insuranceStatusTone(coverage.status)}
        />
        {showDateMeta ? (
          <span className="vm-ins-type-card-date">
            <ExpireDate date={coverage.expireDate} alwaysShowRemainder />
          </span>
        ) : null}
      </div>
    </button>
  );
}

function PolicyFileCell({
  row,
  onPreview,
  onDownload,
}: {
  row: InsuranceHistoryRow;
  onPreview?: (fileName: string) => void;
  onDownload?: (fileName: string) => void;
}) {
  if (!row.policyFileName) {
    return <span className="vm-ins-policy-file-empty">无附件</span>;
  }

  return (
    <div className="vm-ins-policy-file-actions">
      <button
        type="button"
        className="vm-link"
        onClick={() => onPreview?.(row.policyFileName!)}
      >
        预览
      </button>
      <span className="vm-ins-policy-file-divider" aria-hidden>·</span>
      <button
        type="button"
        className="vm-link"
        onClick={() => onDownload?.(row.policyFileName!)}
      >
        下载
      </button>
    </div>
  );
}

export function DetailInsuranceRecordsTab({
  record,
  onOpenInsurancePurchase,
  onPreviewPolicyFile,
  onDownloadPolicyFile,
}: DetailInsuranceRecordsTabProps) {
  const overview = useMemo(() => resolveVehicleInsuranceOverview(record), [record]);
  const [activeType, setActiveType] = useState<VehicleInsuranceTypeKey>('compulsory');

  const activeCoverage = overview.types.find((item) => item.key === activeType) ?? overview.types[0];
  const allInsuranceNotPurchased = overview.types.every((item) => item.status === 'not_purchased');

  return (
    <div className="vm-ins-records-tab">
      <div className="vm-ins-records-hero">
        <div>
          <div className="vm-ins-records-hero-title">车辆保险档案</div>
        </div>
        <StatusTag
          label={`保险状态 · ${overview.overallLabel}`}
          tone={overview.overallTone}
          title={overview.overallTip}
        />
      </div>

      <div className="vm-ins-type-grid">
        {overview.types.map((coverage) => (
          <InsuranceTypeSummaryCard
            key={coverage.key}
            coverage={coverage}
            active={activeType === coverage.key}
            count={coverage.history.length}
            onClick={() => setActiveType(coverage.key)}
          />
        ))}
      </div>

      <div className="vm-ins-records-panel">
        <div className="vm-ins-records-panel-head">
          <h4 className="vm-ins-records-panel-title">{activeCoverage.label}</h4>
        </div>

        {activeCoverage.history.length === 0 ? (
          <div className="vm-ins-records-empty">
            <div className="vm-ins-records-empty-title">{activeCoverage.label}暂无记录</div>
            {!allInsuranceNotPurchased ? (
              <button
                type="button"
                className="vm-btn vm-btn-primary vm-ins-records-empty-upload"
                onClick={() => onOpenInsurancePurchase?.(record, activeCoverage.label)}
              >
                去上传
              </button>
            ) : null}
          </div>
        ) : (
          <>
            <div className="vm-model-param-grid vm-ins-records-summary">
              <div className="vm-model-param-item">
                <span className="vm-model-param-label">保单号</span>
                <div className="vm-model-param-value">{activeCoverage.policyNo || '—'}</div>
              </div>
              <div className="vm-model-param-item">
                <span className="vm-model-param-label">保险公司</span>
                <div className="vm-model-param-value">{activeCoverage.company || '—'}</div>
              </div>
              <div className="vm-model-param-item">
                <span className="vm-model-param-label">到期日期</span>
                <div className="vm-model-param-value">
                  {activeCoverage.expireDate
                    ? <ExpireDate date={activeCoverage.expireDate} alwaysShowRemainder />
                    : '—'}
                </div>
              </div>
              <div className="vm-model-param-item">
                <span className="vm-model-param-label">保费（元）</span>
                <div className="vm-model-param-value">{activeCoverage.premium || '—'}</div>
              </div>
            </div>

            <div className="vm-table-card">
              <div className="vm-table-wrap vm-table-wrap--detail-tab">
                <table className="vm-table">
                  <thead>
                    <tr>
                      <th>保险导入时间</th>
                      <th>操作人</th>
                      <th>类型</th>
                      <th>保单号</th>
                      <th>保险状态</th>
                      <th>保险公司</th>
                      <th>付款时间</th>
                      <th>到期日期</th>
                      <th>保单文件</th>
                    </tr>
                  </thead>
                  <tbody>
                    {activeCoverage.history.map((row) => (
                      <tr key={row.id}>
                        <td>{row.purchaseTime || '—'}</td>
                        <td>{row.operator || '—'}</td>
                        <td>
                          <StatusTag label={row.purchaseType} tone={purchaseTypeTone(row.purchaseType)} />
                        </td>
                        <td><span className="code">{row.policyNo || '—'}</span></td>
                        <td>
                          <StatusTag
                            label={row.policyStatus}
                            tone={row.policyStatus === '已停保' ? 'amber' : row.policyStatus === '已退保' ? 'gray' : 'green'}
                          />
                        </td>
                        <td className="ellipsis" title={row.company !== '—' ? row.company : undefined}>
                          {row.company || '—'}
                        </td>
                        <td>{row.payTime || '—'}</td>
                        <td>
                          {row.expireDate ? (
                            <ExpireDate date={row.expireDate} alwaysShowRemainder />
                          ) : '—'}
                        </td>
                        <td>
                          <PolicyFileCell
                            row={row}
                            onPreview={onPreviewPolicyFile}
                            onDownload={onDownloadPolicyFile}
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
