import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Search, X } from "lucide-react";
import { ModernDatePicker } from "./ModernDatePicker";
import { cn } from "@/lib/utils";
import { commonCodeApi } from "@/lib/api/commonCode";
import { EntityReferenceAPI } from "@/lib/api/entityReference";
import type { DataTableFilter } from "@/types/screen-legacy-backup";
import type { CodeInfo } from "@/types/commonCode";

interface AdvancedSearchFiltersProps {
  filters: DataTableFilter[];
  searchValues: Record<string, any>;
  onSearchValueChange: (columnName: string, value: any) => void;
  onSearch: () => void;
  onClearFilters: () => void;
  className?: string;
  tableColumns?: any[]; // 테이블 컬럼 정보
  tableName?: string; // 테이블명
}

interface DateRangeValue {
  from?: Date;
  to?: Date;
}

interface CodeOption {
  value: string;
  label: string;
}

interface EntityOption {
  value: string;
  label: string;
}

export const AdvancedSearchFilters: React.FC<AdvancedSearchFiltersProps> = ({
  filters,
  searchValues,
  onSearchValueChange,
  onSearch,
  onClearFilters,
  className = "",
  tableColumns = [],
  tableName = "",
}) => {
  // 코드 옵션 캐시
  const [codeOptions, setCodeOptions] = useState<Record<string, CodeOption[]>>({});
  // 엔티티 옵션 캐시
  const [entityOptions, setEntityOptions] = useState<Record<string, EntityOption[]>>({});
  // 로딩 상태
  const [loadingStates, setLoadingStates] = useState<Record<string, boolean>>({});

  // 자동 필터 생성 (설정된 필터가 없을 때 테이블 컬럼 기반으로 생성)
  const autoGeneratedFilters = useMemo(() => {
    if (filters.length > 0 || !tableColumns || tableColumns.length === 0) {
      return [];
    }

    // 필터 가능한 웹타입들
    const filterableWebTypes = ["text", "email", "tel", "number", "decimal", "date", "datetime", "code", "entity"];

    return tableColumns
      .filter((col) => {
        const webType = col.webType || col.web_type;
        const columnName = col.columnName || col.column_name;
        // 체크박스 컬럼과 __checkbox__ 컬럼, 사번 컬럼 제외
        return filterableWebTypes.includes(webType) && 
               col.isVisible !== false && 
               columnName !== "__checkbox__" &&
               !columnName.toLowerCase().includes('checkbox') &&
               !columnName.toLowerCase().includes('sabun') &&
               !columnName.toLowerCase().includes('사번');
      })
      .slice(0, 6) // 최대 6개까지만 자동 생성
      .map((col) => ({
        columnName: col.columnName || col.column_name,
        widgetType: col.webType || col.web_type,
        label: col.displayName || col.column_label || col.columnName || col.column_name,
        gridColumns: 3,
        codeCategory: col.codeCategory || col.code_category,
        referenceTable: col.referenceTable || col.reference_table,
        referenceColumn: col.referenceColumn || col.reference_column,
        displayColumn: col.displayColumn || col.display_column,
      }));
  }, [filters, tableColumns]);

  // 실제 사용할 필터 (설정된 필터가 있으면 우선, 없으면 자동 생성)
  const effectiveFilters = useMemo(() => {
    return filters.length > 0 ? filters : autoGeneratedFilters;
  }, [filters, autoGeneratedFilters]);

  // 코드 데이터 로드
  const loadCodeOptions = useCallback(
    async (codeCategory: string) => {
      if (codeOptions[codeCategory] || loadingStates[codeCategory]) return;

      setLoadingStates((prev) => ({ ...prev, [codeCategory]: true }));

      try {
        const response = await EntityReferenceAPI.getCodeReferenceData(codeCategory, { limit: 1000 });
        const options = response.options.map((option) => ({
          value: option.value,
          label: option.label,
        }));

        setCodeOptions((prev) => ({ ...prev, [codeCategory]: options }));
      } catch (error) {
        // console.error(`코드 카테고리 ${codeCategory} 로드 실패:`, error);
        setCodeOptions((prev) => ({ ...prev, [codeCategory]: [] }));
      } finally {
        setLoadingStates((prev) => ({ ...prev, [codeCategory]: false }));
      }
    },
    [codeOptions, loadingStates],
  );

  // 엔티티 데이터 로드
  const loadEntityOptions = useCallback(
    async (tableName: string, columnName: string) => {
      const key = `${tableName}.${columnName}`;
      if (entityOptions[key] || loadingStates[key]) return;

      setLoadingStates((prev) => ({ ...prev, [key]: true }));

      try {
        const response = await EntityReferenceAPI.getEntityReferenceData(tableName, columnName, { limit: 1000 });
        const options = response.options.map((option) => ({
          value: option.value,
          label: option.label,
        }));

        setEntityOptions((prev) => ({ ...prev, [key]: options }));
      } catch (error) {
        // console.error(`엔티티 ${tableName}.${columnName} 로드 실패:`, error);
        setEntityOptions((prev) => ({ ...prev, [key]: [] }));
      } finally {
        setLoadingStates((prev) => ({ ...prev, [key]: false }));
      }
    },
    [entityOptions, loadingStates],
  );

  // 즉시 검색을 위한 onChange 핸들러
  const handleChange = useCallback(
    (columnName: string, newValue: any) => {
      onSearchValueChange(columnName, newValue);
      // 즉시 검색 실행 (디바운싱 제거)
      onSearch();
    },
    [onSearchValueChange, onSearch],
  );

  // 텍스트 입력용 핸들러 (Enter 키 또는 blur 시에만 검색)
  const handleTextChange = useCallback(
    (columnName: string, newValue: string) => {
      onSearchValueChange(columnName, newValue);
      // 텍스트는 즉시 검색하지 않고 상태만 업데이트
    },
    [onSearchValueChange],
  );

  // Enter 키 또는 blur 시 검색 실행
  const handleTextSearch = useCallback(() => {
    onSearch();
  }, [onSearch]);

  // 필터별 렌더링 함수
  const renderFilter = (filter: DataTableFilter) => {
    const value = searchValues[filter.columnName] || "";

    switch (filter.widgetType) {
      case "text":
      case "email":
      case "tel":
        return (
          <Input
            key={filter.columnName}
            placeholder={`${filter.label} 검색...`}
            value={value}
            onChange={(e) => handleTextChange(filter.columnName, e.target.value)}
            onKeyPress={(e) => {
              if (e.key === "Enter") {
                handleTextSearch();
              }
            }}
            onBlur={handleTextSearch}
          />
        );

      case "number":
      case "decimal":
        // 숫자 필터 모드에 따라 다른 UI 렌더링
        if (filter.numberFilterMode === "exact") {
          // 정확한 값 검색
          return (
            <Input
              key={filter.columnName}
              type="number"
              placeholder={`${filter.label} 입력...`}
              value={value || ""}
              onChange={(e) => handleChange(filter.columnName, e.target.value)}
            />
          );
        } else {
          // 범위 검색 (기본값)
          return (
            <div key={filter.columnName} className="flex space-x-2">
              <Input
                type="number"
                placeholder={`최소값`}
                value={value?.min || ""}
                onChange={(e) =>
                  handleChange(filter.columnName, {
                    ...value,
                    min: e.target.value,
                  })
                }
              />
              <Input
                type="number"
                placeholder={`최대값`}
                value={value?.max || ""}
                onChange={(e) =>
                  handleChange(filter.columnName, {
                    ...value,
                    max: e.target.value,
                  })
                }
              />
            </div>
          );
        }

      case "date":
      case "datetime":
        return (
          <ModernDatePicker
            key={filter.columnName}
            label={filter.label}
            value={value || {}}
            onChange={(newValue) => handleChange(filter.columnName, newValue)}
            includeTime={filter.widgetType === "datetime"}
          />
        );

      case "code":
        return (
          <CodeFilter
            key={filter.columnName}
            filter={filter}
            value={value}
            onChange={(newValue) => handleChange(filter.columnName, newValue)}
            options={codeOptions[filter.codeCategory || ""] || []}
            loading={loadingStates[filter.codeCategory || ""]}
            onLoadOptions={() => filter.codeCategory && loadCodeOptions(filter.codeCategory)}
          />
        );

      case "entity":
        return (
          <EntityFilter
            key={filter.columnName}
            filter={filter}
            value={value}
            onChange={(newValue) => handleChange(filter.columnName, newValue)}
            options={entityOptions[`${filter.referenceTable}.${filter.columnName}`] || []}
            loading={loadingStates[`${filter.referenceTable}.${filter.columnName}`]}
            onLoadOptions={() => filter.referenceTable && loadEntityOptions(filter.referenceTable, filter.columnName)}
          />
        );

      case "select":
      case "dropdown":
        return (
          <Select
            key={filter.columnName}
            value={value}
            onValueChange={(newValue) => onSearchValueChange(filter.columnName, newValue)}
          >
            <SelectTrigger>
              <SelectValue placeholder={`${filter.label} 선택...`} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="__ALL__">전체</SelectItem>
              {/* TODO: 동적 옵션 로드 */}
            </SelectContent>
          </Select>
        );

      default:
        return (
          <Input
            key={filter.columnName}
            placeholder={`${filter.label} 검색...`}
            value={value}
            onChange={(e) => handleTextChange(filter.columnName, e.target.value)}
            onKeyPress={(e) => {
              if (e.key === "Enter") {
                handleTextSearch();
              }
            }}
            onBlur={handleTextSearch}
          />
        );
    }
  };

  // 활성 필터 개수 계산
  const activeFiltersCount = Object.values(searchValues).filter((value) => {
    if (typeof value === "string") return value.trim() !== "";
    if (typeof value === "object" && value !== null) {
      return Object.values(value).some((v) => v !== "" && v !== null && v !== undefined);
    }
    return value !== null && value !== undefined && value !== "";
  }).length;

  return (
    <div className={cn(className)}>
      {/* 필터 그리드 + 초기화 버튼 한 줄 */}
      {effectiveFilters.length > 0 && (
        <div className="flex flex-wrap items-center gap-3">
          {effectiveFilters.map((filter: DataTableFilter) => {
            // 필터 개수에 따라 적절한 너비 계산
            const getFilterWidth = () => {
              const filterCount = effectiveFilters.length;
              if (filterCount === 1) return "w-80"; // 1개일 때는 적당한 크기
              if (filterCount === 2) return "w-64"; // 2개일 때는 조금 작게
              if (filterCount === 3) return "w-52"; // 3개일 때는 더 작게
              return "w-48"; // 4개 이상일 때는 가장 작게
            };

            return (
              <div key={filter.columnName} className={`${getFilterWidth()}`}>
                {renderFilter(filter)}
              </div>
            );
          })}
          
          {/* 필터 초기화 버튼 - 같은 줄에 배치 */}
          {activeFiltersCount > 0 && (
            <Button variant="outline" size="sm" onClick={onClearFilters} className="gap-2 flex-shrink-0">
              <X className="h-3 w-3" />
              필터 초기화
            </Button>
          )}
        </div>
      )}
    </div>
  );
};

