import React, { useMemo, useState } from 'react';
import { CircleHelp, Truck, X } from 'lucide-react';
import {
  LEASE_CONTRACT_LIST_RECORDS,
  enrichLeaseContractListRecords,
  resolveContractDisplayStatus,
  buildOnLeaseFleetByBrandModel,
} from '../../lease-contract-management/lease-contract-list-data.js';

const FLEET_KPI_DESC = '按品牌型号统计在租车辆；点击卡片在弹窗中查看各车型分布与明细。';

type FleetBucket = ReturnType<typeof buildOnLeaseFleetByBrandModel>[number];

type FleetEntry = FleetBucket['entries'][number];

function useFleetData() {
  const fleetSourceList = useMemo(
    () => enrichLeaseContractListRecords(LEASE_CONTRACT_LIST_RECORDS).map((record) => ({
      ...record,
      contractStatus: resolveContractDisplayStatus(record),
    })),
    [],
  );

  const summary = useMemo(
    () => buildOnLeaseFleetByBrandModel(fleetSourceList),
    [fleetSourceList],
  );

  const totalOnLease = useMemo(
    () => summary.reduce((sum, item) => sum + item.count, 0),
    [summary],
  );

  return { summary, totalOnLease };
}

function FleetModelCard({
  item,
  totalOnLease,
  maxCount,
  onOpenDetail,
}: {
  item: FleetBucket;
  totalOnLease: number;
  maxCount: number;
  onOpenDetail: (item: FleetBucket) => void;
}) {
  const share = totalOnLease ? Math.round((item.count / totalOnLease) * 100) : 0;
  const barWidth = maxCount ? Math.max(8, Math.round((item.count / maxCount) * 100)) : 8;

  return (
    <article
      className="vm-fleet-model-card"
      role="listitem"
      tabIndex={0}
      onClick={() => onOpenDetail(item)}
      onKeyDown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onOpenDetail(item);
        }
      }}
      aria-label={`${item.brand} ${item.model}，${item.count} 辆在租，点击查看明细`}
    >
      <div className="vm-fleet-model-card__top">
        <span className="vm-fleet-model-card__brand">{item.brand}</span>
        <span className="vm-fleet-model-card__type">{item.vehicleType}</span>
      </div>
      <h3 className="vm-fleet-model-card__model" title={item.model}>{item.model}</h3>
      <div className="vm-fleet-model-card__metrics">
        <span className="vm-fleet-model-card__count tabular-nums">{item.count}</span>
        <span className="vm-fleet-model-card__unit">辆</span>
        <span className="vm-fleet-model-card__share tabular-nums">占 {share}%</span>
      </div>
      <div className="vm-fleet-model-card__bar" aria-hidden>
        <span className="vm-fleet-model-card__bar-fill" style={{ width: `${barWidth}%` }} />
      </div>
      <span className="vm-fleet-model-card__hint">点击查看车辆明细</span>
    </article>
  );
}

function FleetOverviewModal({
  open,
  onClose,
  summary,
  totalOnLease,
  onOpenDetail,
}: {
  open: boolean;
  onClose: () => void;
  summary: FleetBucket[];
  totalOnLease: number;
  onOpenDetail: (item: FleetBucket) => void;
}) {
  const [brandFilter, setBrandFilter] = useState('全部');

  const brandOptions = useMemo(() => {
    const set = new Set(summary.map((item) => item.brand));
    return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
  }, [summary]);

  const filtered = useMemo(
    () => summary.filter((item) => brandFilter === '全部' || item.brand === brandFilter),
    [summary, brandFilter],
  );

  const maxCount = filtered.length
    ? Math.max(...filtered.map((item) => item.count))
    : 1;

  if (!open) return null;

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-fleet-overview-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="vm-fleet-overview-title"
        onClick={(event) => event.stopPropagation()}
        data-annotation-id="vm-fleet-overview-modal"
      >
        <header className="vm-modal-header">
          <div>
            <h2 id="vm-fleet-overview-title">在租车辆 · 各车型分布</h2>
            <p>共 <span className="tabular-nums">{totalOnLease}</span> 辆在租，点击车型卡片查看车辆明细</p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-fleet-overview-modal__body">
          <div className="vm-fleet-overview-modal__brands" role="group" aria-label="按品牌筛选">
            <button
              type="button"
              className={`vm-fleet-brand-chip${brandFilter === '全部' ? ' is-active' : ''}`}
              onClick={() => setBrandFilter('全部')}
              aria-pressed={brandFilter === '全部'}
            >
              全部
            </button>
            {brandOptions.map((brand) => (
              <button
                key={brand}
                type="button"
                className={`vm-fleet-brand-chip${brandFilter === brand ? ' is-active' : ''}`}
                onClick={() => setBrandFilter(brandFilter === brand ? '全部' : brand)}
                aria-pressed={brandFilter === brand}
              >
                {brand}
              </button>
            ))}
          </div>
          {filtered.length ? (
            <div className="vm-fleet-overview-modal__grid" role="list">
              {filtered.map((item) => (
                <FleetModelCard
                  key={item.key}
                  item={item}
                  totalOnLease={totalOnLease}
                  maxCount={maxCount}
                  onOpenDetail={onOpenDetail}
                />
              ))}
            </div>
          ) : (
            <div className="vm-fleet-overview-modal__empty">
              <p>该品牌暂无在租车型</p>
              <button type="button" className="vm-btn vm-btn-ghost" data-vm-icon="eye" onClick={() => setBrandFilter('全部')}>
                查看全部
              </button>
            </div>
          )}
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-primary" onClick={onClose} data-vm-icon="x">关闭</button>
        </footer>
      </div>
    </div>
  );
}

