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 { StatusTag } from './StatusTag';
import { TablePagination } from './TablePagination';
import {
  ACCIDENT_LEVEL_OPTIONS,
  ACCIDENT_STATUS_OPTIONS,
  applyAccidentRecordFilters,
  buildAccidentRecordOptions,
  EMPTY_ACCIDENT_RECORD_FILTERS,
  formatAccidentAmount,
  formatAccidentCell,
  accidentStatusTone,
  resolveVehicleAccidentRecords,
  type AccidentRecordFilters,
  type AccidentRecordRow,
} from '../utils/accidentRecords';

interface DetailAccidentRecordsTabProps {
  record: VehicleRecord;
  onOpenAccidentDetail?: (record: VehicleRecord, row: AccidentRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailAccidentRecordsTab({
  record,
  onOpenAccidentDetail,
}: DetailAccidentRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleAccidentRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<AccidentRecordFilters>(EMPTY_ACCIDENT_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<AccidentRecordFilters>(EMPTY_ACCIDENT_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const customerOptions = useMemo(
    () => buildAccidentRecordOptions(allRows, 'customerName'),
    [allRows],
  );
  const levelOptions = useMemo(() => {
    const fromData = buildAccidentRecordOptions(allRows, 'accidentLevel');
    return fromData.length ? fromData : [...ACCIDENT_LEVEL_OPTIONS];
  }, [allRows]);
  const statusOptions = useMemo(() => {
    const fromData = buildAccidentRecordOptions(allRows, 'status');
    return fromData.length ? fromData : [...ACCIDENT_STATUS_OPTIONS];
  }, [allRows]);

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

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

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

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

  return (
    <div className="vm-accident-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--accident">
          <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.customerName}
              options={customerOptions}
              placeholder="请输入或选择客户名称"
              ariaLabel="客户名称"
              onChange={(value) => updatePending({ customerName: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>事故等级</span>
            <FilterPickerField
              value={pendingFilters.accidentLevel}
              options={levelOptions}
              placeholder="请选择事故等级"
              ariaLabel="事故等级"
              onChange={(value) => updatePending({ accidentLevel: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>事故状态</span>
            <FilterPickerField
              value={pendingFilters.accidentStatus}
              options={statusOptions}
              placeholder="请选择事故状态"
              ariaLabel="事故状态"
              onChange={(value) => updatePending({ accidentStatus: 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--accident">
            <thead>
              <tr>
                <th>事故编码</th>
                <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={10} className="vm-empty-cell">暂无数据</td>
                </tr>
              ) : (
                paged.map((row) => (
                  <tr key={row.id}>
                    <td>
                      <button
                        type="button"
                        className="vm-link code"
                        onClick={() => onOpenAccidentDetail?.(record, row)}
                      >
                        {row.accidentCode}
                      </button>
                    </td>
                    <td>{row.accidentTime}</td>
                    <td className="ellipsis" title={row.accidentLocation}>{row.accidentLocation}</td>
                    <td>{row.accidentType}</td>
                    <td className="ellipsis" title={row.customerName}>{row.customerName}</td>
                    <td className="vm-table-num">{formatAccidentAmount(row.ourDamageAmount)}</td>
                    <td className="vm-table-num">{formatAccidentAmount(row.theirDamageAmount)}</td>
                    <td>{row.responsibility}</td>
                    <td>
                      <StatusTag label={row.status} tone={accidentStatusTone(row.status)} />
                    </td>
                    <td>{formatAccidentCell(row.closedTime)}</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>
  );
}
