"use client";

import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useCommonCode } from "@/hooks/useCommonCode";
// import { useMultiLang } from "@/hooks/useMultiLang"; // 무한 루프 방지를 위해 임시 제거
import { LoadingSpinner } from "@/components/common/LoadingSpinner";
import { CodeCategory } from "@/types/commonCode";

interface CodeCategoryFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  editingCategoryCode?: string;
}

export function CodeCategoryFormModal({ isOpen, onClose, editingCategoryCode }: CodeCategoryFormModalProps) {
  // const { getText } = useMultiLang(); // 무한 루프 방지를 위해 임시 제거
  const { categories, createCategory, updateCategory } = useCommonCode();

  // 폼 상태
  const [formData, setFormData] = useState({
    categoryCode: "",
    categoryName: "",
    categoryNameEng: "",
    description: "",
    sortOrder: 0,
    isActive: true,
  });

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 수정 모드일 때 기존 데이터 로드
  useEffect(() => {
    if (editingCategoryCode && categories.length > 0) {
      const category = categories.find((c) => c.category_code === editingCategoryCode);
      if (category) {
        setFormData({
          categoryCode: category.category_code,
          categoryName: category.category_name,
          categoryNameEng: category.category_name_eng || "",
          description: category.description || "",
          sortOrder: category.sort_order,
          isActive: category.is_active === "Y",
        });
      }
    } else {
      // 새 카테고리일 때 초기값
      setFormData({
        categoryCode: "",
        categoryName: "",
        categoryNameEng: "",
        description: "",
        sortOrder: 0,
        isActive: true,
      });
    }
    setErrors({});
  }, [editingCategoryCode, categories, isOpen]);

  // 입력값 검증
  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.categoryCode.trim()) {
      newErrors.categoryCode = "필수 입력 항목입니다.";
    }

    if (!formData.categoryName.trim()) {
      newErrors.categoryName = "필수 입력 항목입니다.";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 폼 제출 핸들러
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    setLoading(true);

    try {
      if (editingCategoryCode) {
        // 수정
        await updateCategory(editingCategoryCode, {
          categoryName: formData.categoryName,
          categoryNameEng: formData.categoryNameEng,
          description: formData.description,
          sortOrder: formData.sortOrder,
          isActive: formData.isActive,
        });
      } else {
        // 생성
        await createCategory({
          categoryCode: formData.categoryCode,
          categoryName: formData.categoryName,
          categoryNameEng: formData.categoryNameEng,
          description: formData.description,
          sortOrder: formData.sortOrder,
        });
      }

      onClose();
    } catch (error) {
      console.error("카테고리 저장 오류:", error);
      // 에러 처리는 useCommonCode 훅에서 처리됨
    } finally {
      setLoading(false);
    }
  };

  // 입력값 변경 핸들러
  const handleChange = (field: string, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));

    // 에러 제거
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{editingCategoryCode ? "카테고리 수정" : "새 카테고리"}</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* 카테고리 코드 */}
          <div className="space-y-2">
            <Label htmlFor="categoryCode">{"카테고리 코드"} *</Label>
            <Input
              id="categoryCode"
              value={formData.categoryCode}
              onChange={(e) => handleChange("categoryCode", e.target.value)}
              disabled={!!editingCategoryCode || loading}
              placeholder={"카테고리 코드를 입력하세요"}
              className={errors.categoryCode ? "border-red-500" : ""}
            />
            {errors.categoryCode && <p className="text-sm text-red-600">{errors.categoryCode}</p>}
          </div>

          {/* 카테고리명 */}
          <div className="space-y-2">
            <Label htmlFor="categoryName">{"카테고리명"} *</Label>
            <Input
              id="categoryName"
              value={formData.categoryName}
              onChange={(e) => handleChange("categoryName", e.target.value)}
              disabled={loading}
              placeholder={"카테고리명을 입력하세요"}
              className={errors.categoryName ? "border-red-500" : ""}
            />
            {errors.categoryName && <p className="text-sm text-red-600">{errors.categoryName}</p>}
          </div>

          {/* 영문명 */}
          <div className="space-y-2">
            <Label htmlFor="categoryNameEng">{"카테고리 영문명"}</Label>
            <Input
              id="categoryNameEng"
              value={formData.categoryNameEng}
              onChange={(e) => handleChange("categoryNameEng", e.target.value)}
              disabled={loading}
              placeholder={"카테고리 영문명을 입력하세요"}
            />
          </div>

          {/* 설명 */}
          <div className="space-y-2">
            <Label htmlFor="description">{"설명"}</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleChange("description", e.target.value)}
              disabled={loading}
              placeholder={"설명을 입력하세요"}
              rows={3}
            />
          </div>

          {/* 정렬 순서 */}
          <div className="space-y-2">
            <Label htmlFor="sortOrder">{"정렬 순서"}</Label>
            <Input
              id="sortOrder"
              type="number"
              value={formData.sortOrder}
              onChange={(e) => handleChange("sortOrder", parseInt(e.target.value) || 0)}
              disabled={loading}
              min={0}
            />
          </div>

          {/* 활성 상태 (수정 시에만) */}
          {editingCategoryCode && (
            <div className="flex items-center space-x-2">
              <Switch
                id="isActive"
                checked={formData.isActive}
                onCheckedChange={(checked) => handleChange("isActive", checked)}
                disabled={loading}
              />
              <Label htmlFor="isActive">{"활성"}</Label>
            </div>
          )}

          {/* 버튼 */}
          <div className="flex justify-end space-x-2 pt-4">
            <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
              {"취소"}
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? (
                <>
                  <LoadingSpinner size="sm" className="mr-2" />
                  {"저장 중..."}
                </>
              ) : (
                "저장"
              )}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
