'use client';

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

export interface UseReorderManagementReturn {
  moveSection: (selectedPage: ItemPage | null, dragIndex: number, hoverIndex: number) => Promise<void>;
  moveField: (selectedPage: ItemPage | null, sectionId: number, dragFieldId: number, hoverFieldId: number) => Promise<void>;
}

export function useReorderManagement(): UseReorderManagementReturn {
  const {
    reorderSections,
    reorderFields,
  } = useItemMaster();

  // 섹션 순서 변경 핸들러 (드래그앤드롭)
  const moveSection = useCallback(async (
    selectedPage: ItemPage | null,
    dragIndex: number,
    hoverIndex: number
  ) => {
    if (!selectedPage) return;

    const sections = [...selectedPage.sections];
    const [draggedSection] = sections.splice(dragIndex, 1);
    sections.splice(hoverIndex, 0, draggedSection);

    const sectionIds = sections.map(s => s.id);

    try {
      await reorderSections(selectedPage.id, sectionIds);
      toast.success('섹션 순서가 변경되었습니다');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('섹션 순서 변경 실패:', error);
      toast.error('섹션 순서 변경에 실패했습니다');
    }
  }, [reorderSections]);

  // 필드 순서 변경 핸들러
  const moveField = useCallback(async (
    selectedPage: ItemPage | null,
    sectionId: number,
    dragFieldId: number,
    hoverFieldId: number
  ) => {
    if (!selectedPage) return;
    const section = selectedPage.sections.find(s => s.id === sectionId);
    if (!section || !section.fields) return;

    // 동일 필드면 스킵
    if (dragFieldId === hoverFieldId) return;

    // 정렬된 배열에서 ID로 인덱스 찾기
    const sortedFields = [...section.fields].sort((a, b) => (a.order_no ?? 0) - (b.order_no ?? 0));
    const dragIndex = sortedFields.findIndex(f => f.id === dragFieldId);
    const hoverIndex = sortedFields.findIndex(f => f.id === hoverFieldId);

    // 유효하지 않은 인덱스 체크
    if (dragIndex === -1 || hoverIndex === -1) {
      return;
    }

    // 드래그된 필드를 제거하고 새 위치에 삽입
    const [draggedField] = sortedFields.splice(dragIndex, 1);
    sortedFields.splice(hoverIndex, 0, draggedField);

    const newFieldIds = sortedFields.map(f => f.id);

    try {
      await reorderFields(sectionId, newFieldIds);
      toast.success('항목 순서가 변경되었습니다');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('항목 순서 변경에 실패했습니다');
    }
  }, [reorderFields]);

  return {
    moveSection,
    moveField,
  };
}