"use client";

import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { ResizableDialog, ResizableDialogContent, ResizableDialogHeader, DialogTitle } from "@/components/ui/resizable-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 { LoadingSpinner } from "@/components/common/LoadingSpinner";
import { ValidationMessage } from "@/components/common/ValidationMessage";
import { useCreateCategory, useUpdateCategory } from "@/hooks/queries/useCategories";
import type { CodeCategory } from "@/types/commonCode";
import { useCheckCategoryDuplicate } from "@/hooks/queries/useValidation";
import { useState } from "react";
import {
  createCategorySchema,
  updateCategorySchema,
  type CreateCategoryData,
  type UpdateCategoryData,
} from "@/lib/schemas/commonCode";

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

export function CodeCategoryFormModal({
  isOpen,
  onClose,
  editingCategoryCode,
  categories,
}: CodeCategoryFormModalProps) {
  const createCategoryMutation = useCreateCategory();
  const updateCategoryMutation = useUpdateCategory();

  const isEditing = !!editingCategoryCode;
  const editingCategory = categories.find((c) => c.category_code === editingCategoryCode);

  // 생성과 수정을 위한 별도 폼 설정
  const createForm = useForm<CreateCategoryData>({
    resolver: zodResolver(createCategorySchema),
    mode: "onChange",
    defaultValues: {
      categoryCode: "",
      categoryName: "",
      categoryNameEng: "",
      description: "",
      sortOrder: 1,
    },
  });

  const updateForm = useForm<UpdateCategoryData>({
    resolver: zodResolver(updateCategorySchema),
    mode: "onChange",
    defaultValues: {
      categoryName: "",
      categoryNameEng: "",
      description: "",
      sortOrder: 1,
      isActive: "Y",
    },
  });

  // 필드 검증 상태 관리
  const [validatedFields, setValidatedFields] = useState<Set<string>>(new Set());

  // 필드 검증 처리 함수
  const handleFieldBlur = (fieldName: string) => {
    setValidatedFields((prev) => new Set(prev).add(fieldName));
  };

  // 중복 검사 훅들
  const categoryCodeCheck = useCheckCategoryDuplicate(
    "categoryCode",
    isEditing ? "" : createForm.watch("categoryCode"),
    isEditing ? editingCategoryCode : undefined,
    validatedFields.has("categoryCode"),
  );

  const categoryNameCheck = useCheckCategoryDuplicate(
    "categoryName",
    isEditing ? updateForm.watch("categoryName") : createForm.watch("categoryName"),
    isEditing ? editingCategoryCode : undefined,
    validatedFields.has("categoryName"),
  );

  const categoryNameEngCheck = useCheckCategoryDuplicate(
    "categoryNameEng",
    isEditing ? updateForm.watch("categoryNameEng") : createForm.watch("categoryNameEng"),
    isEditing ? editingCategoryCode : undefined,
    validatedFields.has("categoryNameEng"),
  );

  // 중복 검사 결과 확인 (수정 시에는 카테고리 코드 검사 제외)
  const hasDuplicateErrors =
    (!isEditing && categoryCodeCheck.data?.isDuplicate && validatedFields.has("categoryCode")) ||
    (categoryNameCheck.data?.isDuplicate && validatedFields.has("categoryName")) ||
    (categoryNameEngCheck.data?.isDuplicate && validatedFields.has("categoryNameEng"));

  // 중복 검사 로딩 중인지 확인 (수정 시에는 카테고리 코드 검사 제외)
  const isDuplicateChecking =
    (!isEditing && categoryCodeCheck.isLoading) || categoryNameCheck.isLoading || categoryNameEngCheck.isLoading;

  // 폼은 조건부로 직접 사용

  // 편집 모드일 때 기존 데이터 로드
  useEffect(() => {
    if (isOpen) {
      // 검증 상태 초기화
      setValidatedFields(new Set());

      if (isEditing && editingCategory) {
        // 수정 모드: 기존 데이터 로드
        updateForm.reset({
          categoryName: editingCategory.category_name,
          categoryNameEng: editingCategory.category_name_eng || "",
          description: editingCategory.description || "",
          sortOrder: editingCategory.sort_order,
          isActive: editingCategory.is_active as "Y" | "N", // 타입 안전한 캐스팅
        });
      } else {
        // 새 카테고리 모드: 자동 순서 계산
        const maxSortOrder = categories.length > 0 ? Math.max(...categories.map((c) => c.sort_order)) : 0;

        createForm.reset({
          categoryCode: "",
          categoryName: "",
          categoryNameEng: "",
          description: "",
          sortOrder: maxSortOrder + 1,
        });
      }
    }
  }, [isOpen, isEditing, editingCategory, categories, createForm, updateForm]);

  const handleSubmit = isEditing
    ? updateForm.handleSubmit(async (data) => {
        try {
          await updateCategoryMutation.mutateAsync({
            categoryCode: editingCategoryCode!,
            data: data as UpdateCategoryData,
          });
          onClose();
          updateForm.reset();
        } catch (error) {
          console.error("카테고리 수정 실패:", error);
        }
      })
    : createForm.handleSubmit(async (data) => {
        try {
          await createCategoryMutation.mutateAsync(data as CreateCategoryData);
          onClose();
          createForm.reset();
        } catch (error) {
          console.error("카테고리 생성 실패:", error);
        }
      });

  const isLoading = createCategoryMutation.isPending || updateCategoryMutation.isPending;

  return (
    <ResizableDialog open={isOpen} onOpenChange={onClose}>
      <ResizableDialogContent className="max-w-[95vw] sm:max-w-[500px]">
        <ResizableDialogHeader>
          <ResizableDialogTitle className="text-base sm:text-lg">{isEditing ? "카테고리 수정" : "새 카테고리"}</ResizableDialogTitle>
        </ResizableDialogHeader>

        <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
          {/* 카테고리 코드 */}
          {!isEditing && (
            <div className="space-y-2">
              <Label htmlFor="categoryCode" className="text-xs sm:text-sm">카테고리 코드 *</Label>
              <Input
                id="categoryCode"
                {...createForm.register("categoryCode")}
                disabled={isLoading}
                placeholder="카테고리 코드를 입력하세요"
                className={createForm.formState.errors.categoryCode ? "h-8 text-xs sm:h-10 sm:text-sm border-destructive" : "h-8 text-xs sm:h-10 sm:text-sm"}
                onBlur={() => handleFieldBlur("categoryCode")}
              />
              {createForm.formState.errors.categoryCode && (
                <p className="text-[10px] sm:text-xs text-destructive">{createForm.formState.errors.categoryCode.message}</p>
              )}
              {!createForm.formState.errors.categoryCode && (
                <ValidationMessage
                  message={categoryCodeCheck.data?.message}
                  isValid={!categoryCodeCheck.data?.isDuplicate}
                  isLoading={categoryCodeCheck.isLoading}
                />
              )}
            </div>
          )}

          {/* 카테고리 코드 표시 (수정 시) */}
          {isEditing && editingCategory && (
            <div className="space-y-2">
              <Label htmlFor="categoryCodeDisplay" className="text-xs sm:text-sm">카테고리 코드</Label>
              <Input id="categoryCodeDisplay" value={editingCategory.category_code} disabled className="h-8 text-xs sm:h-10 sm:text-sm bg-muted cursor-not-allowed" />
              <p className="text-[10px] sm:text-xs text-muted-foreground">카테고리 코드는 수정할 수 없습니다.</p>
            </div>
          )}

          {/* 카테고리명 */}
          <div className="space-y-2">
            <Label htmlFor="categoryName">카테고리명 *</Label>
            <Input
              id="categoryName"
              {...(isEditing ? updateForm.register("categoryName") : createForm.register("categoryName"))}
              disabled={isLoading}
              placeholder="카테고리명을 입력하세요"
              className={
                isEditing
                  ? updateForm.formState.errors.categoryName
                    ? "border-destructive"
                    : ""
                  : createForm.formState.errors.categoryName
                    ? "border-destructive"
                    : ""
              }
              onBlur={() => handleFieldBlur("categoryName")}
            />
            {isEditing
              ? updateForm.formState.errors.categoryName && (
                  <p className="text-sm text-destructive">{updateForm.formState.errors.categoryName.message}</p>
                )
              : createForm.formState.errors.categoryName && (
                  <p className="text-sm text-destructive">{createForm.formState.errors.categoryName.message}</p>
                )}
            {!(isEditing ? updateForm.formState.errors.categoryName : createForm.formState.errors.categoryName) && (
              <ValidationMessage
                message={categoryNameCheck.data?.message}
                isValid={!categoryNameCheck.data?.isDuplicate}
                isLoading={categoryNameCheck.isLoading}
              />
            )}
          </div>

          {/* 영문명 */}
          <div className="space-y-2">
            <Label htmlFor="categoryNameEng">카테고리 영문명 *</Label>
            <Input
              id="categoryNameEng"
              {...(isEditing ? updateForm.register("categoryNameEng") : createForm.register("categoryNameEng"))}
              disabled={isLoading}
              placeholder="카테고리 영문명을 입력하세요"
              className={
                isEditing
                  ? updateForm.formState.errors.categoryNameEng
                    ? "border-destructive"
                    : ""
                  : createForm.formState.errors.categoryNameEng
                    ? "border-destructive"
                    : ""
              }
              onBlur={() => handleFieldBlur("categoryNameEng")}
            />
            {isEditing
              ? updateForm.formState.errors.categoryNameEng && (
                  <p className="text-sm text-destructive">{updateForm.formState.errors.categoryNameEng.message}</p>
                )
              : createForm.formState.errors.categoryNameEng && (
                  <p className="text-sm text-destructive">{createForm.formState.errors.categoryNameEng.message}</p>
                )}
            {!(isEditing
              ? updateForm.formState.errors.categoryNameEng
              : createForm.formState.errors.categoryNameEng) && (
              <ValidationMessage
                message={categoryNameEngCheck.data?.message}
                isValid={!categoryNameEngCheck.data?.isDuplicate}
                isLoading={categoryNameEngCheck.isLoading}
              />
            )}
          </div>

          {/* 설명 */}
          <div className="space-y-2">
            <Label htmlFor="description">설명 *</Label>
            <Textarea
              id="description"
              {...(isEditing ? updateForm.register("description") : createForm.register("description"))}
              disabled={isLoading}
              placeholder="설명을 입력하세요"
              rows={3}
              className={
                isEditing
                  ? updateForm.formState.errors.description
                    ? "border-destructive"
                    : ""
                  : createForm.formState.errors.description
                    ? "border-destructive"
                    : ""
              }
              onBlur={() => handleFieldBlur("description")}
            />
            {isEditing
              ? updateForm.formState.errors.description && (
                  <p className="text-sm text-destructive">{updateForm.formState.errors.description.message}</p>
                )
              : createForm.formState.errors.description && (
                  <p className="text-sm text-destructive">{createForm.formState.errors.description.message}</p>
                )}
          </div>

          {/* 정렬 순서 */}
          <div className="space-y-2">
            <Label htmlFor="sortOrder">정렬 순서</Label>
            <Input
              id="sortOrder"
              type="number"
              {...(isEditing
                ? updateForm.register("sortOrder", { valueAsNumber: true })
                : createForm.register("sortOrder", { valueAsNumber: true }))}
              disabled={isLoading}
              min={1}
              className={
                isEditing
                  ? updateForm.formState.errors.sortOrder
                    ? "border-destructive"
                    : ""
                  : createForm.formState.errors.sortOrder
                    ? "border-destructive"
                    : ""
              }
            />
            {isEditing
              ? updateForm.formState.errors.sortOrder && (
                  <p className="text-sm text-destructive">{updateForm.formState.errors.sortOrder.message}</p>
                )
              : createForm.formState.errors.sortOrder && (
                  <p className="text-sm text-destructive">{createForm.formState.errors.sortOrder.message}</p>
                )}
          </div>

          {/* 활성 상태 (수정 시에만) */}
          {isEditing && (
            <div className="flex items-center space-x-2">
              <Switch
                id="isActive"
                checked={updateForm.watch("isActive") === "Y"}
                onCheckedChange={(checked) => updateForm.setValue("isActive", checked ? "Y" : "N")}
                disabled={isLoading}
              />
              <Label htmlFor="isActive">{updateForm.watch("isActive") === "Y" ? "활성" : "비활성"}</Label>
            </div>
          )}

          {/* 버튼 */}
          <div className="flex gap-2 pt-4 sm:justify-end sm:gap-0">
            <Button 
              type="button" 
              variant="outline" 
              onClick={onClose} 
              disabled={isLoading}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              취소
            </Button>
            <Button
              type="submit"
              disabled={
                isLoading ||
                !(isEditing ? updateForm.formState.isValid : createForm.formState.isValid) ||
                hasDuplicateErrors ||
                isDuplicateChecking
              }
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              {isLoading ? (
                <>
                  <LoadingSpinner size="sm" className="mr-2" />
                  {isEditing ? "수정 중..." : "저장 중..."}
                </>
              ) : isEditing ? (
                "카테고리 수정"
              ) : (
                "카테고리 저장"
              )}
            </Button>
          </div>
        </form>
      </ResizableDialogContent>
    </ResizableDialog>
  );
}
