"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LoadingSpinner } from "@/components/common/LoadingSpinner";
import { CodeCategoryFormModal } from "./CodeCategoryFormModal";
import { CategoryItem } from "./CategoryItem";
import { AlertModal } from "@/components/common/AlertModal";
import { Search, Plus } from "lucide-react";
import { useDeleteCategory } from "@/hooks/queries/useCategories";
import { useCategoriesInfinite } from "@/hooks/queries/useCategoriesInfinite";

interface CodeCategoryPanelProps {
  selectedCategoryCode: string;
  onSelectCategory: (categoryCode: string) => void;
}

export function CodeCategoryPanel({ selectedCategoryCode, onSelectCategory }: CodeCategoryPanelProps) {
  // 검색 및 필터 상태 (먼저 선언)
  const [searchTerm, setSearchTerm] = useState("");
  const [showActiveOnly, setShowActiveOnly] = useState(false);

  // React Query로 카테고리 데이터 관리 (무한 스크롤)
  const {
    data: categories = [],
    isLoading,
    error,
    handleScroll,
    isFetchingNextPage,
    hasNextPage,
  } = useCategoriesInfinite({
    search: searchTerm || undefined,
    active: showActiveOnly || undefined, // isActive -> active로 수정
  });
  const deleteCategoryMutation = useDeleteCategory();

  // 모달 상태
  const [showFormModal, setShowFormModal] = useState(false);
  const [editingCategory, setEditingCategory] = useState<string>("");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingCategory, setDeletingCategory] = useState<string>("");

  // 새 카테고리 생성
  const handleNewCategory = () => {
    setEditingCategory("");
    setShowFormModal(true);
  };

  // 카테고리 수정
  const handleEditCategory = (categoryCode: string) => {
    setEditingCategory(categoryCode);
    setShowFormModal(true);
  };

  // 카테고리 삭제 확인
  const handleDeleteCategory = (categoryCode: string) => {
    setDeletingCategory(categoryCode);
    setShowDeleteModal(true);
  };

  // 카테고리 삭제 실행
  const handleConfirmDelete = async () => {
    if (!deletingCategory) return;

    try {
      await deleteCategoryMutation.mutateAsync(deletingCategory);

      // 삭제된 카테고리가 선택된 상태라면 선택 해제
      if (selectedCategoryCode === deletingCategory) {
        onSelectCategory("");
      }

      setShowDeleteModal(false);
      setDeletingCategory("");
    } catch (error) {
      console.error("카테고리 삭제 실패:", error);
    }
  };

  if (error) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <p className="text-red-600">카테고리를 불러오는 중 오류가 발생했습니다.</p>
          <Button variant="outline" onClick={() => window.location.reload()} className="mt-2">
            다시 시도
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      {/* 검색 및 필터 */}
      <div className="border-b p-4">
        <div className="space-y-3">
          {/* 검색 */}
          <div className="relative">
            <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <Input
              placeholder="카테고리 검색..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          {/* 활성 필터 */}
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="activeOnly"
              checked={showActiveOnly}
              onChange={(e) => setShowActiveOnly(e.target.checked)}
              className="rounded border-gray-300"
            />
            <label htmlFor="activeOnly" className="text-sm text-gray-600">
              활성 카테고리만 표시
            </label>
          </div>

          {/* 새 카테고리 버튼 */}
          <Button onClick={handleNewCategory} className="w-full" size="sm">
            <Plus className="mr-2 h-4 w-4" />새 카테고리
          </Button>
        </div>
      </div>

      {/* 카테고리 목록 (무한 스크롤) */}
      <div className="h-96 overflow-y-auto" onScroll={handleScroll}>
        {isLoading ? (
          <div className="flex h-32 items-center justify-center">
            <LoadingSpinner />
          </div>
        ) : categories.length === 0 ? (
          <div className="p-4 text-center text-gray-500">
            {searchTerm ? "검색 결과가 없습니다." : "카테고리가 없습니다."}
          </div>
        ) : (
          <>
            <div className="space-y-1 p-2">
              {categories.map((category, index) => (
                <CategoryItem
                  key={`${category.category_code}-${index}`}
                  category={category}
                  isSelected={selectedCategoryCode === category.category_code}
                  onSelect={() => onSelectCategory(category.category_code)}
                  onEdit={() => handleEditCategory(category.category_code)}
                  onDelete={() => handleDeleteCategory(category.category_code)}
                />
              ))}
            </div>

            {/* 추가 로딩 표시 */}
            {isFetchingNextPage && (
              <div className="flex justify-center py-4">
                <LoadingSpinner size="sm" />
                <span className="ml-2 text-sm text-gray-500">추가 로딩 중...</span>
              </div>
            )}

            {/* 더 이상 데이터가 없을 때 */}
            {!hasNextPage && categories.length > 0 && (
              <div className="py-4 text-center text-sm text-gray-400">모든 카테고리를 불러왔습니다.</div>
            )}
          </>
        )}
      </div>

      {/* 카테고리 폼 모달 */}
      {showFormModal && (
        <CodeCategoryFormModal
          isOpen={showFormModal}
          onClose={() => setShowFormModal(false)}
          editingCategoryCode={editingCategory}
          categories={categories}
        />
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <AlertModal
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          type="error"
          title="카테고리 삭제"
          message="정말로 이 카테고리를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
          confirmText="삭제"
          onConfirm={handleConfirmDelete}
        />
      )}
    </div>
  );
}
