'use client';

import { useState, useCallback } from 'react';
import { useItemMaster } from '@/contexts/ItemMasterContext';
import { getErrorMessage } from '@/lib/api/error-handler';
import { toast } from 'sonner';
import type { ItemPage } from '@/contexts/ItemMasterContext';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

export interface UseImportManagementReturn {
  // 섹션 Import 상태
  isImportSectionDialogOpen: boolean;
  setIsImportSectionDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
  selectedImportSectionId: number | null;
  setSelectedImportSectionId: React.Dispatch<React.SetStateAction<number | null>>;

  // 필드 Import 상태
  isImportFieldDialogOpen: boolean;
  setIsImportFieldDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
  selectedImportFieldId: number | null;
  setSelectedImportFieldId: React.Dispatch<React.SetStateAction<number | null>>;
  importFieldTargetSectionId: number | null;
  setImportFieldTargetSectionId: React.Dispatch<React.SetStateAction<number | null>>;

  // 핸들러
  handleImportSection: (selectedPageId: number | null) => Promise<void>;
  handleImportField: (selectedPage: ItemPage | null) => Promise<void>;
  handleCloneSection: (sectionId: number) => Promise<void>;
}

export function useImportManagement(): UseImportManagementReturn {
  const {
    linkSectionToPage,
    linkFieldToSection,
    cloneSection,
  } = useItemMaster();

  // 섹션 Import 상태
  const [isImportSectionDialogOpen, setIsImportSectionDialogOpen] = useState(false);
  const [selectedImportSectionId, setSelectedImportSectionId] = useState<number | null>(null);

  // 필드 Import 상태
  const [isImportFieldDialogOpen, setIsImportFieldDialogOpen] = useState(false);
  const [selectedImportFieldId, setSelectedImportFieldId] = useState<number | null>(null);
  const [importFieldTargetSectionId, setImportFieldTargetSectionId] = useState<number | null>(null);

  // 섹션 불러오기 핸들러
  const handleImportSection = useCallback(async (selectedPageId: number | null) => {
    if (!selectedPageId || !selectedImportSectionId) return;

    try {
      await linkSectionToPage(selectedPageId, selectedImportSectionId);
      toast.success('섹션을 불러왔습니다.');
      setSelectedImportSectionId(null);
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('섹션 불러오기 실패:', error);
      toast.error(getErrorMessage(error));
    }
  }, [selectedImportSectionId, linkSectionToPage]);

  // 필드 불러오기 핸들러
  const handleImportField = useCallback(async (selectedPage: ItemPage | null) => {
    if (!importFieldTargetSectionId || !selectedImportFieldId) return;

    try {
      // 해당 섹션의 마지막 순서 + 1로 설정
      const targetSection = selectedPage?.sections.find(s => s.id === importFieldTargetSectionId);
      const existingFieldsCount = targetSection?.fields?.length ?? 0;
      const newOrderNo = existingFieldsCount;

      await linkFieldToSection(importFieldTargetSectionId, selectedImportFieldId, newOrderNo);
      toast.success('필드를 섹션에 연결했습니다.');

      setSelectedImportFieldId(null);
      setImportFieldTargetSectionId(null);
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('필드 불러오기 실패:', error);
      toast.error(getErrorMessage(error));
    }
  }, [importFieldTargetSectionId, selectedImportFieldId, linkFieldToSection]);

  // 섹션 복제 핸들러
  const handleCloneSection = useCallback(async (sectionId: number) => {
    try {
      await cloneSection(sectionId);
      toast.success('섹션이 복제되었습니다.');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('섹션 복제 실패:', error);
      toast.error(getErrorMessage(error));
    }
  }, [cloneSection]);

  return {
    // 섹션 Import
    isImportSectionDialogOpen,
    setIsImportSectionDialogOpen,
    selectedImportSectionId,
    setSelectedImportSectionId,

    // 필드 Import
    isImportFieldDialogOpen,
    setIsImportFieldDialogOpen,
    selectedImportFieldId,
    setSelectedImportFieldId,
    importFieldTargetSectionId,
    setImportFieldTargetSectionId,

    // 핸들러
    handleImportSection,
    handleImportField,
    handleCloneSection,
  };
}