import React, { useState, useEffect } from "react";
import { useTableOptions } from "@/contexts/TableOptionsContext";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Checkbox } from "@/components/ui/checkbox";
import { Layers } from "lucide-react";
import { TableFilter, GroupSumConfig } from "@/types/table-options";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onFiltersApplied?: (filters: TableFilter[]) => void; // 필터 적용 시 콜백
  screenId?: number; // 화면 ID 추가
}

// 필터 타입별 연산자
const operatorsByType: Record<string, Record<string, string>> = {
  text: {
    contains: "포함",
    equals: "같음",
    startsWith: "시작",
    endsWith: "끝",
    notEquals: "같지 않음",
  },
  number: {
    equals: "같음",
    gt: "보다 큼",
    lt: "보다 작음",
    gte: "이상",
    lte: "이하",
    notEquals: "같지 않음",
  },
  date: {
    equals: "같음",
    gt: "이후",
    lt: "이전",
    gte: "이후 포함",
    lte: "이전 포함",
  },
  select: {
    equals: "같음",
    notEquals: "같지 않음",
  },
};

// 컬럼 필터 설정 인터페이스
interface ColumnFilterConfig {
  columnName: string;
  columnLabel: string;
  inputType: string;
  enabled: boolean;
  filterType: "text" | "number" | "date" | "select";
  width?: number; // 필터 입력 필드 너비 (px)
  selectOptions?: Array<{ label: string; value: string }>;
}