function FleetDetailModal({
  open,
  item,
  onClose,
}: {
  open: boolean;
  item: FleetBucket | null;
  onClose: () => void;
}) {
  if (!open || !item) return null;

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-fleet-detail-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="vm-fleet-detail-title"
        onClick={(event) => event.stopPropagation()}
      >
        <header className="vm-modal-header">
          <div>
            <h2 id="vm-fleet-detail-title">{item.brand} · {item.model}</h2>
            <p>
              <span className="vm-fleet-detail-modal__badge tabular-nums">{item.count} 辆在租</span>
              <span className="vm-fleet-detail-modal__type">{item.vehicleType}</span>
            </p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-fleet-detail-modal__body">
          <div className="vm-table-card">
            <table className="vm-table vm-fleet-detail-table">
              <thead>
                <tr>
                  <th scope="col">车辆类型</th>
                  <th scope="col">品牌</th>
                  <th scope="col">型号</th>
                  <th scope="col">车牌号</th>
                  <th scope="col">合同编码</th>
                  <th scope="col">项目名称</th>
                </tr>
              </thead>
              <tbody>
                {item.entries.map((entry: FleetEntry, index: number) => {
                  const record = entry.record;
                  const vehicle = entry.vehicle;
                  return (
                    <tr key={`${record?.id || 'rec'}-fleet-${index}`}>
                      <td>{vehicle.vehicleType || '—'}</td>
                      <td>{vehicle.brand || '—'}</td>
                      <td>{vehicle.model || '—'}</td>
                      <td>{vehicle.plateNo || '—'}</td>
                      <td>{record?.contractCode || '—'}</td>
                      <td>{record?.projectName || '—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-primary" onClick={onClose} data-vm-icon="x">关闭</button>
        </footer>
      </div>
    </div>
  );
}

export function useOnLeaseFleetKpi() {
  const { summary, totalOnLease } = useFleetData();
  const [overviewOpen, setOverviewOpen] = useState(false);
  const [detailItem, setDetailItem] = useState<FleetBucket | null>(null);

  const trailing = totalOnLease > 0 ? (
    <button
      type="button"
      className={`vm-kpi-card vm-kpi-card--on-lease${overviewOpen ? ' active' : ''}`}
      onClick={() => setOverviewOpen(true)}
      aria-pressed={overviewOpen}
      data-annotation-id="vm-kpi-onLeaseFleet"
    >
      <span
        className="vm-kpi-tip"
        tabIndex={0}
        role="note"
        aria-label="在租车辆说明"
        onClick={(event) => event.stopPropagation()}
        onMouseDown={(event) => event.stopPropagation()}
      >
        <CircleHelp size={14} aria-hidden />
        <span className="vm-kpi-tooltip" role="tooltip">{FLEET_KPI_DESC}</span>
      </span>
      <span className="vm-kpi-icon" aria-hidden>
        <Truck size={18} />
      </span>
      <span className="vm-kpi-main">
        <span className="vm-kpi-eyebrow">在租车辆</span>
        <span className="vm-kpi-val tabular-nums">{totalOnLease}</span>
      </span>
    </button>
  ) : null;

  const modals = (
    <>
      <FleetOverviewModal
        open={overviewOpen}
        onClose={() => setOverviewOpen(false)}
        summary={summary}
        totalOnLease={totalOnLease}
        onOpenDetail={(item) => {
          setDetailItem(item);
          setOverviewOpen(false);
        }}
      />
      <FleetDetailModal
        open={!!detailItem}
        item={detailItem}
        onClose={() => setDetailItem(null)}
      />
    </>
  );

  return { trailing, modals };
}

/** @deprecated 请使用 useOnLeaseFleetKpi + KpiCards trailing */
export function OnLeaseFleetSection() {
  const { trailing, modals } = useOnLeaseFleetKpi();
  if (!trailing) return null;
  return (
    <>
      <div className="vm-kpi-row vm-kpi-row--on-lease-only">{trailing}</div>
      {modals}
    </>
  );
}