// 코드 필터 컴포넌트
const CodeFilter: React.FC<{
  filter: DataTableFilter;
  value: string;
  onChange: (value: string) => void;
  options: CodeOption[];
  loading: boolean;
  onLoadOptions: () => void;
}> = ({ filter, value, onChange, options, loading, onLoadOptions }) => {
  useEffect(() => {
    if (filter.codeCategory && options.length === 0 && !loading) {
      onLoadOptions();
    }
  }, [filter.codeCategory, options.length, loading, onLoadOptions]);

  return (
    <Select value={value} onValueChange={onChange}>
      <SelectTrigger>
        <SelectValue placeholder={loading ? "로딩 중..." : `${filter.label} 선택...`} />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="__ALL__">전체</SelectItem>
        {options.map((option) => (
          <SelectItem key={option.value} value={option.value}>
            {option.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

// 엔티티 필터 컴포넌트
const EntityFilter: React.FC<{
  filter: DataTableFilter;
  value: string;
  onChange: (value: string) => void;
  options: EntityOption[];
  loading: boolean;
  onLoadOptions: () => void;
}> = ({ filter, value, onChange, options, loading, onLoadOptions }) => {
  useEffect(() => {
    if (filter.referenceTable && options.length === 0 && !loading) {
      onLoadOptions();
    }
  }, [filter.referenceTable, options.length, loading, onLoadOptions]);

  return (
    <Select value={value} onValueChange={onChange}>
      <SelectTrigger>
        <SelectValue placeholder={loading ? "로딩 중..." : `${filter.label} 선택...`} />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="__ALL__">전체</SelectItem>
        {options.map((option) => (
          <SelectItem key={option.value} value={option.value}>
            {option.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};
