import React, { useMemo, useState } from 'react';
import { Search } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { DateRangeFilterField } from './DateRangeFilterField';
import { FilterPickerField } from './FilterPickerField';
import { TablePagination } from './TablePagination';
import {
  applyTransferRecordFilters,
  buildTransferRecordOptions,
  EMPTY_TRANSFER_RECORD_FILTERS,
  formatTransferCell,
  resolveVehicleTransferRecords,
  type TransferRecordFilters,
  type TransferRecordRow,
} from '../utils/transferRecords';

interface DetailTransferRecordsTabProps {
  record: VehicleRecord;
  onOpenTransferDetail?: (record: VehicleRecord, row: TransferRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailTransferRecordsTab({
  record,
  onOpenTransferDetail,
}: DetailTransferRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleTransferRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<TransferRecordFilters>(EMPTY_TRANSFER_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<TransferRecordFilters>(EMPTY_TRANSFER_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const transferOutOptions = useMemo(
    () => buildTransferRecordOptions(allRows, 'transferOutPerson'),
    [allRows],
  );
  const recipientOptions = useMemo(
    () => buildTransferRecordOptions(allRows, 'recipientPerson'),
    [allRows],
  );

  const filtered = useMemo(
    () => applyTransferRecordFilters(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<TransferRecordFilters>) => {
    setPendingFilters((prev) => ({ ...prev, ...patch }));
  };

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

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

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

  return (
    <div className="vm-transfer-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--transfer">
          <label className="vm-filter-field">
            <span>调拨日期</span>
            <DateRangeFilterField
              startDate={pendingFilters.startDate}
              endDate={pendingFilters.endDate}
              ariaLabel="调拨日期"
              startPlaceholder="开始日期"
              endPlaceholder="结束日期"
              onChange={(range) => updatePending(range)}
            />
          </label>
          <label className="vm-filter-field">
            <span>调出人</span>
            <FilterPickerField
              value={pendingFilters.transferOutPerson}
              options={transferOutOptions}
              placeholder="请选择调出人"
              ariaLabel="调出人"
              onChange={(value) => updatePending({ transferOutPerson: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>接收人</span>
            <FilterPickerField
              value={pendingFilters.recipientPerson}
              options={recipientOptions}
              placeholder="请选择接收人"
              ariaLabel="接收人"
              onChange={(value) => updatePending({ recipientPerson: 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 vm-table--transfer">
            <thead>
              <tr>
                <th>调拨日期</th>
                <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={9} className="vm-empty-cell">暂无数据</td>
                </tr>
              ) : (
                paged.map((row) => (
                  <tr key={row.id}>
                    <td>
                      <button
                        type="button"
                        className="vm-link"
                        onClick={() => onOpenTransferDetail?.(record, row)}
                      >
                        {row.transferDate}
                      </button>
                    </td>
                    <td>{row.transferOutPerson}</td>
                    <td>{row.recipientPerson}</td>
                    <td>{row.departureArea}</td>
                    <td>{row.receivingArea}</td>
                    <td>{row.transferMethod}</td>
                    <td className="ellipsis" title={row.departureParking}>{formatTransferCell(row.departureParking)}</td>
                    <td className="ellipsis" title={row.receivingParking}>{formatTransferCell(row.receivingParking)}</td>
                    <td>{formatTransferCell(row.receiveDate)}</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>
  );
}
