/**
 * filekorolheader: 搜索表单组件 - 可配置的搜索条件表单
 * 功能：搜索条件输入、下拉选择、实时搜索、重置功能
 * 路径：/components/common/searchFormPagination/components/SearchFormComponent
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式，支持完全自定义
 */
'use client';

import { useState, useEffect, useRef, memo } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search } from 'lucide-react';

// 搜索字段配置接口
export interface SearchFieldConfig {
  key: string;
  type: 'text' | 'select';
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
  defaultValue?: string;
}

// 组件Props接口
export interface SearchFormComponentProps {
  fields: SearchFieldConfig[];
  filters: Record<string, string>;
  onFiltersChange: (filters: Record<string, string>) => void;
  placeholder?: string;
  loading?: boolean;
  layout?: 'horizontal' | 'vertical';
  maxVisibleFields?: number;
}

export function SearchFormComponent({
  fields,
  filters,
  onFiltersChange,
  placeholder = '请输入搜索关键词...',
  loading = false,
  layout = 'horizontal',
  maxVisibleFields = 3,
}: SearchFormComponentProps) {
  const [localFilters, setLocalFilters] = useState<Record<string, string>>(filters);
  const [showAllFields, setShowAllFields] = useState(false);

  // 使用ref保持最新的onFiltersChange引用，避免useEffect重复触发
  const onFiltersChangeRef = useRef(onFiltersChange);
  onFiltersChangeRef.current = onFiltersChange;

  // 同步外部filters到本地state
  useEffect(() => {
    setLocalFilters(filters);
  }, [filters]);

  // 处理输入变化 - 区分文本输入和下拉选择
  const handleInputChange = (key: string, value: string, fieldType: 'text' | 'select') => {
    const newFilters = {
      ...localFilters,
      [key]: value,
    };
    setLocalFilters(newFilters);

    // 下拉框选择立即触发查询，文本输入使用防抖
    if (fieldType === 'select') {
      onFiltersChangeRef.current(newFilters);
    }
    // 文本输入的防抖在useEffect中处理
  };

  // 使用防抖来减少搜索频率，仅针对文本输入
  useEffect(() => {
    const timer = setTimeout(() => {
      // 使用ref引用最新的onFiltersChange函数，避免依赖变化导致重复触发
      onFiltersChangeRef.current(localFilters);
    }, 300); // 300ms 防抖延迟

    return () => clearTimeout(timer);
  }, [localFilters]); // 只依赖localFilters，使用ref避免函数依赖问题

  // 计算显示的字段
  const visibleFields = showAllFields
    ? fields
    : fields.slice(0, maxVisibleFields);

  const hasMoreFields = fields.length > maxVisibleFields;

  // 渲染单个搜索字段
  const renderSearchField = (field: SearchFieldConfig) => {
    const value = localFilters[field.key] || field.defaultValue || '';

    switch (field.type) {
      case 'select':
        return (
          <div key={field.key}>
            <Select
              value={value}
              onValueChange={(newValue) => handleInputChange(field.key, newValue, 'select')}
              disabled={false} // 始终允许选择，不因加载而禁用
            >
              <SelectTrigger className="w-40">
                <SelectValue placeholder={field.placeholder || '请选择'} />
              </SelectTrigger>
              <SelectContent>
                {field.options?.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        );

      case 'text':
      default:
        return (
          <div key={field.key} className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder={field.placeholder || placeholder}
              value={value}
              onChange={(e) => handleInputChange(field.key, e.target.value, 'text')}
              disabled={false} // 始终允许输入，不因加载而禁用
              className="pl-10 w-64"
            />
          </div>
        );
    }
  };

  // 主搜索框（当没有配置字段时使用默认搜索）
  const renderMainSearch = () => (
    <div className="relative flex-1 max-w-md">
      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
      <Input
        placeholder={placeholder}
        value={localFilters.search || ''}
        onChange={(e) => handleInputChange('search', e.target.value, 'text')}
        disabled={false} // 始终允许输入，不因加载而禁用
        className="pl-10"
      />
    </div>
  );

  // 如果没有配置字段，使用简单搜索
  if (fields.length === 0) {
    return renderMainSearch();
  }

  return (
    <div className={`flex ${layout === 'horizontal' ? 'flex-row items-end' : 'flex-col items-start'} gap-4 flex-wrap`}>
      {/* 渲染搜索字段 */}
      {visibleFields.map(renderSearchField)}

      {/* 展开/收起按钮 */}
      {hasMoreFields && (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowAllFields(!showAllFields)}
          className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
        >
          {showAllFields ? '收起' : `展开更多 (${fields.length - maxVisibleFields})`}
        </Button>
      )}
    </div>
  );
}

const MemoizedSearchFormComponent = memo(SearchFormComponent);
export default MemoizedSearchFormComponent;