"use client";

/**
 * FilterPopup 컴포넌트
 * 피벗 필드의 값을 필터링하는 팝업
 */

import React, { useState, useMemo } from "react";
import { cn } from "@/lib/utils";
import { PivotFieldConfig } from "../types";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Label } from "@/components/ui/label";
import {
  Search,
  Filter,
  Check,
  X,
  CheckSquare,
  Square,
} from "lucide-react";

// ==================== 타입 ====================

interface FilterPopupProps {
  field: PivotFieldConfig;
  data: any[];
  onFilterChange: (field: PivotFieldConfig, values: any[], type: "include" | "exclude") => void;
  trigger?: React.ReactNode;
}

// ==================== 메인 컴포넌트 ====================

export const FilterPopup: React.FC<FilterPopupProps> = ({
  field,
  data,
  onFilterChange,
  trigger,
}) => {
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedValues, setSelectedValues] = useState<Set<any>>(
    new Set(field.filterValues || [])
  );
  const [filterType, setFilterType] = useState<"include" | "exclude">(
    field.filterType || "include"
  );

  // 고유 값 추출
  const uniqueValues = useMemo(() => {
    const values = new Set<any>();
    data.forEach((row) => {
      const value = row[field.field];
      if (value !== null && value !== undefined) {
        values.add(value);
      }
    });
    return Array.from(values).sort((a, b) => {
      if (typeof a === "number" && typeof b === "number") return a - b;
      return String(a).localeCompare(String(b), "ko");
    });
  }, [data, field.field]);

  // 필터링된 값 목록
  const filteredValues = useMemo(() => {
    if (!searchQuery) return uniqueValues;
    const query = searchQuery.toLowerCase();
    return uniqueValues.filter((val) =>
      String(val).toLowerCase().includes(query)
    );
  }, [uniqueValues, searchQuery]);

  // 값 토글
  const handleValueToggle = (value: any) => {
    const newSelected = new Set(selectedValues);
    if (newSelected.has(value)) {
      newSelected.delete(value);
    } else {
      newSelected.add(value);
    }
    setSelectedValues(newSelected);
  };

  // 모두 선택
  const handleSelectAll = () => {
    setSelectedValues(new Set(filteredValues));
  };

  // 모두 해제
  const handleClearAll = () => {
    setSelectedValues(new Set());
  };

  // 적용
  const handleApply = () => {
    onFilterChange(field, Array.from(selectedValues), filterType);
    setOpen(false);
  };

  // 초기화
  const handleReset = () => {
    setSelectedValues(new Set());
    setFilterType("include");
    onFilterChange(field, [], "include");
    setOpen(false);
  };

  // 필터 활성 상태
  const isFilterActive = field.filterValues && field.filterValues.length > 0;

  // 선택된 항목 수
  const selectedCount = selectedValues.size;
  const totalCount = uniqueValues.length;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        {trigger || (
          <button
            className={cn(
              "p-1 rounded hover:bg-accent",
              isFilterActive && "text-primary"
            )}
          >
            <Filter className="h-3.5 w-3.5" />
          </button>
        )}
      </PopoverTrigger>
      <PopoverContent className="w-72 p-0" align="start">
        <div className="p-3 border-b border-border">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium">{field.caption} 필터</span>
            <div className="flex gap-1">
              <button
                onClick={() => setFilterType("include")}
                className={cn(
                  "px-2 py-0.5 text-xs rounded",
                  filterType === "include"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted hover:bg-accent"
                )}
              >
                포함
              </button>
              <button
                onClick={() => setFilterType("exclude")}
                className={cn(
                  "px-2 py-0.5 text-xs rounded",
                  filterType === "exclude"
                    ? "bg-destructive text-destructive-foreground"
                    : "bg-muted hover:bg-accent"
                )}
              >
                제외
              </button>
            </div>
          </div>

          {/* 검색 */}
          <div className="relative">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
            <Input
              placeholder="검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8 h-8 text-sm"
            />
          </div>

          {/* 전체 선택/해제 */}
          <div className="flex items-center justify-between mt-2 text-xs text-muted-foreground">
            <span>
              {selectedCount} / {totalCount} 선택됨
            </span>
            <div className="flex gap-2">
              <button
                onClick={handleSelectAll}
                className="flex items-center gap-1 hover:text-foreground"
              >
                <CheckSquare className="h-3 w-3" />
                전체 선택
              </button>
              <button
                onClick={handleClearAll}
                className="flex items-center gap-1 hover:text-foreground"
              >
                <Square className="h-3 w-3" />
                전체 해제
              </button>
            </div>
          </div>
        </div>

        {/* 값 목록 */}
        <ScrollArea className="h-48">
          <div className="p-2 space-y-1">
            {filteredValues.length === 0 ? (
              <div className="text-center py-4 text-sm text-muted-foreground">
                결과가 없습니다
              </div>
            ) : (
              filteredValues.map((value) => (
                <label
                  key={String(value)}
                  className={cn(
                    "flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer",
                    "hover:bg-muted text-sm"
                  )}
                >
                  <Checkbox
                    checked={selectedValues.has(value)}
                    onCheckedChange={() => handleValueToggle(value)}
                  />
                  <span className="truncate">{String(value)}</span>
                  <span className="ml-auto text-xs text-muted-foreground">
                    ({data.filter((r) => r[field.field] === value).length})
                  </span>
                </label>
              ))
            )}
          </div>
        </ScrollArea>

        {/* 버튼 */}
        <div className="flex items-center justify-between p-2 border-t border-border">
          <Button
            variant="ghost"
            size="sm"
            onClick={handleReset}
            className="h-7 text-xs"
          >
            초기화
          </Button>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setOpen(false)}
              className="h-7 text-xs"
            >
              취소
            </Button>
            <Button
              size="sm"
              onClick={handleApply}
              className="h-7 text-xs"
            >
              적용
            </Button>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
};

export default FilterPopup;

