"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { LoadingSpinner } from "@/components/common/LoadingSpinner";
import { useCommonCode } from "@/hooks/useCommonCode";
// import { useMultiLang } from "@/hooks/useMultiLang"; // 무한 루프 방지를 위해 임시 제거
import { CodeCategoryFormModal } from "./CodeCategoryFormModal";
import { AlertModal } from "@/components/common/AlertModal";
import { Search, Plus, Edit, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";

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

export function CodeCategoryPanel({ selectedCategoryCode, onSelectCategory }: CodeCategoryPanelProps) {
  // useMultiLang 호출 제거 - 상위에서 전달받도록 수정
  const {
    categories,
    categoriesLoading,
    categoriesError,
    fetchCategories,
    createCategory,
    updateCategory,
    deleteCategory,
  } = useCommonCode();

  // 로컬 상태
  const [searchTerm, setSearchTerm] = useState("");
  const [showActiveOnly, setShowActiveOnly] = useState(false); // 활성 필터 상태
  const [showFormModal, setShowFormModal] = useState(false);
  const [editingCategory, setEditingCategory] = useState<string>("");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingCategory, setDeletingCategory] = useState<string>("");

  // 검색 및 활성 상태 필터링
  const filteredCategories = categories.filter((category) => {
    // 검색 조건
    const matchesSearch =
      category.category_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      category.category_code.toLowerCase().includes(searchTerm.toLowerCase());

    // 활성 상태 필터 조건
    const matchesActiveFilter = showActiveOnly ? category.is_active : true;

    return matchesSearch && matchesActiveFilter;
  });

  // 카테고리 생성 핸들러
  const handleCreateCategory = () => {
    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 deleteCategory(deletingCategory);
      setShowDeleteModal(false);
      setDeletingCategory("");
    } catch (error) {
      console.error("카테고리 삭제 오류:", error);
      // 에러 처리는 useCommonCode 훅에서 처리됨
    }
  };

  if (categoriesError) {
    return (
      <div className="p-4 text-center text-red-600">
        <p className="mb-2">❌ {categoriesError}</p>
        <Button onClick={() => fetchCategories()} variant="outline" size="sm">
          다시 시도
        </Button>
      </div>
    );
  }

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

        {/* 활성 상태 필터 토글 */}
        <div className="flex items-center gap-2">
          <label className="flex cursor-pointer items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={showActiveOnly}
              onChange={(e) => setShowActiveOnly(e.target.checked)}
              className="h-4 w-4 rounded border-gray-300 bg-gray-100 text-blue-600 focus:ring-2 focus:ring-blue-500"
            />
            활성 카테고리만 표시
          </label>
        </div>

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

      {/* 카테고리 목록 */}
      <div className="max-h-96 overflow-y-auto">
        {categoriesLoading ? (
          <div className="p-4 text-center">
            <LoadingSpinner size="sm" />
            <p className="text-muted-foreground mt-2 text-sm">카테고리를 불러오는 중...</p>
          </div>
        ) : filteredCategories.length === 0 ? (
          <div className="text-muted-foreground p-4 text-center">
            <p>카테고리가 없습니다.</p>
          </div>
        ) : (
          <div className="space-y-1">
            {filteredCategories.map((category) => (
              <div
                key={category.category_code}
                className={cn(
                  "group flex cursor-pointer items-center justify-between rounded-lg p-3 transition-colors",
                  selectedCategoryCode === category.category_code
                    ? "border-2 border-gray-300 bg-gray-100 shadow-sm"
                    : "hover:bg-muted",
                )}
                onClick={() => onSelectCategory(category.category_code)}
              >
                <div className="min-w-0 flex-1">
                  <div className="mb-1 flex items-center gap-2">
                    <span className="text-sm font-medium">{category.category_name}</span>
                    {category.is_active === "Y" ? (
                      <Badge variant="secondary" className="text-xs">
                        활성
                      </Badge>
                    ) : (
                      <Badge variant="outline" className="text-xs">
                        비활성
                      </Badge>
                    )}
                  </div>
                  <p className="text-muted-foreground truncate text-xs">{category.category_code}</p>
                  {category.description && (
                    <p className="text-muted-foreground mt-1 truncate text-xs">{category.description}</p>
                  )}
                </div>

                {/* 액션 버튼 */}
                <div
                  className={cn(
                    "flex gap-1 transition-opacity",
                    selectedCategoryCode === category.category_code
                      ? "opacity-100"
                      : "opacity-0 group-hover:opacity-100",
                  )}
                >
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEditCategory(category.category_code);
                    }}
                  >
                    <Edit className="h-3 w-3" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0 text-red-600 hover:text-red-700"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteCategory(category.category_code);
                    }}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

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

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <AlertModal
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          onConfirm={handleConfirmDelete}
          type="error"
          title="삭제 확인"
          message="이 카테고리를 삭제하시겠습니까? 관련된 모든 코드도 함께 삭제됩니다."
          confirmText="삭제"
        />
      )}
    </div>
  );
}
