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 {
  applyMovementRecordFilters,
  buildMovementRecordOptions,
  EMPTY_MOVEMENT_RECORD_FILTERS,
  formatMovementNumber,
  formatMovementPercent,
  movementStatusTone,
  resolveVehicleMovementRecords,
  type MovementRecordFilters,
  type MovementRecordRow,
} from '../utils/movementRecords';

interface DetailMovementRecordsTabProps {
  record: VehicleRecord;
  onOpenMovementDetail?: (record: VehicleRecord, row: MovementRecordRow) => void;
}

const DEFAULT_PAGE_SIZE = 10;

export function DetailMovementRecordsTab({
  record,
  onOpenMovementDetail,
}: DetailMovementRecordsTabProps) {
  const allRows = useMemo(() => resolveVehicleMovementRecords(record), [record]);
  const [pendingFilters, setPendingFilters] = useState<MovementRecordFilters>(EMPTY_MOVEMENT_RECORD_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<MovementRecordFilters>(EMPTY_MOVEMENT_RECORD_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const destinationOptions = useMemo(
    () => buildMovementRecordOptions(allRows, 'destinationType'),
    [allRows],
  );
  const movementTypeOptions = useMemo(
    () => buildMovementRecordOptions(allRows, 'movementType'),
    [allRows],
  );

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

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

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

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

  return (
    <div className="vm-movement-records-tab">
      <div className="vm-detail-tab-filter">
        <div className="vm-detail-tab-filter-grid vm-detail-tab-filter-grid--movement">
          <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.destinationType}
              options={destinationOptions}
              placeholder="请选择异动目的地"
              ariaLabel="异动目的地"
              onChange={(value) => updatePending({ destinationType: value })}
            />
          </label>
          <label className="vm-filter-field">
            <span>异动类型</span>
            <FilterPickerField
              value={pendingFilters.movementType}
              options={movementTypeOptions}
              placeholder="请选择异动类型"
              ariaLabel="异动类型"
              onChange={(value) => updatePending({ movementType: 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--movement">
            <thead>
              <tr>
                <th>异动开始日期</th>
                <th>异动预计结束日期</th>
                <th>异动状态</th>
                <th>异动目的地</th>
                <th>目的地名称</th>
                <th>异动类型</th>
                <th>预计异动里程 (km)</th>
                <th>异动开始里程 (km)</th>
                <th>异动开始电量 (kWh)</th>
                <th>异动开始氢量</th>
                <th>异动结束里程 (km)</th>
                <th>异动结束电量 (kWh)</th>
                <th>异动结束氢量</th>
                <th>创建人</th>
                <th>创建时间</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 ? (
                <tr>
                  <td colSpan={15} className="vm-empty-cell">暂无数据</td>
                </tr>
              ) : (
                paged.map((row) => (
                  <tr key={row.id}>
                    <td>
                      <button
                        type="button"
                        className="vm-link"
                        onClick={() => onOpenMovementDetail?.(record, row)}
                      >
                        {row.startDate}
                      </button>
                    </td>
                    <td>{row.estimatedEndDate}</td>
                    <td>
                      <StatusTag label={row.status} tone={movementStatusTone(row.status)} />
                    </td>
                    <td>{row.destinationType}</td>
                    <td className="ellipsis" title={row.destinationName}>{row.destinationName}</td>
                    <td>{row.movementType}</td>
                    <td className="vm-table-num">{formatMovementNumber(row.estimatedMileageKm)}</td>
                    <td className="vm-table-num">{formatMovementNumber(row.startMileageKm)}</td>
                    <td className="vm-table-num">{formatMovementNumber(row.startBatteryKwh, 1)}</td>
                    <td className="vm-table-num">{formatMovementPercent(row.startHydrogenPct)}</td>
                    <td className="vm-table-num">{formatMovementNumber(row.endMileageKm)}</td>
                    <td className="vm-table-num">{formatMovementNumber(row.endBatteryKwh, 1)}</td>
                    <td className="vm-table-num">{formatMovementPercent(row.endHydrogenPct)}</td>
                    <td>{row.createdBy}</td>
                    <td>{row.createdAt}</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>
  );
}
