import React, { useEffect, useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { LeaseBusinessDetailRow, LeaseDetailFilters } from '../types';
import { FilterPickerField } from '../../vehicle-management/components/FilterPickerField';
import { MultiPlateFilterField } from '../../vehicle-management/components/MultiPlateFilterField';
import { buildDetailMonthOptions, buildDetailOptions } from '../utils/detail';
import { DETAIL_PAYMENT_STATUS_OPTIONS } from '../utils/payment-status';

const PRIMARY_KEYS = ['statMonth', 'businessDept', 'salesperson', 'customerName', 'paymentStatus'] as const;
const EXTRA_KEYS = ['plateNos'] as const;

type FieldKey = (typeof PRIMARY_KEYS)[number] | (typeof EXTRA_KEYS)[number];

interface FilterFieldDef {
  key: FieldKey;
  label: string;
  control: React.ReactNode;
}

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

function hasExtraFiltersActive(filters: LeaseDetailFilters): boolean {
  return filters.plateNos.length > 0;
}

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

  useEffect(() => {
    if (hasExtraFiltersActive(filters)) setExpanded(true);
  }, [filters.plateNos]);

  const monthOptions = useMemo(() => buildDetailMonthOptions(records), [records]);
  const deptOptions = useMemo(() => buildDetailOptions(records, 'businessDept'), [records]);
  const salespersonOptions = useMemo(() => buildDetailOptions(records, 'salesperson'), [records]);

  const fieldMap = useMemo<Record<FieldKey, FilterFieldDef>>(() => ({
    statMonth: {
      key: 'statMonth',
      label: '统计月份',
      control: (
        <FilterPickerField
          value={filters.statMonth}
          options={monthOptions}
          placeholder="全部月份"
          ariaLabel="统计月份"
          onChange={(statMonth) => onChange({ statMonth })}
        />
      ),
    },
    businessDept: {
      key: 'businessDept',
      label: '业务部门',
      control: (
        <FilterPickerField
          value={filters.businessDept}
          options={deptOptions}
          placeholder="全部部门"
          ariaLabel="业务部门"
          onChange={(businessDept) => onChange({ businessDept })}
        />
      ),
    },
    salesperson: {
      key: 'salesperson',
      label: '业务员',
      control: (
        <FilterPickerField
          value={filters.salesperson}
          options={salespersonOptions}
          placeholder="全部业务员"
          ariaLabel="业务员"
          onChange={(salesperson) => onChange({ salesperson })}
        />
      ),
    },
    customerName: {
      key: 'customerName',
      label: '客户名称',
      control: (
        <input
          className="vm-input"
          value={filters.customerName}
          placeholder="输入客户名称（模糊匹配）"
          aria-label="客户名称"
          onChange={(e) => onChange({ customerName: e.target.value })}
        />
      ),
    },
    paymentStatus: {
      key: 'paymentStatus',
      label: '状态',
      control: (
        <FilterPickerField
          value={filters.paymentStatus}
          options={DETAIL_PAYMENT_STATUS_OPTIONS}
          placeholder="全部状态"
          ariaLabel="状态"
          onChange={(paymentStatus) => onChange({ paymentStatus })}
        />
      ),
    },
    plateNos: {
      key: 'plateNos',
      label: '车牌号码',
      control: (
        <MultiPlateFilterField
          value={filters.plateNos}
          placeholder="点击输入多个车牌"
          ariaLabel="车牌号码"
          onChange={(plateNos) => onChange({ plateNos })}
        />
      ),
    },
  }), [filters, onChange, monthOptions, deptOptions, salespersonOptions]);

  const primaryFields = PRIMARY_KEYS.map((key) => fieldMap[key]);
  const extraFields = EXTRA_KEYS.map((key) => fieldMap[key]);
  const extraActiveCount = filters.plateNos.length > 0 ? 1 : 0;

  const renderField = (field: FilterFieldDef) => (
    <label key={field.key} className="vm-filter-field">
      <span>{field.label}</span>
      {field.control}
    </label>
  );

  return (
    <section
      className="vm-filter-card ldb-filter-card"
      data-annotation-id="lbd-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(renderField)}
        </div>

        <div
          className={`ldb-filter-expand ${expanded ? 'is-expanded' : ''}`}
          aria-hidden={!expanded}
          id="lbd-filter-expand-panel"
        >
          <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(renderField) : null}
            </div>
          </div>
        </div>
      </div>

      <div className="vm-filter-actions ldb-filter-actions">
        <button
          type="button"
          className="vm-btn vm-btn-link ldb-filter-toggle"
          onClick={() => setExpanded(!expanded)}
          aria-expanded={expanded}
          aria-controls="lbd-filter-expand-panel"
        
          data-vm-icon={expanded ? 'chevron-up' : 'filter'}>
          {expanded ? '收起' : '更多筛选'}
          {extraActiveCount > 0 && !expanded ? (
            <span className="ldb-filter-toggle-badge" aria-label="已设置扩展筛选">
              {extraActiveCount}
            </span>
          ) : null}
          </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>
  );
}
