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 {
  applyAnnualReviewRecordFilters,
  buildAnnualReviewRecordOptions,
  EMPTY_ANNUAL_REVIEW_RECORD_FILTERS,
  formatAnnualReviewCell,
  formatAnnualReviewMoney,
  resolveVehicleAnnualReviewRecords,
  type AnnualReviewRecordFilters,
  type AnnualReviewRecordRow,
} from '../utils/annualReviewRecords';

interface DetailAnnualReviewRecordsTabProps {
  record: VehicleRecord;
  onOpenAnnualReviewDetail?: (record: VehicleRecord, row: AnnualReviewRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailAnnualReviewRecordsTab({
  record,
  onOpenAnnualReviewDetail,
}: DetailAnnualReviewRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleAnnualReviewRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<AnnualReviewRecordFilters>(
    EMPTY_ANNUAL_REVIEW_RECORD_FILTERS,
  );
  const [appliedFilters, setAppliedFilters] = useState<AnnualReviewRecordFilters>(
    EMPTY_ANNUAL_REVIEW_RECORD_FILTERS,
  );
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const executorOptions = useMemo(
    () => buildAnnualReviewRecordOptions(allRows, 'executor'),
    [allRows],
  );

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

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

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

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

  return (
    <div className="vm-annual-review-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--annual-review">
          <label className="vm-filter-field">
            <span>完成时间</span>
            <DateRangeFilterField
              startDate={pendingFilters.executeStartDate}
              endDate={pendingFilters.executeEndDate}
              ariaLabel="完成时间"
              startPlaceholder="开始日期"
              endPlaceholder="结束日期"
              onChange={(range) => updatePending({
                executeStartDate: range.startDate,
                executeEndDate: range.endDate,
              })}
            />
          </label>
          <label className="vm-filter-field">
            <span>检验有效期</span>
            <DateRangeFilterField
              startDate={pendingFilters.validStartDate}
              endDate={pendingFilters.validEndDate}
              ariaLabel="检验有效期"
              startPlaceholder="开始日期"
              endPlaceholder="结束日期"
              onChange={(range) => updatePending({
                validStartDate: range.startDate,
                validEndDate: range.endDate,
              })}
            />
          </label>
          <label className="vm-filter-field">
            <span>办理人</span>
            <FilterPickerField
              value={pendingFilters.executor}
              options={executorOptions}
              placeholder="请选择办理人"
              ariaLabel="办理人"
              onChange={(value) => updatePending({ executor: 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 vm-table-wrap--wide">
          <table className="vm-table vm-table--annual-review">
            <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={() => onOpenAnnualReviewDetail?.(record, row)}
                      >
                        {row.inspectionValidUntil}
                      </button>
                    </td>
                    <td className="ellipsis" title={row.inspectionStation || undefined}>
                      {formatAnnualReviewCell(row.inspectionStation)}
                    </td>
                    <td className="vm-table-num">{formatAnnualReviewMoney(row.inspectionCost)}</td>
                    <td className="ellipsis" title={row.m2Station || undefined}>
                      {formatAnnualReviewCell(row.m2Station)}
                    </td>
                    <td className="vm-table-num">{formatAnnualReviewMoney(row.m2Cost)}</td>
                    <td className="ellipsis" title={row.zbStation || undefined}>
                      {formatAnnualReviewCell(row.zbStation)}
                    </td>
                    <td className="vm-table-num">{formatAnnualReviewMoney(row.zbCost)}</td>
                    <td>{row.executor}</td>
                    <td>{row.executeTime}</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>
  );
}
