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 {
  applyViolationRecordFilters,
  buildViolationRecordOptions,
  EMPTY_VIOLATION_RECORD_FILTERS,
  formatViolationFine,
  formatViolationPoints,
  resolveVehicleViolationRecords,
  VIOLATION_PAYMENT_STATUS_OPTIONS,
  VIOLATION_PROCESSED_OPTIONS,
  violationPaymentTone,
  violationProcessedTone,
  type ViolationRecordFilters,
  type ViolationRecordRow,
} from '../utils/violationRecords';

interface DetailViolationRecordsTabProps {
  record: VehicleRecord;
  onOpenViolationDetail?: (record: VehicleRecord, row: ViolationRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailViolationRecordsTab({
  record,
  onOpenViolationDetail,
}: DetailViolationRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleViolationRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<ViolationRecordFilters>(EMPTY_VIOLATION_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<ViolationRecordFilters>(EMPTY_VIOLATION_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const customerOptions = useMemo(
    () => buildViolationRecordOptions(allRows, 'customerName'),
    [allRows],
  );
  const paymentOptions = useMemo(() => {
    const fromData = buildViolationRecordOptions(allRows, 'paymentStatus');
    return fromData.length ? fromData : [...VIOLATION_PAYMENT_STATUS_OPTIONS];
  }, [allRows]);
  const processedOptions = useMemo(() => {
    const fromData = buildViolationRecordOptions(allRows, 'processed');
    return fromData.length ? fromData : [...VIOLATION_PROCESSED_OPTIONS];
  }, [allRows]);

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

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

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

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

  return (
    <div className="vm-violation-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--violation">
          <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.paymentStatus}
              options={paymentOptions}
              placeholder="请选择缴费状态"
              ariaLabel="缴费状态"
              onChange={(value) => updatePending({ paymentStatus: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>是否处理</span>
            <FilterPickerField
              value={pendingFilters.processed}
              options={processedOptions}
              placeholder="请选择是否处理"
              ariaLabel="是否处理"
              onChange={(value) => updatePending({ processed: 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--violation">
            <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>{row.violationTime}</td>
                    <td className="ellipsis" title={row.violationLocation}>{row.violationLocation}</td>
                    <td className="ellipsis" title={row.violationBehavior}>
                      <button
                        type="button"
                        className="vm-link"
                        onClick={() => onOpenViolationDetail?.(record, row)}
                      >
                        {row.violationBehavior}
                      </button>
                    </td>
                    <td>{formatViolationPoints(row.pointsDeducted)}</td>
                    <td className="vm-table-num">{formatViolationFine(row.fineAmount)}</td>
                    <td>
                      <StatusTag label={row.paymentStatus} tone={violationPaymentTone(row.paymentStatus)} />
                    </td>
                    <td>
                      <StatusTag label={row.processed} tone={violationProcessedTone(row.processed)} />
                    </td>
                    <td className="ellipsis" title={row.collectionUnit}>{row.collectionUnit}</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>
  );
}
