"use client";

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

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

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

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

  // 검증 상태 관리
  const [validationStates, setValidationStates] = useState({
    categoryCode: { enabled: false, value: "" },
    categoryName: { enabled: false, value: "" },
    categoryNameEng: { enabled: false, value: "" },
    description: { enabled: false, value: "" }, // 설명 필드 추가
  });

  // 중복 검사 훅들
  const categoryCodeCheck = useCheckCategoryDuplicate(
    "categoryCode",
    validationStates.categoryCode.value,
    isEditing ? editingCategoryCode : undefined,
    validationStates.categoryCode.enabled,
  );

  const categoryNameCheck = useCheckCategoryDuplicate(
    "categoryName",
    validationStates.categoryName.value,
    isEditing ? editingCategoryCode : undefined,
    validationStates.categoryName.enabled,
  );

  const categoryNameEngCheck = useCheckCategoryDuplicate(
    "categoryNameEng",
    validationStates.categoryNameEng.value,
    isEditing ? editingCategoryCode : undefined,
    validationStates.categoryNameEng.enabled,
  );

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

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

  // 필수 필드들이 모두 검증되었는지 확인 (생성 시에만 적용)
  const requiredFieldsValidated =
    isEditing ||
    (validationStates.categoryCode.enabled &&
      validationStates.categoryName.enabled &&
      validationStates.categoryNameEng.enabled &&
      validationStates.description.enabled);

  // 폼 스키마 선택 (생성/수정에 따라)
  const schema = isEditing ? updateCategorySchema : createCategorySchema;

  const form = useForm<CreateCategoryData | UpdateCategoryData>({
    resolver: zodResolver(schema),
    mode: "onChange", // 실시간 검증 활성화
    defaultValues: {
      categoryCode: "",
      categoryName: "",
      categoryNameEng: "",
      description: "",
      sortOrder: 1,
      ...(isEditing && { isActive: true }),
    },
  });

  // 편집 모드일 때 기존 데이터 로드
  useEffect(() => {
    if (isOpen) {
      if (isEditing && editingCategory) {
        // 수정 모드: 기존 데이터 로드
        form.reset({
          categoryCode: editingCategory.category_code, // 카테고리 코드도 표시
          categoryName: editingCategory.category_name,
          categoryNameEng: editingCategory.category_name_eng || "",
          description: editingCategory.description || "",
          sortOrder: editingCategory.sort_order,
          isActive: editingCategory.is_active, // 🔧 "Y"/"N" 문자열 그대로 사용
        });
      } else {
        // 새 카테고리 모드: 자동 순서 계산
        const maxSortOrder = categories.length > 0 ? Math.max(...categories.map((c) => c.sort_order)) : 0;

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

  const handleSubmit = form.handleSubmit(async (data) => {
    try {
      if (isEditing && editingCategoryCode) {
        // 수정
        await updateCategoryMutation.mutateAsync({
          categoryCode: editingCategoryCode,
          data: data as UpdateCategoryData,
        });
      } else {
        // 생성
        await createCategoryMutation.mutateAsync(data as CreateCategoryData);
      }

      onClose();
      form.reset();
    } catch (error) {
      console.error("카테고리 저장 실패:", error);
    }
  });

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

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

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* 카테고리 코드 */}
          {
            <div className="space-y-2">
              <Label htmlFor="categoryCode">카테고리 코드 *</Label>
              <Input
                id="categoryCode"
                {...form.register("categoryCode")}
                disabled={isLoading || isEditing} // 수정 시에는 비활성화
                placeholder="카테고리 코드를 입력하세요"
                className={form.formState.errors.categoryCode ? "border-red-500" : ""}
                onBlur={(e) => {
                  const value = e.target.value.trim();
                  if (value) {
                    setValidationStates((prev) => ({
                      ...prev,
                      categoryCode: { enabled: true, value },
                    }));
                  }
                }}
              />
              {form.formState.errors.categoryCode && (
                <p className="text-sm text-red-600">{form.formState.errors.categoryCode.message}</p>
              )}
              {!isEditing && !form.formState.errors.categoryCode && (
                <ValidationMessage
                  message={categoryCodeCheck.data?.message}
                  isValid={!categoryCodeCheck.data?.isDuplicate}
                  isLoading={categoryCodeCheck.isLoading}
                />
              )}
            </div>
          }

          {/* 카테고리명 */}
          <div className="space-y-2">
            <Label htmlFor="categoryName">카테고리명 *</Label>
            <Input
              id="categoryName"
              {...form.register("categoryName")}
              disabled={isLoading}
              placeholder="카테고리명을 입력하세요"
              className={form.formState.errors.categoryName ? "border-red-500" : ""}
              onBlur={(e) => {
                const value = e.target.value.trim();
                if (value) {
                  setValidationStates((prev) => ({
                    ...prev,
                    categoryName: { enabled: true, value },
                  }));
                }
              }}
            />
            {form.formState.errors.categoryName && (
              <p className="text-sm text-red-600">{form.formState.errors.categoryName.message}</p>
            )}
            {!form.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"
              {...form.register("categoryNameEng")}
              disabled={isLoading}
              placeholder="카테고리 영문명을 입력하세요"
              className={form.formState.errors.categoryNameEng ? "border-red-500" : ""}
              onBlur={(e) => {
                const value = e.target.value.trim();
                if (value) {
                  setValidationStates((prev) => ({
                    ...prev,
                    categoryNameEng: { enabled: true, value },
                  }));
                }
              }}
            />
            {form.formState.errors.categoryNameEng && (
              <p className="text-sm text-red-600">{form.formState.errors.categoryNameEng.message}</p>
            )}
            {!form.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"
              {...form.register("description")}
              disabled={isLoading}
              placeholder="설명을 입력하세요"
              rows={3}
              className={form.formState.errors.description ? "border-red-500" : ""}
              onBlur={(e) => {
                const value = e.target.value.trim();
                if (value) {
                  setValidationStates((prev) => ({
                    ...prev,
                    description: { enabled: true, value },
                  }));
                }
              }}
            />
            {form.formState.errors.description && (
              <p className="text-sm text-red-600">{form.formState.errors.description.message}</p>
            )}
          </div>

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

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

          {/* 버튼 */}
          <div className="flex justify-end space-x-2 pt-4">
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              취소
            </Button>
            <Button
              type="submit"
              disabled={isLoading || !form.formState.isValid || hasDuplicateErrors || isDuplicateChecking}
            >
              {isLoading ? (
                <>
                  <LoadingSpinner size="sm" className="mr-2" />
                  {isEditing ? "수정 중..." : "저장 중..."}
                </>
              ) : isEditing ? (
                "카테고리 수정"
              ) : (
                "카테고리 저장"
              )}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
