import React, { useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { LeaseLedgerFilters, LeaseLedgerRow } from '../types';
import { FilterPickerField } from '../../vehicle-management/components/FilterPickerField';
import { buildLeaseOptions } from '../utils/ledger';

const STATUS_OPTIONS = ['草稿', '已确认', '部分收款', '已收款'];
const DEFAULT_VISIBLE = 4;

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

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

  const yearOptions = useMemo(() => buildLeaseOptions(records, 'year'), [records]);
  const monthOptions = useMemo(() => buildLeaseOptions(records, 'month'), [records]);
  const deptOptions = useMemo(() => buildLeaseOptions(records, 'dept'), [records]);
  const salesmanOptions = useMemo(() => buildLeaseOptions(records, 'salesman'), [records]);
  const plateOptions = useMemo(() => buildLeaseOptions(records, 'plateNo'), [records]);

  const fields = [
    { label: '年份', control: <FilterPickerField value={filters.year} options={yearOptions} placeholder="全部年份" ariaLabel="年份" onChange={(year) => onChange({ year })} /> },
    { label: '月份', control: <FilterPickerField value={filters.month} options={monthOptions} placeholder="全部月份" ariaLabel="月份" onChange={(month) => onChange({ month })} /> },
    { label: '业务部门', control: <FilterPickerField value={filters.dept} options={deptOptions} placeholder="全部部门" ariaLabel="业务部门" onChange={(dept) => onChange({ dept })} /> },
    { label: '业务员', control: <FilterPickerField value={filters.salesman} options={salesmanOptions} placeholder="全部业务员" ariaLabel="业务员" onChange={(salesman) => onChange({ salesman })} /> },
    { label: '车牌号码', control: <FilterPickerField value={filters.plateNo} options={plateOptions} placeholder="全部车牌" ariaLabel="车牌号码" onChange={(plateNo) => onChange({ plateNo })} /> },
    { label: '客户名称', control: <input className="vm-input" value={filters.customerName} placeholder="输入客户名称" aria-label="客户名称" onChange={(e) => onChange({ customerName: e.target.value })} /> },
    { label: '明细状态', control: <FilterPickerField value={filters.status} options={STATUS_OPTIONS} placeholder="全部状态" ariaLabel="明细状态" onChange={(status) => onChange({ status })} /> },
    { label: '付款日期', control: (
        <div className="ldb-date-range">
          <input type="date" className="vm-input" value={filters.paymentFrom} aria-label="付款开始日期" onChange={(e) => onChange({ paymentFrom: e.target.value })} />
          <span className="ldb-date-range-sep" aria-hidden>至</span>
          <input type="date" className="vm-input" value={filters.paymentTo} aria-label="付款结束日期" onChange={(e) => onChange({ paymentTo: e.target.value })} />
        </div>
      ),
    },
  ];

  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="lbl-filter">
      <header className="vm-filter-header">
        <h1 className="ldb-page-title">租赁业务台账</h1>
      </header>
      <div className="vm-filter-grid">
        {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' : ''}`}>
          <div className="ldb-filter-expand-inner">
            <div className="vm-filter-grid ldb-filter-expand-grid">
              {extraFields.map((field) => (
                <label key={field.label} className="vm-filter-field">
                  <span>{field.label}</span>
                  {field.control}
                </label>
              ))}
            </div>
          </div>
        </div>
      )}
      <div className="vm-filter-actions">
        {extraFields.length > 0 && (
          <button type="button" className="vm-btn vm-btn-link ldb-filter-toggle" onClick={() => setExpanded(!expanded)} aria-expanded={expanded}>
            {expanded ? '收起' : '更多筛选'}
            <ChevronDown size={14} aria-hidden className={`ldb-filter-toggle-icon ${expanded ? 'is-open' : ''}`} />
          </button>
        )}
        <button type="button" className="vm-btn vm-btn-ghost ldb-toolbar-btn" onClick={onReset}>重置</button>
        <button type="button" className="vm-btn vm-btn-primary ldb-toolbar-btn" onClick={onSearch}>
          <Search size={16} aria-hidden />
          查询
        </button>
      </div>
    </section>
  );
}