export const FilterPanel: React.FC<Props> = ({ isOpen, onClose, onFiltersApplied, screenId }) => {
  const { getTable, selectedTableId } = useTableOptions();
  const table = selectedTableId ? getTable(selectedTableId) : undefined;

  const [columnFilters, setColumnFilters] = useState<ColumnFilterConfig[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  // 🆕 그룹별 합산 설정
  const [groupSumEnabled, setGroupSumEnabled] = useState(false);
  const [groupByColumn, setGroupByColumn] = useState<string>("");

  // localStorage에서 저장된 필터 설정 불러오기
  useEffect(() => {
    if (table?.columns && table?.tableName) {
      // 화면별로 독립적인 필터 설정 저장
      const storageKey = screenId
        ? `table_filters_${table.tableName}_screen_${screenId}`
        : `table_filters_${table.tableName}`;
      const savedFilters = localStorage.getItem(storageKey);

      // 🆕 그룹핑 설정도 불러오기
      const groupSumKey = screenId
        ? `table_groupsum_${table.tableName}_screen_${screenId}`
        : `table_groupsum_${table.tableName}`;
      const savedGroupSum = localStorage.getItem(groupSumKey);

      if (savedGroupSum) {
        try {
          const parsed = JSON.parse(savedGroupSum) as GroupSumConfig;
          setGroupSumEnabled(parsed.enabled);
          setGroupByColumn(parsed.groupByColumn || "");
        } catch (error) {
          console.error("그룹핑 설정 불러오기 실패:", error);
        }
      }

      let filters: ColumnFilterConfig[];

      if (savedFilters) {
        try {
          const parsed = JSON.parse(savedFilters) as ColumnFilterConfig[];
          // 저장된 설정과 현재 컬럼 병합
          filters = table.columns
            .filter((col) => col.filterable !== false)
            .map((col) => {
              const saved = parsed.find((f) => f.columnName === col.columnName);
              return (
                saved || {
                  columnName: col.columnName,
                  columnLabel: col.columnLabel,
                  inputType: col.inputType || "text",
                  enabled: false,
                  filterType: mapInputTypeToFilterType(col.inputType || "text"),
                }
              );
            });
        } catch (error) {
          console.error("저장된 필터 설정 불러오기 실패:", error);
          filters = table.columns
            .filter((col) => col.filterable !== false)
            .map((col) => ({
              columnName: col.columnName,
              columnLabel: col.columnLabel,
              inputType: col.inputType || "text",
              enabled: false,
              filterType: mapInputTypeToFilterType(col.inputType || "text"),
            }));
        }
      } else {
        filters = table.columns
          .filter((col) => col.filterable !== false)
          .map((col) => ({
            columnName: col.columnName,
            columnLabel: col.columnLabel,
            inputType: col.inputType || "text",
            enabled: false,
            filterType: mapInputTypeToFilterType(col.inputType || "text"),
          }));
      }

      setColumnFilters(filters);
    }
  }, [table?.columns, table?.tableName]);

  // inputType을 filterType으로 매핑
  const mapInputTypeToFilterType = (inputType: string): "text" | "number" | "date" | "select" => {
    if (inputType.includes("number") || inputType.includes("decimal")) {
      return "number";
    }
    if (inputType.includes("date") || inputType.includes("time")) {
      return "date";
    }
    if (inputType.includes("select") || inputType.includes("code") || inputType.includes("category")) {
      return "select";
    }
    return "text";
  };

  // 전체 선택/해제
  const toggleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    setColumnFilters((prev) => prev.map((filter) => ({ ...filter, enabled: checked })));
  };

  // 개별 필터 토글
  const toggleFilter = (columnName: string) => {
    setColumnFilters((prev) =>
      prev.map((filter) => (filter.columnName === columnName ? { ...filter, enabled: !filter.enabled } : filter)),
    );
  };

  // 필터 타입 변경
  const updateFilterType = (columnName: string, filterType: "text" | "number" | "date" | "select") => {
    setColumnFilters((prev) =>
      prev.map((filter) => (filter.columnName === columnName ? { ...filter, filterType } : filter)),
    );
  };

  // 저장
  const applyFilters = () => {
    // enabled된 필터들만 TableFilter로 변환
    const activeFilters: TableFilter[] = columnFilters
      .filter((cf) => cf.enabled)
      .map((cf) => ({
        columnName: cf.columnName,
        operator: "contains", // 기본 연산자
        value: "",
        filterType: cf.filterType,
        width: cf.width && cf.width >= 10 && cf.width <= 100 ? cf.width : 25,
      }));

    // localStorage에 저장 (화면별로 독립적)
    if (table?.tableName) {
      const storageKey = screenId
        ? `table_filters_${table.tableName}_screen_${screenId}`
        : `table_filters_${table.tableName}`;
      localStorage.setItem(storageKey, JSON.stringify(columnFilters));

      // 🆕 그룹핑 설정 저장
      const groupSumKey = screenId
        ? `table_groupsum_${table.tableName}_screen_${screenId}`
        : `table_groupsum_${table.tableName}`;

      if (groupSumEnabled && groupByColumn) {
        const selectedColumn = columnFilters.find((f) => f.columnName === groupByColumn);
        const groupSumConfig: GroupSumConfig = {
          enabled: true,
          groupByColumn: groupByColumn,
          groupByColumnLabel: selectedColumn?.columnLabel,
        };
        localStorage.setItem(groupSumKey, JSON.stringify(groupSumConfig));
        table?.onGroupSumChange?.(groupSumConfig);
      } else {
        localStorage.removeItem(groupSumKey);
        table?.onGroupSumChange?.(null);
      }
    }

    table?.onFilterChange(activeFilters);

    // 콜백으로 활성화된 필터 정보 전달
    onFiltersApplied?.(activeFilters);

    onClose();
  };

  // 초기화 (즉시 저장 및 적용)
  const clearFilters = () => {
    const clearedFilters = columnFilters.map((filter) => ({
      ...filter,
      enabled: false,
    }));

    setColumnFilters(clearedFilters);
    setSelectAll(false);

    // 🆕 그룹핑 설정 초기화
    setGroupSumEnabled(false);
    setGroupByColumn("");

    // localStorage에서 제거 (화면별로 독립적)
    if (table?.tableName) {
      const storageKey = screenId
        ? `table_filters_${table.tableName}_screen_${screenId}`
        : `table_filters_${table.tableName}`;
      localStorage.removeItem(storageKey);

      // 🆕 그룹핑 설정도 제거
      const groupSumKey = screenId
        ? `table_groupsum_${table.tableName}_screen_${screenId}`
        : `table_groupsum_${table.tableName}`;
      localStorage.removeItem(groupSumKey);
    }

    // 빈 필터 배열로 적용
    table?.onFilterChange([]);

    // 🆕 그룹핑 해제
    table?.onGroupSumChange?.(null);

    // 콜백으로 빈 필터 정보 전달
    onFiltersApplied?.([]);

    // 즉시 닫기
    onClose();
  };

  const enabledCount = columnFilters.filter((f) => f.enabled).length;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-[95vw] sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="text-base sm:text-lg">검색 필터 설정</DialogTitle>
          <DialogDescription className="text-xs sm:text-sm">
            검색 필터로 사용할 컬럼을 선택하세요. 선택한 컬럼의 검색 입력 필드가 표시됩니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 sm:space-y-4">
          {/* 전체 선택/해제 */}
          <div className="bg-muted/30 flex items-center justify-between rounded-lg border p-3">
            <div className="flex items-center gap-3">
              <Checkbox checked={selectAll} onCheckedChange={(checked) => toggleSelectAll(checked as boolean)} />
              <span className="text-sm font-medium">전체 선택/해제</span>
            </div>
            <div className="text-muted-foreground text-xs">
              {enabledCount} / {columnFilters.length}개
            </div>
          </div>

          {/* 컬럼 필터 리스트 */}
          <ScrollArea className="h-[400px] sm:h-[450px]">
            <div className="space-y-2 pr-4">
              {columnFilters.map((filter) => (
                <div
                  key={filter.columnName}
                  className="bg-background hover:bg-muted/50 flex items-center gap-3 rounded-lg border p-3 transition-colors"
                >
                  {/* 체크박스 */}
                  <Checkbox checked={filter.enabled} onCheckedChange={() => toggleFilter(filter.columnName)} />

                  {/* 컬럼 정보 */}
                  <div className="min-w-0 flex-1">
                    <div className="truncate text-sm font-medium">{filter.columnLabel}</div>
                    <div className="text-muted-foreground truncate text-xs">{filter.columnName}</div>
                  </div>

                  {/* 필터 타입 선택 */}
                  <Select
                    value={filter.filterType}
                    onValueChange={(val: any) => updateFilterType(filter.columnName, val)}
                    disabled={!filter.enabled}
                  >
                    <SelectTrigger className="h-8 w-[110px] text-xs sm:h-9 sm:text-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="text">텍스트</SelectItem>
                      <SelectItem value="number">숫자</SelectItem>
                      <SelectItem value="date">날짜</SelectItem>
                      <SelectItem value="select">선택</SelectItem>
                    </SelectContent>
                  </Select>

                  {/* 너비 입력 */}
                  <Input
                    type="number"
                    value={filter.width && filter.width >= 10 && filter.width <= 100 ? filter.width : 25}
                    onChange={(e) => {
                      const newWidth = Math.min(100, Math.max(10, parseInt(e.target.value) || 25));
                      setColumnFilters((prev) =>
                        prev.map((f) => (f.columnName === filter.columnName ? { ...f, width: newWidth } : f)),
                      );
                    }}
                    disabled={!filter.enabled}
                    placeholder="25"
                    className="h-8 w-[80px] text-xs sm:h-9 sm:text-sm"
                    min={10}
                    max={100}
                  />
                  <span className="text-muted-foreground text-xs">%</span>
                </div>
              ))}
            </div>
          </ScrollArea>

          {/* 🆕 그룹별 합산 설정 */}
          <div className="bg-muted/30 space-y-3 rounded-lg border p-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Layers className="text-muted-foreground h-4 w-4" />
                <Label htmlFor="group-sum-toggle" className="cursor-pointer text-sm font-medium">
                  그룹별 합산
                </Label>
              </div>
              <Switch id="group-sum-toggle" checked={groupSumEnabled} onCheckedChange={setGroupSumEnabled} />
            </div>

            {groupSumEnabled && (
              <div className="space-y-2">
                <Label className="text-muted-foreground text-xs">
                  그룹 기준 컬럼 (숫자 컬럼은 자동으로 합산됩니다)
                </Label>
                <Select value={groupByColumn} onValueChange={setGroupByColumn}>
                  <SelectTrigger className="h-8 text-xs">
                    <SelectValue placeholder="그룹 기준 컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {columnFilters.map((filter) => (
                      <SelectItem key={filter.columnName} value={filter.columnName}>
                        {filter.columnLabel}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>

          {/* 안내 메시지 */}
          <div className="bg-muted/50 text-muted-foreground rounded-lg p-3 text-center text-xs">
            검색 필터를 사용하려면 최소 1개 이상의 컬럼을 선택하세요
          </div>
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button variant="ghost" onClick={clearFilters} className="h-8 text-xs sm:h-10 sm:text-sm">
            초기화
          </Button>
          <Button variant="outline" onClick={onClose} className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm">
            취소
          </Button>
          <Button
            onClick={applyFilters}
            disabled={enabledCount === 0}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
