"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";

interface CodeFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  categoryCode: string;
  editingCodeValue?: string;
}

export function CodeFormModal({ isOpen, onClose, categoryCode, editingCodeValue }: CodeFormModalProps) {
  // const { getText } = useMultiLang(); // 무한 루프 방지를 위해 임시 제거
  const { codes, createCode, updateCode } = useCommonCode();

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

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

  // 수정 모드일 때 기존 데이터 로드
  useEffect(() => {
    if (editingCodeValue && codes.length > 0) {
      const code = codes.find((c) => c.code_value === editingCodeValue);
      if (code) {
        setFormData({
          codeValue: code.code_value,
          codeName: code.code_name,
          codeNameEng: code.code_name_eng || "",
          description: code.description || "",
          sortOrder: code.sort_order,
          isActive: code.is_active === "Y",
        });
      }
    } else {
      // 새 코드일 때 초기값
      setFormData({
        codeValue: "",
        codeName: "",
        codeNameEng: "",
        description: "",
        sortOrder: 0,
        isActive: true,
      });
    }
    setErrors({});
  }, [editingCodeValue, codes, isOpen]);

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

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

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

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

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

    if (!validateForm()) return;

    setLoading(true);

    try {
      if (editingCodeValue) {
        // 수정
        await updateCode(categoryCode, editingCodeValue, {
          codeName: formData.codeName,
          codeNameEng: formData.codeNameEng,
          description: formData.description,
          sortOrder: formData.sortOrder,
          isActive: formData.isActive,
        });
      } else {
        // 생성
        await createCode(categoryCode, {
          codeValue: formData.codeValue,
          codeName: formData.codeName,
          codeNameEng: formData.codeNameEng,
          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>{editingCodeValue ? "코드 수정" : "새 코드"}</DialogTitle>
        </DialogHeader>

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

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

          {/* 영문명 */}
          <div className="space-y-2">
            <Label htmlFor="codeNameEng">{"코드 영문명"}</Label>
            <Input
              id="codeNameEng"
              value={formData.codeNameEng}
              onChange={(e) => handleChange("codeNameEng", 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>

          {/* 활성 상태 (수정 시에만) */}
          {editingCodeValue && (
            <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>
  );
}
