import { useFormikContext } from 'formik';
import React from 'react'
import { moveToBottom, moveToTop } from '../utils/reOrder';
type FormValues = {
  Questions: Array<{ id: string; sub_order?: number } & Record<string, any>>;
};

export function useReOrderQuestions() {
    const {setFieldValue,values} = useFormikContext<FormValues>()

          const withSubOrder = (arr: any[]) => arr.map((it, i) => ({ ...it, sub_order: i }));
    
    const scrollToIdWithOffset = (id: string) => {
      const el = document.getElementById(id);
      if (!el) return;
      const top = el.getBoundingClientRect().top ;
      console.log(el.getBoundingClientRect())
      window.scrollBy({ top, behavior: "smooth" });
    };
    
    const afterLayout = (fn: () => void) => {
      requestAnimationFrame(() => requestAnimationFrame(fn));
    };
    
        const moveItemUp = (item:any,index: number) => {
          if (index <= 0) return;
          const next = moveToTop(index, values.Questions);
          setFieldValue("Questions", withSubOrder(next));
      afterLayout(() => scrollToIdWithOffset(`q-${item.id || item.unique}`));
    
        };
    
        const moveItemDown = (item:any,index: number) => {
          if (index >= values.Questions.length - 1) return;
          const next = moveToBottom(index, values.Questions);
          setFieldValue("Questions", withSubOrder(next));
      afterLayout(() => scrollToIdWithOffset(`q-${item.id || item.unique}`));
    
        };

        return { moveItemDown , moveItemUp }
}

