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 {
  FAULT_AI_MATCH_OPTIONS,
  FAULT_LEVEL_OPTIONS,
  FAULT_RESOLUTION_OPTIONS,
  applyFaultRecordFilters,
  buildFaultRecordOptions,
  EMPTY_FAULT_RECORD_FILTERS,
  faultLevelTone,
  formatAiMatched,
  formatFaultCell,
  resolveVehicleFaultRecords,
  type FaultRecordFilters,
  type FaultRecordRow,
} from '../utils/faultRecords';

interface DetailFaultRecordsTabProps {
  record: VehicleRecord;
  onViewFaultDetail?: (record: VehicleRecord, row: FaultRecordRow) => void;
  onEditFaultRecord?: (record: VehicleRecord, row: FaultRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailFaultRecordsTab({
  record,
  onViewFaultDetail,
  onEditFaultRecord,
}: DetailFaultRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleFaultRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<FaultRecordFilters>(EMPTY_FAULT_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<FaultRecordFilters>(EMPTY_FAULT_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const faultNoOptions = useMemo(
    () => buildFaultRecordOptions(allRows, 'faultNo'),
    [allRows],
  );
  const levelOptions = useMemo(() => {
    const fromData = buildFaultRecordOptions(allRows, 'faultLevel');
    return fromData.length ? fromData : [...FAULT_LEVEL_OPTIONS];
  }, [allRows]);
  const typeOptions = useMemo(
    () => buildFaultRecordOptions(allRows, 'faultType'),
    [allRows],
  );

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

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

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

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

  return (
    <div className="vm-fault-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--fault">
          <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.faultNo}
              options={faultNoOptions}
              placeholder="请输入或选择故障编号"
              ariaLabel="故障编号"
              onChange={(value) => updatePending({ faultNo: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>故障等级</span>
            <FilterPickerField
              value={pendingFilters.faultLevel}
              options={levelOptions}
              placeholder="请选择故障等级"
              ariaLabel="故障等级"
              onChange={(value) => updatePending({ faultLevel: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>故障类型</span>
            <FilterPickerField
              value={pendingFilters.faultType}
              options={typeOptions}
              placeholder="请选择故障类型"
              ariaLabel="故障类型"
              onChange={(value) => updatePending({ faultType: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>解决情况</span>
            <FilterPickerField
              value={pendingFilters.resolutionStatus}
              options={[...FAULT_RESOLUTION_OPTIONS]}
              placeholder="请选择解决情况"
              ariaLabel="解决情况"
              onChange={(value) => updatePending({ resolutionStatus: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>AI匹配状态</span>
            <FilterPickerField
              value={pendingFilters.aiMatched}
              options={[...FAULT_AI_MATCH_OPTIONS]}
              placeholder="请选择AI匹配状态"
              ariaLabel="AI匹配状态"
              onChange={(value) => updatePending({ aiMatched: 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--fault">
            <thead>
              <tr>
                <th>故障编号</th>
                <th>解决情况</th>
                <th>车牌号</th>
                <th>车辆品牌</th>
                <th>车辆型号</th>
                <th>运营公司</th>
                <th>故障等级</th>
                <th>故障类型</th>
                <th>故障描述</th>
                <th>上报时间</th>
                <th>解决时间</th>
                <th>AI匹配状态</th>
                <th>最后操作人</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr>
                  <td colSpan={14} className="vm-empty-cell">暂无数据</td>
                </tr>
              ) : (
                paged.map((row) => (
                  <tr key={row.id}>
                    <td>
                      <button
                        type="button"
                        className="vm-link code"
                        onClick={() => onViewFaultDetail?.(record, row)}
                      >
                        {row.faultNo}
                      </button>
                    </td>
                    <td>
                      {row.resolutionStatus === '已解决' ? (
                        <StatusTag label="已解决" tone="green" />
                      ) : (
                        '—'
                      )}
                    </td>
                    <td>{row.plateNo}</td>
                    <td>{row.brand}</td>
                    <td className="ellipsis" title={row.model}>{row.model}</td>
                    <td className="ellipsis" title={row.operateCompany || undefined}>
                      {formatFaultCell(row.operateCompany)}
                    </td>
                    <td>
                      <StatusTag label={row.faultLevel} tone={faultLevelTone(row.faultLevel)} />
                    </td>
                    <td>{row.faultType}</td>
                    <td className="ellipsis" title={row.faultDescription}>{row.faultDescription}</td>
                    <td>{row.reportedAt}</td>
                    <td>{formatFaultCell(row.resolvedAt)}</td>
                    <td>
                      <span className={row.aiMatched ? 'vm-fault-ai-yes' : undefined}>
                        {formatAiMatched(row.aiMatched)}
                      </span>
                    </td>
                    <td>{row.lastOperator}</td>
                    <td>
                      <div className="vm-table-actions">
                        <button
                          type="button"
                          className="vm-link"
                          onClick={() => onViewFaultDetail?.(record, row)}
                        >
                          查看详情
                        </button>
                        <button
                          type="button"
                          className="vm-link"
                          onClick={() => onEditFaultRecord?.(record, row)}
                        >
                          编辑
                        </button>
                      </div>
                    </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>
  );
}
