import React, { useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { SelfOperatedFilters, SelfOperatedLedgerRow } from '../types';
import { FilterPickerField } from '../../vehicle-management/components/FilterPickerField';
import { MultiSelectField } from '../../customer-management/components/MultiSelectField';
import { BRAND_MODEL_MAP, UNDERTAKER_OPTIONS, buildSelfOptions } from '../utils/ledger';

const DEFAULT_VISIBLE = 4;
const IS_SUPERVISOR = true;

interface FilterPanelProps {
  records: SelfOperatedLedgerRow[];
  filters: SelfOperatedFilters;
  onChange: (patch: Partial<SelfOperatedFilters>) => void;
  onReset: () => void;
  onSearch: () => void;
}

export function FilterPanel({ records, filters, onChange, onReset, onSearch }: FilterPanelProps) {
  const [expanded, setExpanded] = useState(false);

  const monthOptions = useMemo(() => buildSelfOptions(records, 'month'), [records]);
  const businessOptions = useMemo(() => buildSelfOptions(records, 'businessName'), [records]);
  const plateOptions = useMemo(() => buildSelfOptions(records, 'plateNo'), [records]);
  const brandOptions = useMemo(() => Object.keys(BRAND_MODEL_MAP), []);
  const modelOptions = useMemo(
    () => (filters.brand ? BRAND_MODEL_MAP[filters.brand] ?? [] : []),
    [filters.brand],
  );
  const maintainerOptions = useMemo(() => buildSelfOptions(records, 'maintainerName'), [records]);

  const fields = [
    { label: '月份', control: <FilterPickerField value={filters.month} options={monthOptions} placeholder="全部月份" ariaLabel="月份" onChange={(month) => onChange({ month })} /> },
    {
      label: '出车日期',
      control: (
        <div className="ldb-date-range">
          <input type="date" className="vm-input" value={filters.dispatchFrom} aria-label="出车开始日期" onChange={(e) => onChange({ dispatchFrom: e.target.value })} />
          <span aria-hidden>—</span>
          <input type="date" className="vm-input" value={filters.dispatchTo} aria-label="出车结束日期" onChange={(e) => onChange({ dispatchTo: e.target.value })} />
        </div>
      ),
    },
    { label: '业务名称', control: <FilterPickerField value={filters.businessName} options={businessOptions} placeholder="请选择业务名称" ariaLabel="业务名称" onChange={(businessName) => onChange({ businessName })} /> },
    { label: '车牌号码', control: <MultiSelectField values={filters.plateNos} options={plateOptions} placeholder="全部车牌" ariaLabel="车牌号码" onChange={(plateNos) => onChange({ plateNos })} /> },
    { label: '车辆承接方', control: <FilterPickerField value={filters.vehicleUndertaker} options={UNDERTAKER_OPTIONS} placeholder="全部" ariaLabel="车辆承接方" onChange={(vehicleUndertaker) => onChange({ vehicleUndertaker })} /> },
    {
      label: '品牌',
      control: (
        <FilterPickerField
          value={filters.brand}
          options={brandOptions}
          placeholder="全部品牌"
          ariaLabel="品牌"
          onChange={(brand) => onChange({ brand, model: '' })}
        />
      ),
    },
    {
      label: '型号',
      control: (
        <FilterPickerField
          value={filters.model}
          options={modelOptions}
          placeholder={filters.brand ? '全部型号' : '请先选择品牌'}
          ariaLabel="型号"
          onChange={(model) => onChange({ model })}
        />
      ),
    },
  ];

  if (IS_SUPERVISOR) {
    fields.push({
      label: '维护人',
      control: (
        <FilterPickerField
          value={filters.maintainerName}
          options={maintainerOptions}
          placeholder="全部维护人"
          ariaLabel="维护人"
          onChange={(maintainerName) => onChange({ maintainerName })}
        />
      ),
    });
  }

  const visible = expanded ? fields : fields.slice(0, DEFAULT_VISIBLE);

  return (
    <section className="vm-filter-card" data-annotation-id="sob-filter">
      <header className="vm-filter-header">
        <h1 className="ldb-page-title">自营业务台账</h1>
        <p className="ldb-page-desc">业务服务组操作人维护各自台账；主管可查看全部。支持导入、行内编辑与盈亏自动计算（原型演示）。</p>
      </header>
      <div className="vm-filter-grid">
        {visible.map((field) => (
          <label key={field.label} className="vm-filter-field">
            <span>{field.label}</span>
            {field.control}
          </label>
        ))}
      </div>
      <div className="vm-filter-actions">
        {fields.length > DEFAULT_VISIBLE && (
          <button type="button" className="vm-btn vm-btn-link" onClick={() => setExpanded(!expanded)}>
            {expanded ? '收起' : '更多筛选'}
            <ChevronDown size={14} aria-hidden style={{ transform: expanded ? 'rotate(180deg)' : undefined }} />
          </button>
        )}
        <button type="button" className="vm-btn vm-btn-ghost" onClick={onReset}>重置</button>
        <button type="button" className="vm-btn vm-btn-primary" onClick={onSearch}>
          <Search size={16} aria-hidden />
          查询
        </button>
      </div>
    </section>
  );
}
