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

const STATUS_OPTIONS = ['未收款', '部分收款', '已收款'];

/** PRD §2：默认首行 4 项 */
const PRIMARY_FIELD_KEYS = ['year', 'month', 'dept', 'salesman'] as const;
/** PRD §2：「更多筛选」展开其余 4 项 */
const EXTRA_FIELD_KEYS = ['plateNos', 'customerName', 'status', 'paymentDue'] as const;

type FieldKey = (typeof PRIMARY_FIELD_KEYS)[number] | (typeof EXTRA_FIELD_KEYS)[number];

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

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

function hasExtraFiltersActive(filters: LeaseLedgerFilters): boolean {
  return Boolean(
    filters.plateNos.length > 0
    || filters.customerName.trim()
    || filters.status
    || filters.paymentFrom
    || filters.paymentTo,
  );
}

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

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

  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 fieldMap = useMemo<Record<FieldKey, FilterFieldDef>>(() => ({
    year: {
      key: 'year',
      label: '年份',
      control: (
        <FilterPickerField
          value={filters.year}
          options={yearOptions}
          placeholder="全部年份"
          ariaLabel="年份"
          onChange={(year) => onChange({ year })}
        />
      ),
    },
    month: {
      key: 'month',
      label: '月份',
      control: (
        <FilterPickerField
          value={filters.month}
          options={monthOptions}
          placeholder="全部月份"
          ariaLabel="月份"
          onChange={(month) => onChange({ month })}
        />
      ),
    },
    dept: {
      key: 'dept',
      label: '业务部门',
      control: (
        <FilterPickerField
          value={filters.dept}
          options={deptOptions}
          placeholder="全部部门"
          ariaLabel="业务部门"
          onChange={(dept) => onChange({ dept })}
        />
      ),
    },
    salesman: {
      key: 'salesman',
      label: '业务员',
      control: (
        <FilterPickerField
          value={filters.salesman}
          options={salesmanOptions}
          placeholder="全部业务员"
          ariaLabel="业务员"
          onChange={(salesman) => onChange({ salesman })}
        />
      ),
    },
    plateNos: {
      key: 'plateNos',
      label: '车牌号码',
      control: (
        <MultiPlateFilterField
          value={filters.plateNos}
          placeholder="点击输入多个车牌"
          ariaLabel="车牌号码"
          onChange={(plateNos) => onChange({ plateNos })}
        />
      ),
    },
    customerName: {
      key: 'customerName',
      label: '客户名称',
      control: (
        <input
          className="vm-input"
          value={filters.customerName}
          placeholder="输入客户名称（模糊匹配）"
          aria-label="客户名称"
          onChange={(e) => onChange({ customerName: e.target.value })}
        />
      ),
    },
    status: {
      key: 'status',
      label: '明细状态',
      control: (
        <FilterPickerField
          value={filters.status}
          options={STATUS_OPTIONS}
          placeholder="全部状态"
          ariaLabel="明细状态"
          onChange={(status) => onChange({ status })}
        />
      ),
    },
    paymentDue: {
      key: 'paymentDue',
      label: '应付款日',
      control: (
        <DateRangeFilterField
          startDate={filters.paymentFrom}
          endDate={filters.paymentTo}
          ariaLabel="应付款日"
          startPlaceholder="开始日期"
          endPlaceholder="结束日期"
          onChange={({ startDate, endDate }) => onChange({ paymentFrom: startDate, paymentTo: endDate })}
        />
      ),
    },
  }), [
    filters,
    onChange,
    yearOptions,
    monthOptions,
    deptOptions,
    salesmanOptions,
  ]);

  const primaryFields = PRIMARY_FIELD_KEYS.map((key) => fieldMap[key]);
  const extraFields = EXTRA_FIELD_KEYS.map((key) => fieldMap[key]);
  const extraActiveCount = [
    filters.plateNos.length > 0,
    filters.customerName.trim(),
    filters.status,
    filters.paymentFrom || filters.paymentTo,
  ].filter(Boolean).length;

  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="lbl-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="ldb-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="ldb-filter-expand-panel"
        
          data-vm-icon={expanded ? 'chevron-up' : 'filter'}>
          {expanded ? '收起' : '更多筛选'}
          {extraActiveCount > 0 && !expanded ? (
            <span className="ldb-filter-toggle-badge" aria-label={`已设置 ${extraActiveCount} 项扩展筛选`}>
              {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>
  );
}
