import React, { useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { CustomerFilters, CustomerRecord } from '../types';
import { FilterPickerField } from '../../vehicle-management/components/FilterPickerField';
import {
  CUSTOMER_LABEL_OPTIONS,
  CUSTOMER_STATUS_OPTIONS,
  REGION_OPTIONS,
} from '../utils/constants';
import {
  buildCodeOptions,
  buildDeptManagerMap,
  buildOptions,
  getManagerOptions,
} from '../utils/filters';
import { MultiSelectField } from './MultiSelectField';

const DEFAULT_VISIBLE_COUNT = 4;

interface FilterPanelProps {
  records: CustomerRecord[];
  filters: CustomerFilters;
  onChange: (patch: Partial<CustomerFilters>) => 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, 'name'), [records]);
  const departmentOptions = useMemo(() => buildOptions(records, 'department'), [records]);
  const deptManagerMap = useMemo(() => buildDeptManagerMap(records), [records]);
  const managerOptions = useMemo(
    () => getManagerOptions(deptManagerMap, filters.departments),
    [deptManagerMap, filters.departments],
  );

  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 handleDeptChange = (departments: string[]) => {
    const allowed = getManagerOptions(deptManagerMap, departments);
    onChange({
      departments,
      managers: filters.managers.filter((manager) => allowed.includes(manager)),
    });
  };

  const fields = [
    {
      label: '客户编号',
      control: (
        <FilterPickerField
          value={filters.code ? (codeValueToLabel[filters.code] ?? '') : ''}
          options={codePickerOptions}
          placeholder="请选择或搜索客户编号"
          ariaLabel="客户编号"
          onChange={(label) => onChange({ code: codeLabelToValue[label] ?? '' })}
        />
      ),
    },
    {
      label: '客户名称',
      control: (
        <FilterPickerField
          value={filters.name}
          options={nameOptions}
          placeholder="请选择或搜索客户名称"
          ariaLabel="客户名称"
          onChange={(name) => onChange({ name })}
        />
      ),
    },
    {
      label: '标签',
      control: (
        <MultiSelectField
          values={filters.labels}
          options={[...CUSTOMER_LABEL_OPTIONS]}
          placeholder="请选择标签"
          ariaLabel="标签"
          onChange={(labels) => onChange({ labels })}
        />
      ),
    },
    {
      label: '区域',
      control: (
        <FilterPickerField
          value={filters.region}
          options={[...REGION_OPTIONS]}
          placeholder="请选择客户区域"
          ariaLabel="区域"
          onChange={(region) => onChange({ region })}
        />
      ),
    },
    {
      label: '客户状态',
      control: (
        <MultiSelectField
          values={filters.statuses}
          options={[...CUSTOMER_STATUS_OPTIONS]}
          placeholder="请选择客户状态"
          ariaLabel="客户状态"
          onChange={(statuses) => onChange({ statuses: statuses as CustomerFilters['statuses'] })}
        />
      ),
    },
    {
      label: '业务部门',
      control: (
        <MultiSelectField
          values={filters.departments}
          options={departmentOptions}
          placeholder="请选择业务部门"
          ariaLabel="业务部门"
          onChange={handleDeptChange}
        />
      ),
    },
    {
      label: '业务负责人',
      control: (
        <MultiSelectField
          values={filters.managers}
          options={managerOptions}
          placeholder="请选择业务负责人"
          ariaLabel="业务负责人"
          onChange={(managers) => onChange({ managers })}
        />
      ),
    },
    {
      label: '创建时间',
      control: (
        <div className="cm-date-range">
          <input
            type="date"
            className="vm-input cm-date-input"
            value={filters.createFrom}
            onChange={(event) => onChange({ createFrom: event.target.value })}
            aria-label="创建开始日期"
          />
          <span className="cm-date-sep" aria-hidden>—</span>
          <input
            type="date"
            className="vm-input cm-date-input"
            value={filters.createTo}
            onChange={(event) => onChange({ createTo: event.target.value })}
            aria-label="创建结束日期"
          />
        </div>
      ),
    },
  ];

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

  return (
    <section className="vm-filter-card cm-filter-card" data-annotation-id="cm-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 cm-filter-actions">
        {fields.length > DEFAULT_VISIBLE_COUNT && (
          <button
            type="button"
            className="vm-btn vm-btn-link"
            onClick={() => setExpanded(!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>
  );
}
