import React, { useCallback, useMemo, useRef, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import type { VehicleFilters, VehicleRecord } from '../types';
import { buildOptions } from '../utils/filters';
import { OperateCityField } from './OperateCityField';
import { FilterPickerField } from './FilterPickerField';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';
import { parseMultiPlates } from '../utils/vehicle';
import { OPERATE_STATUS_OPTIONS, PROJECT_TYPE_OPTIONS, VEHICLE_SOURCE_OPTIONS } from '../utils/vehicle';

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

export function FilterPanel({
  records,
  filters,
  onChange,
  onReset,
  onSearch,
}: FilterPanelProps) {
  const [expanded, setExpanded] = useState(false);
  const [plateOpen, setPlateOpen] = useState(false);
  const [plateDraft, setPlateDraft] = useState('');
  const plateFieldRef = useRef<HTMLDivElement>(null);

  const dismissPlate = useCallback(() => {
    setPlateOpen(false);
  }, []);

  useDismissOnFocusOutside(plateOpen, plateFieldRef, dismissPlate);

  const brands = useMemo(() => buildOptions(records, 'brand'), [records]);
  const models = useMemo(() => buildOptions(records, 'model'), [records]);
  const customers = useMemo(() => buildOptions(records, 'customer'), [records]);
  const departments = useMemo(() => buildOptions(records, 'department'), [records]);
  const projects = useMemo(() => buildOptions(records, 'projectName'), [records]);
  const contracts = useMemo(() => buildOptions(records, 'contractNo'), [records]);
  const ownerships = useMemo(() => buildOptions(records, 'ownership'), [records]);
  const companies = useMemo(() => buildOptions(records, 'operateCompany'), [records]);
  const leases = useMemo(() => buildOptions(records, 'leaseCompany'), [records]);
  const parkings = useMemo(() => buildOptions(records, 'parking'), [records]);

  const plateSummary = filters.plateNos.length <= 2
    ? filters.plateNos.join('、')
    : filters.plateNos.length > 0
      ? `已选 ${filters.plateNos.length} 个车牌`
      : '';

  const renderPicker = (
    fieldKey: keyof VehicleFilters,
    label: string,
    options: string[],
    placeholder: string,
  ) => (
    <FilterPickerField
      value={String(filters[fieldKey] ?? '')}
      options={options}
      placeholder={placeholder}
      ariaLabel={label}
      onChange={(value) => onChange({ [fieldKey]: value } as Partial<VehicleFilters>)}
    />
  );

  const fields = [
    {
      label: '车牌号',
      control: (
        <div className="vm-plate-field" ref={plateFieldRef}>
          <button
            type="button"
            className="vm-input vm-plate-trigger"
            onClick={() => { setPlateDraft(filters.plateNos.join('\n')); setPlateOpen(true); }}
          >
            {plateSummary || <span className="placeholder">请选择或输入车牌号</span>}
            <ChevronDown size={14} aria-hidden />
          </button>
          {plateOpen && (
            <div className="vm-plate-popover">
              <textarea
                className="vm-input vm-plate-textarea"
                value={plateDraft}
                onChange={(e) => setPlateDraft(e.target.value)}
                placeholder="请输入车牌号，多个车牌跨行输入"
                rows={5}
              />
              <div className="vm-plate-popover-actions">
                <button type="button" className="vm-btn vm-btn-ghost" onClick={() => setPlateOpen(false)}>取消</button>
                <button
                  type="button"
                  className="vm-btn vm-btn-primary"
                  onClick={() => {
                    onChange({ plateNos: parseMultiPlates(plateDraft) });
                    setPlateOpen(false);
                  }}
                >
                  确认
                </button>
              </div>
            </div>
          )}
        </div>
      ),
    },
    {
      label: '运营城市',
      control: (
        <OperateCityField
          records={records}
          value={filters.operateCities}
          onChange={(operateCities) => onChange({ operateCities })}
        />
      ),
    },
    {
      label: '品牌',
      control: renderPicker('brand', '品牌', brands, '请选择品牌'),
    },
    {
      label: '型号',
      control: renderPicker('model', '型号', models, '请选择型号'),
    },
    {
      label: '客户名称',
      control: renderPicker('customer', '客户名称', customers, '请选择或输入客户名称'),
    },
    {
      label: '归属业务部门',
      control: renderPicker('department', '归属业务部门', departments, '请选择归属业务部门'),
    },
    {
      label: '项目名称',
      control: renderPicker('projectName', '项目名称', projects, '请选择或输入项目名称'),
    },
    {
      label: '项目类型',
      control: renderPicker('projectType', '项目类型', PROJECT_TYPE_OPTIONS, '请选择项目类型'),
    },
    {
      label: '合同编码',
      control: renderPicker('contractNo', '合同编码', contracts, '请选择或输入合同编码'),
    },
    {
      label: '登记所有权',
      control: renderPicker('ownership', '登记所有权', ownerships, '请选择登记所有权'),
    },
    {
      label: '运营公司',
      control: renderPicker('operateCompany', '运营公司', companies, '请选择或输入运营公司'),
    },
    {
      label: '运营状态',
      control: renderPicker('operateStatus', '运营状态', OPERATE_STATUS_OPTIONS, '请选择运营状态'),
    },
    {
      label: '车辆来源',
      control: renderPicker('vehicleSource', '车辆来源', VEHICLE_SOURCE_OPTIONS, '请选择车辆来源'),
    },
    {
      label: '租赁公司',
      control: renderPicker('leaseCompany', '租赁公司', leases, '请选择或搜索租赁公司'),
    },
    {
      label: '停车场',
      control: renderPicker('parking', '停车场', parkings, '请选择或输入停车场'),
    },
  ];

  const visible = expanded ? fields : fields.slice(0, 4);

  return (
    <section className="vm-filter-card">
      <header className="vm-filter-header">
        <h2 className="vm-filter-title">筛选条件</h2>
      </header>
      <div className="vm-filter-grid">
        {visible.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 > 4 && (
          <button type="button" className="vm-btn vm-btn-link" onClick={() => setExpanded(!expanded)}>
            {expanded ? '收起' : '展开更多筛选项'}
          </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>
  );
}
