import React, { useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { FilterPickerField } from './FilterPickerField';
import { TablePagination } from './TablePagination';
import {
  applyLeaseRecordFilters,
  buildLeaseRecordOptions,
  EMPTY_LEASE_RECORD_FILTERS,
  formatLeaseRecordCell,
  isLeaseRecordLinkable,
  resolveVehicleLeaseRecords,
  type LeaseRecordFilters,
  type LeaseRecordRow,
} from '../utils/leaseRecords';

interface DetailLeaseRecordsTabProps {
  record: VehicleRecord;
  onOpenLeaseContract?: (record: VehicleRecord, contractNo: string) => void;
  onOpenDeliveryRecord?: (record: VehicleRecord, row: LeaseRecordRow) => void;
  onOpenReturnRecord?: (record: VehicleRecord, row: LeaseRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailLeaseRecordsTab({
  record,
  onOpenLeaseContract,
  onOpenDeliveryRecord,
  onOpenReturnRecord,
}: DetailLeaseRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleLeaseRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<LeaseRecordFilters>(EMPTY_LEASE_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<LeaseRecordFilters>(EMPTY_LEASE_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const contractOptions = useMemo(
    () => buildLeaseRecordOptions(allRows, 'contractNo'),
    [allRows],
  );
  const projectOptions = useMemo(
    () => buildLeaseRecordOptions(allRows, 'projectName'),
    [allRows],
  );
  const customerOptions = useMemo(
    () => buildLeaseRecordOptions(allRows, 'customerName'),
    [allRows],
  );
  const businessTypeOptions = useMemo(
    () => buildLeaseRecordOptions(allRows, 'businessType'),
    [allRows],
  );

  const filtered = useMemo(
    () => applyLeaseRecordFilters(allRows, appliedFilters),
    [allRows, appliedFilters],
  );

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const currentPage = Math.min(page, totalPages);
  const paged = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, currentPage, pageSize]);

  const updatePending = (patch: Partial<LeaseRecordFilters>) => {
    setPendingFilters((prev) => ({ ...prev, ...patch }));
  };

  const handleReset = () => {
    setPendingFilters(EMPTY_LEASE_RECORD_FILTERS);
    setAppliedFilters(EMPTY_LEASE_RECORD_FILTERS);
    setPage(1);
  };

  const handleSearch = () => {
    setAppliedFilters(pendingFilters);
    setPage(1);
  };

  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setPage(1);
  };

  const openContract = (contractNo: string) => {
    if (!isLeaseRecordLinkable(contractNo)) return;
    onOpenLeaseContract?.(record, contractNo);
  };

  return (
    <div className="vm-lease-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid">
          <label className="vm-filter-field">
            <span>合同编码</span>
            <FilterPickerField
              value={pendingFilters.contractNo}
              options={contractOptions}
              placeholder="请输入或选择合同编码"
              ariaLabel="合同编码"
              onChange={(value) => updatePending({ contractNo: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>项目名称</span>
            <FilterPickerField
              value={pendingFilters.projectName}
              options={projectOptions}
              placeholder="请输入或选择项目名称"
              ariaLabel="项目名称"
              onChange={(value) => updatePending({ projectName: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>客户名称</span>
            <FilterPickerField
              value={pendingFilters.customerName}
              options={customerOptions}
              placeholder="请输入或选择客户名称"
              ariaLabel="客户名称"
              onChange={(value) => updatePending({ customerName: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>业务类型</span>
            <FilterPickerField
              value={pendingFilters.businessType}
              options={businessTypeOptions}
              placeholder="请输入或选择业务类型"
              ariaLabel="业务类型"
              onChange={(value) => updatePending({ businessType: value })}
            />
          </label>
        </div>
        <div className="vm-detail-tab-filter-actions">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={handleReset}>
            重置
          </button>
          <button type="button" className="vm-btn vm-btn-primary" onClick={handleSearch}>
            <Search size={16} aria-hidden />
            查询
          </button>
        </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>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr>
                  <td colSpan={8} className="vm-empty-cell">暂无租赁记录</td>
                </tr>
              ) : (
                paged.map((row) => (
                  <tr key={row.id}>
                    <td>
                      {isLeaseRecordLinkable(row.contractNo) ? (
                        <button
                          type="button"
                          className="vm-link code"
                          onClick={() => openContract(row.contractNo)}
                        >
                          {row.contractNo}
                        </button>
                      ) : (
                        <span className="code">{formatLeaseRecordCell(row.contractNo)}</span>
                      )}
                    </td>
                    <td className="ellipsis" title={row.projectName || undefined}>
                      {isLeaseRecordLinkable(row.projectName) ? (
                        <button
                          type="button"
                          className="vm-link primary"
                          onClick={() => openContract(row.contractNo)}
                        >
                          {row.projectName}
                        </button>
                      ) : (
                        formatLeaseRecordCell(row.projectName)
                      )}
                    </td>
                    <td className="ellipsis" title={row.customerName || undefined}>
                      {formatLeaseRecordCell(row.customerName)}
                    </td>
                    <td>{row.businessType}</td>
                    <td>
                      {isLeaseRecordLinkable(row.deliveryDate) ? (
                        <button
                          type="button"
                          className="vm-link"
                          onClick={() => onOpenDeliveryRecord?.(record, row)}
                        >
                          {row.deliveryDate}
                        </button>
                      ) : (
                        formatLeaseRecordCell(row.deliveryDate)
                      )}
                    </td>
                    <td>{formatLeaseRecordCell(row.deliveryPerson)}</td>
                    <td>
                      {isLeaseRecordLinkable(row.returnDate) ? (
                        <button
                          type="button"
                          className="vm-link"
                          onClick={() => onOpenReturnRecord?.(record, row)}
                        >
                          {row.returnDate}
                        </button>
                      ) : (
                        formatLeaseRecordCell(row.returnDate)
                      )}
                    </td>
                    <td>{formatLeaseRecordCell(row.returnPerson)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <div className="vm-table-footer vm-table-footer--split vm-table-footer--compact">
          <span className="vm-table-total">共 {filtered.length} 条</span>
          {filtered.length > 0 && (
            <TablePagination
              page={currentPage}
              pageSize={pageSize}
              total={filtered.length}
              onPageChange={setPage}
              onPageSizeChange={handlePageSizeChange}
            />
          )}
        </div>
      </div>
    </div>
  );
}
