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 { DateRangeFilterField } from '../../vehicle-management/components/DateRangeFilterField';
import { MultiSelectField } from '../../customer-management/components/MultiSelectField';
import { buildMonthFilterOptions, buildSelfOptions, buildSystemVehicleTypeOptions } from '../utils/ledger';

const DEFAULT_VISIBLE = 4;

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(() => buildMonthFilterOptions(records), [records]);
  const businessOptions = useMemo(() => buildSelfOptions(records, 'businessName'), [records]);
  const plateOptions = useMemo(() => buildSelfOptions(records, 'plateNo'), [records]);
  const systemVehicleTypeOptions = useMemo(() => buildSystemVehicleTypeOptions(records), [records]);

  const fields = [
    { label: '月份', control: <FilterPickerField value={filters.month} options={monthOptions} placeholder="全部月份" ariaLabel="月份" onChange={(month) => onChange({ month })} /> },
    {
      label: '出车日期',
      control: (
        <DateRangeFilterField
          startDate={filters.dispatchFrom}
          endDate={filters.dispatchTo}
          ariaLabel="出车日期"
          startPlaceholder="开始日期"
          endPlaceholder="结束日期"
          onChange={({ startDate, endDate }) => onChange({ dispatchFrom: startDate, dispatchTo: endDate })}
        />
      ),
    },
    { 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.systemVehicleType}
          options={systemVehicleTypeOptions}
          placeholder="全部车型"
          ariaLabel="系统车型"
          onChange={(systemVehicleType) => onChange({ systemVehicleType })}
        />
      ),
    },
  ];

  const primaryFields = fields.slice(0, DEFAULT_VISIBLE);
  const extraFields = fields.slice(DEFAULT_VISIBLE);

  return (
    <section className="vm-filter-card ldb-filter-card" data-annotation-id="sob-filter" aria-label="筛选条件">
      <header className="vm-filter-header">
        <h2 className="vm-filter-title">筛选条件</h2>
      </header>

      <div className="ldb-filter-body">
        <div className="vm-filter-grid ldb-filter-grid ldb-filter-grid--primary" data-filter-tier="primary">
          {primaryFields.map((field) => (
            <label key={field.label} className="vm-filter-field">
              <span>{field.label}</span>
              {field.control}
            </label>
          ))}
        </div>

        {extraFields.length > 0 && (
          <div className={`ldb-filter-expand ${expanded ? 'is-expanded' : ''}`} aria-hidden={!expanded}>
            <div className="ldb-filter-expand-inner">
              <div className="vm-filter-grid ldb-filter-grid ldb-filter-expand-grid" data-filter-tier="extra">
                {expanded
                  ? extraFields.map((field) => (
                    <label key={field.label} className="vm-filter-field">
                      <span>{field.label}</span>
                      {field.control}
                    </label>
                  ))
                  : null}
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="vm-filter-actions ldb-filter-actions">
        {extraFields.length > 0 && (
          <button
            type="button"
            className="vm-btn vm-btn-link ldb-filter-toggle"
            onClick={() => setExpanded(!expanded)}
            aria-expanded={expanded}
            data-vm-icon={expanded ? 'chevron-up' : 'filter'}>
            {expanded ? '收起' : '更多筛选'}
            </button>
        )}
        <button type="button" className="vm-btn vm-btn-ghost ldb-toolbar-btn" onClick={onReset} data-vm-icon="rotate-ccw">重置</button>
        <button type="button" className="vm-btn vm-btn-primary ldb-toolbar-btn" onClick={onSearch} data-vm-icon="search">查询
        </button>
      </div>
    </section>
  );
}
