"use client";

import { useState, useEffect } 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 { CodeFormModal } from "./CodeFormModal";
import { AlertModal } from "@/components/common/AlertModal";
import { Search, Plus, Edit, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";

interface CodeDetailPanelProps {
  categoryCode: string;
}

export function CodeDetailPanel({ categoryCode }: CodeDetailPanelProps) {
  // const { getText } = useMultiLang(); // 무한 루프 방지를 위해 임시 제거
  const { codes, codesLoading, codesError, fetchCodes, deleteCode } = useCommonCode();

  // 카테고리 변경 시 코드 조회
  useEffect(() => {
    if (categoryCode) {
      console.log("🔍 카테고리 변경됨, 코드 조회:", categoryCode);
      fetchCodes(categoryCode);
    }
  }, [categoryCode, fetchCodes]);

  // 로컬 상태
  const [searchTerm, setSearchTerm] = useState("");
  const [showFormModal, setShowFormModal] = useState(false);
  const [editingCode, setEditingCode] = useState<{ categoryCode: string; codeValue: string }>({
    categoryCode: "",
    codeValue: "",
  });
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingCode, setDeletingCode] = useState<{ categoryCode: string; codeValue: string }>({
    categoryCode: "",
    codeValue: "",
  });

  // 검색 필터링
  const filteredCodes = codes.filter(
    (code) =>
      code.code_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      code.code_value.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  // 코드 생성 핸들러
  const handleCreateCode = () => {
    if (!categoryCode) return;

    setEditingCode({ categoryCode: "", codeValue: "" });
    setShowFormModal(true);
  };

  // 코드 수정 핸들러
  const handleEditCode = (codeValue: string) => {
    setEditingCode({ categoryCode, codeValue });
    setShowFormModal(true);
  };

  // 코드 삭제 핸들러
  const handleDeleteCode = (codeValue: string) => {
    setDeletingCode({ categoryCode, codeValue });
    setShowDeleteModal(true);
  };

  // 삭제 확인 핸들러
  const handleConfirmDelete = async () => {
    if (!deletingCode.categoryCode || !deletingCode.codeValue) return;

    try {
      await deleteCode(deletingCode.categoryCode, deletingCode.codeValue);
      setShowDeleteModal(false);
      setDeletingCode({ categoryCode: "", codeValue: "" });
    } catch (error) {
      console.error("코드 삭제 오류:", error);
      // 에러 처리는 useCommonCode 훅에서 처리됨
    }
  };

  // 카테고리가 선택되지 않은 경우
  if (!categoryCode) {
    return (
      <div className="text-muted-foreground flex h-64 items-center justify-center">
        <div className="text-center">
          <p className="mb-2 text-lg font-medium">카테고리를 선택하세요</p>
          <p className="text-sm">왼쪽에서 카테고리를 선택하면 해당 코드 목록이 표시됩니다.</p>
        </div>
      </div>
    );
  }

  // 에러 상태
  if (codesError) {
    return (
      <div className="p-4 text-center text-red-600">
        <p className="mb-2">❌ {codesError}</p>
        <Button onClick={() => fetchCodes(categoryCode)} 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>

        <Button onClick={handleCreateCode} className="w-full" size="sm">
          <Plus className="mr-2 h-4 w-4" />새 코드
        </Button>
      </div>

      {/* 코드 목록 */}
      <div className="max-h-96 overflow-y-auto">
        {codesLoading ? (
          <div className="p-4 text-center">
            <LoadingSpinner size="sm" />
            <p className="text-muted-foreground mt-2 text-sm">코드를 불러오는 중...</p>
          </div>
        ) : filteredCodes.length === 0 ? (
          <div className="text-muted-foreground p-4 text-center">
            <p>코드가 없습니다.</p>
          </div>
        ) : (
          <div className="space-y-1">
            {filteredCodes.map((code) => (
              <div
                key={`${code.code_category}-${code.code_value}`}
                className="group hover:bg-muted flex items-center justify-between rounded-lg p-3 transition-colors"
              >
                <div className="min-w-0 flex-1">
                  <div className="mb-1 flex items-center gap-2">
                    <span className="text-sm font-medium">{code.code_name}</span>
                    {code.is_active === "Y" ? (
                      <Badge variant="secondary" className="text-xs">
                        활성
                      </Badge>
                    ) : (
                      <Badge variant="outline" className="text-xs">
                        비활성
                      </Badge>
                    )}
                  </div>
                  <div className="text-muted-foreground flex items-center gap-2 text-xs">
                    <span className="bg-muted rounded px-2 py-1 font-mono">{code.code_value}</span>
                    {code.code_name_eng && <span>({code.code_name_eng})</span>}
                  </div>
                  {code.description && (
                    <p className="text-muted-foreground mt-1 truncate text-xs">{code.description}</p>
                  )}
                </div>

                {/* 액션 버튼 */}
                <div className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0"
                    onClick={() => handleEditCode(code.code_value)}
                  >
                    <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={() => handleDeleteCode(code.code_value)}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 코드 폼 모달 */}
      {showFormModal && (
        <CodeFormModal
          isOpen={showFormModal}
          onClose={() => setShowFormModal(false)}
          categoryCode={categoryCode}
          editingCodeValue={editingCode.codeValue}
        />
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <AlertModal
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          onConfirm={handleConfirmDelete}
          title="삭제 확인"
          message="이 코드를 삭제하시겠습니까?"
          confirmText="삭제"
          cancelText="취소"
          variant="destructive"
        />
      )}
    </div>
  );
}
