import React, { useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { SupplierFilters, SupplierRecord } from '../types';
import { FilterPickerField } from '../../vehicle-management/components/FilterPickerField';
import { MultiSelectField } from '../../customer-management/components/MultiSelectField';
import {
  COOP_STATUS_OPTIONS,
  REGION_OPTIONS,
  SUPPLIER_TYPE_OPTIONS,
} from '../utils/constants';
import { buildCodeOptions, buildOptions } from '../utils/filters';

const DEFAULT_VISIBLE_COUNT = 4;

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

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

  const codeOptions = useMemo(() => buildCodeOptions(records), [records]);
  const nameOptions = useMemo(() => buildOptions(records, 'supplierName'), [records]);
  const cityOptions = useMemo(() => buildOptions(records, 'city'), [records]);
  const creatorOptions = useMemo(() => buildOptions(records, 'creator'), [records]);

  const codePickerOptions = codeOptions.map((item) => item.label);
  const codeLabelToValue = useMemo(
    () => Object.fromEntries(codeOptions.map((item) => [item.label, item.value])),
    [codeOptions],
  );
  const codeValueToLabel = useMemo(
    () => Object.fromEntries(codeOptions.map((item) => [item.value, item.label])),
    [codeOptions],
  );

  const fields = [
    {
      label: '供应商名称',
      control: (
        <>
          <input
            className="vm-input"
            value={filters.nameKeyword}
            placeholder="请选择或输入供应商名称"
            aria-label="供应商名称"
            list="sm-supplier-name-options"
            onChange={(event) => onChange({ nameKeyword: event.target.value })}
          />
          <datalist id="sm-supplier-name-options">
            {nameOptions.map((name) => (
              <option key={name} value={name} />
            ))}
          </datalist>
        </>
      ),
    },
    {
      label: '供应商编码',
      control: (
        <FilterPickerField
          value={filters.code ? (codeValueToLabel[filters.code] ?? '') : ''}
          options={codePickerOptions}
          placeholder="请选择或搜索供应商编码"
          ariaLabel="供应商编码"
          onChange={(label) => onChange({ code: codeLabelToValue[label] ?? '' })}
        />
      ),
    },
    {
      label: '合作状态',
      control: (
        <MultiSelectField
          values={filters.coopStatuses}
          options={[...COOP_STATUS_OPTIONS]}
          placeholder="请选择合作状态"
          ariaLabel="合作状态"
          onChange={(coopStatuses) => onChange({ coopStatuses: coopStatuses as SupplierFilters['coopStatuses'] })}
        />
      ),
    },
    {
      label: '类型',
      control: (
        <MultiSelectField
          values={filters.types}
          options={[...SUPPLIER_TYPE_OPTIONS]}
          placeholder="请选择供应商类型"
          ariaLabel="类型"
          onChange={(types) => onChange({ types: types as SupplierFilters['types'] })}
        />
      ),
    },
    {
      label: '区域',
      control: (
        <MultiSelectField
          values={filters.regions}
          options={[...REGION_OPTIONS]}
          placeholder="请选择区域"
          ariaLabel="区域"
          onChange={(regions) => onChange({ regions })}
        />
      ),
    },
    {
      label: '城市',
      control: (
        <FilterPickerField
          value={filters.city}
          options={cityOptions}
          placeholder="请选择城市"
          ariaLabel="城市"
          onChange={(city) => onChange({ city })}
        />
      ),
    },
    {
      label: '创建人',
      control: (
        <FilterPickerField
          value={filters.creator}
          options={creatorOptions}
          placeholder="请选择创建人"
          ariaLabel="创建人"
          onChange={(creator) => onChange({ creator })}
        />
      ),
    },
  ];

  const visibleFields = expanded ? fields : fields.slice(0, DEFAULT_VISIBLE_COUNT);

  return (
    <section className="vm-filter-card sm-filter-card" data-annotation-id="sm-list-filter">
      <header className="vm-filter-header">
        <h2 className="vm-filter-title">筛选条件</h2>
      </header>
      <div className="vm-filter-grid">
        {visibleFields.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_COUNT && (
          <button
            type="button"
            className="vm-btn vm-btn-link"
            onClick={() => setExpanded(!expanded)}
          >
            {expanded ? '收起' : '更多筛选'}
            <ChevronDown
              size={14}
              aria-hidden
              style={{ transform: expanded ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s' }}
            />
          </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>
  );
}
