import React, { useEffect, useMemo, useState } from 'react';
import { ChevronDown, Search } from 'lucide-react';
import { DatePicker, Select } from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import {
  shouldShowFilterExpand,
  splitFilterFields,
  VM_FILTER_PRIMARY_VISIBLE_COUNT,
} from '../../../common/vm-filter-panel';
import type { PaymentRecord, PaymentRecordFilters } from '../types';
import { buildBankOptions, buildCompanyEntityOptions, buildCustomerOptions, buildOperatorOptions } from '../utils/payment';

const { RangePicker } = DatePicker;

const DATE_FORMAT = 'YYYY-MM-DD';

const UNCLAIMED_OPTIONS = [
  { value: '', label: '全部' },
  { value: 'yes', label: '有未关联' },
  { value: 'no', label: '已全部关联' },
];

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

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

function hasExtraFiltersActive(filters: PaymentRecordFilters): boolean {
  return Boolean(filters.operatorName.trim() || filters.unclaimed);
}

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

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

  const customerOptions = useMemo(() => buildCustomerOptions(records), [records]);
  const companyEntityOptions = useMemo(() => buildCompanyEntityOptions(records), [records]);
  const bankOptions = useMemo(() => buildBankOptions(records), [records]);
  const operatorOptions = useMemo(
    () => buildOperatorOptions(records).map((name) => ({ value: name, label: name })),
    [records],
  );

  const dateRangeValue = useMemo((): [Dayjs, Dayjs] | null => {
    if (!filters.paymentFrom && !filters.paymentTo) return null;
    const from = filters.paymentFrom ? dayjs(filters.paymentFrom) : null;
    const to = filters.paymentTo ? dayjs(filters.paymentTo) : null;
    if (from?.isValid() && to?.isValid()) return [from, to];
    return null;
  }, [filters.paymentFrom, filters.paymentTo]);

  const fields = useMemo<FilterFieldDef[]>(() => [
    {
      key: 'customerName',
      label: '汇款账户名',
      control: (
        <Select
          placeholder="请选择或输入汇款账户名"
          style={{ width: '100%' }}
          value={filters.customerName || undefined}
          onChange={(value) => onChange({ customerName: value || '' })}
          allowClear
          showSearch
          options={customerOptions}
          filterOption={(input, option) =>
            (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
        />
      ),
    },
    {
      key: 'companyEntity',
      label: '公司主体',
      control: (
        <Select
          placeholder="请选择公司主体"
          style={{ width: '100%' }}
          value={filters.companyEntity || undefined}
          onChange={(value) => onChange({ companyEntity: value || '' })}
          allowClear
          showSearch
          options={companyEntityOptions}
          filterOption={(input, option) =>
            (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
        />
      ),
    },
    {
      key: 'bank',
      label: '银行',
      control: (
        <Select
          placeholder="请选择收款银行"
          style={{ width: '100%' }}
          value={filters.bank || undefined}
          onChange={(value) => onChange({ bank: value || '' })}
          allowClear
          showSearch
          options={bankOptions}
          filterOption={(input, option) =>
            (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
        />
      ),
    },
    {
      key: 'paymentTime',
      label: '收款时间',
      control: (
        <RangePicker
          className="lc-filter-select pr-payment-range"
          style={{ width: '100%' }}
          picker="date"
          showTime={false}
          format={DATE_FORMAT}
          separator="至"
          placeholder={['开始日期', '结束日期']}
          allowClear
          inputReadOnly
          value={dateRangeValue}
          onChange={(values) => {
            onChange({
              paymentFrom: values?.[0]?.format(DATE_FORMAT) ?? '',
              paymentTo: values?.[1]?.format(DATE_FORMAT) ?? '',
            });
          }}
        />
      ),
    },
    {
      key: 'operatorName',
      label: '操作人',
      control: (
        <Select
          placeholder="全部操作人"
          style={{ width: '100%' }}
          value={filters.operatorName || undefined}
          onChange={(value) => onChange({ operatorName: value || '' })}
          allowClear
          showSearch
          options={operatorOptions}
          filterOption={(input, option) =>
            (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
        />
      ),
    },
    {
      key: 'unclaimed',
      label: '未关联',
      control: (
        <Select
          placeholder="全部"
          style={{ width: '100%' }}
          value={filters.unclaimed || undefined}
          onChange={(value) => onChange({ unclaimed: (value ?? '') as PaymentRecordFilters['unclaimed'] })}
          allowClear
          options={UNCLAIMED_OPTIONS.filter((o) => o.value !== '')}
        />
      ),
    },
  ], [
    bankOptions,
    companyEntityOptions,
    customerOptions,
    dateRangeValue,
    filters,
    onChange,
    operatorOptions,
  ]);

  const { primary, extra } = splitFilterFields(fields, VM_FILTER_PRIMARY_VISIBLE_COUNT);
  const showExpand = shouldShowFilterExpand(fields.length);
  const extraActiveCount = [filters.operatorName.trim(), filters.unclaimed].filter(Boolean).length;
  const expandPanelId = 'pr-filter-expand-panel';

  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" data-annotation-id="pr-filter" aria-label="筛选条件">
      <header className="vm-filter-header">
        <h2 className="vm-filter-title">筛选条件</h2>
      </header>

      <div className="vm-filter-body">
        <div className="vm-filter-grid vm-filter-grid--primary" data-filter-tier="primary">
          {primary.map(renderField)}
        </div>

        {showExpand ? (
          <div
            className={`vm-filter-expand ${expanded ? 'is-expanded' : ''}`}
            aria-hidden={!expanded}
            id={expandPanelId}
          >
            <div className="vm-filter-expand-inner">
              <div className="vm-filter-grid vm-filter-expand-grid" data-filter-tier="extra">
                {expanded ? extra.map(renderField) : null}
              </div>
            </div>
          </div>
        ) : null}
      </div>

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