"use client";

import { Step } from "@/components/ui/Stepper";

import { useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";


interface IPageTypeFields {
    type: "company" | "organization";
    language?: string;
    company_name?: string;
    country?: string;
    key: string;
}

const TOTAL_STEPS = 7;

const useMarketingForm = (
    initialData: any,
    onSubmit: (data: any) => void,
) => {

    const [step, setStep] = useState(0);
    const [formData, setFormData] = useState<any>(initialData || {});
    const [stepValidity, setStepValidity] = useState<boolean[]>(() =>
        new Array(TOTAL_STEPS).fill(false),
    );
    const heroRef = useRef<any>(null);
    const chartRef = useRef<any>(null);
    const featuresRef = useRef<any>(null);
    const challengesRef = useRef<any>(null);
    const benefitsRef = useRef<any>(null);
    const contactsRef = useRef<any>(null);
    const footerRef = useRef<any>(null);

    const {
        register: registerPageType,
        watch: watchPageType,
        formState: { errors: pageTypeErrors, isValid: isPageTypeValid },
        getValues: getPageTypeValues,
        setValue,
        reset,
        trigger: triggerPageType,
    } = useForm<IPageTypeFields>({
        mode: "onChange",
        defaultValues: {
            type: "company",
            language: "en",
            country: "USA",
            company_name: "",
            key: "",
        },
    });

    // Stable per-step callbacks so each step form can report its live validity
    // without recreating handlers (which would re-fire the reporting effect).
    const stepValidityHandlers = useMemo(
        () =>
            Array.from(
                { length: TOTAL_STEPS },
                (_, index) => (valid: boolean) =>
                    setStepValidity((prev) => {
                        if (prev[index] === valid) return prev;
                        const next = [...prev];
                        next[index] = valid;
                        return next;
                    }),
            ),
        [],
    );

    const isCurrentStepValid = isPageTypeValid && Boolean(stepValidity[step]);

    useEffect(() => {
        if (initialData) {
            const formValues = {
                type: initialData.type || "company",
                language: initialData.language ?? "en",
                company_name: initialData.company_name || "",
                country: initialData.country ?? "USA",
                key: initialData.key || "",
            };
            reset(formValues);
            setFormData(initialData);
        }
    }, [initialData, reset]);

    const pageType = watchPageType("type");
    const isCompany = pageType === "company";

    const saveCurrentStepData = async () => {
        const refs = [
            heroRef,
            chartRef,
            featuresRef,
            challengesRef,
            benefitsRef,
            contactsRef,
            footerRef,
        ];

        const keys = [
            "hero",
            "chart",
            "features",
            "challenges",
            "advantages",
            "contact",
            "footer",
        ];

        const currentRef = refs[step];
        if (currentRef?.current?.getData) {
            try {
                const data = await currentRef.current.getData();
                setFormData((prev: any) => ({
                    ...prev,
                    [keys[step]]: data,
                }));
            } catch (error) {
                console.error(`Error collecting data from step ${step}:`, error);
            }
        }
    };

    const collectAllStepsData = async () => {
        await saveCurrentStepData();

        const refs = [
            heroRef,
            chartRef,
            featuresRef,
            challengesRef,
            benefitsRef,
            contactsRef,
            footerRef,
        ];

        const allData: any = { ...formData };

        const keys = [
            "hero",
            "chart",
            "features",
            "challenges",
            "advantages",
            "contact",
            "footer",
        ];

        for (let i = 0; i < refs.length; i++) {
            const ref = refs[i];
            if (ref?.current?.getData) {
                try {
                    const data = await ref.current.getData();
                    allData[keys[i]] = data;
                } catch (error) {
                    console.error(`Error collecting data from step ${i}:`, error);
                }
            }
        }

        return allData;
    };

    const stepRefs = [
        heroRef,
        chartRef,
        featuresRef,
        challengesRef,
        benefitsRef,
        contactsRef,
        footerRef,
    ];

    const validateCurrentStep = async () => {
        const isPageTypeValid = await triggerPageType();
        const currentRef = stepRefs[step];
        const isStepValid = currentRef?.current?.validate
            ? await currentRef.current.validate()
            : true;
        return isPageTypeValid && isStepValid;
    };

    const validateAllSteps = async () => {
        const isPageTypeValid = await triggerPageType();
        const results = await Promise.all(
            stepRefs.map((ref) =>
                ref?.current?.validate ? ref.current.validate() : Promise.resolve(true),
            ),
        );
        return isPageTypeValid && results.every(Boolean);
    };

    const handleSubmitAll = async () => {
        const isValid = await validateAllSteps();
        if (!isValid) return;

        const allData = await collectAllStepsData();
        const pageTypeData = getPageTypeValues();

        const finalData = {
            ...allData,
            type: pageTypeData.type,
            key: pageTypeData.key,
            ...(pageTypeData.type === "company" && {
                language: pageTypeData.language,
                company_name: pageTypeData.company_name,
                country: pageTypeData.country,
            }),
        };

        onSubmit(finalData);
    };

    const steps: Step[] = [
        {
            title: "Hero",
            description: "Create the hero section",
            content: null,
        },
        {
            title: "Chart",
            description: "Create the chart",
            content: null,
        },
        {
            title: "Features",
            description: "Add features",
            content: null,
        },
        {
            title: "Challenges",
            description: "Create challenges section",
            content: null,
        },
        {
            title: "Benefits",
            description: "create benefits section",
            content: null,
        },
        {
            title: "Contacts",
            description: "Create contacts section",
            content: null,
        },
        {
            title: "Footer",
            description: "Add footer information",
            content: null,
        },
    ];

    const handleStepChange = async (newStep: number) => {
        if (newStep > step) {
            const isValid = await validateCurrentStep();
            if (!isValid) return;
        }
        await saveCurrentStepData();
        setStep(newStep);
    };

    return {
        step,
        formData,
        steps,
        handleStepChange,
        handleSubmitAll,
        registerPageType,
        watchPageType,
        pageTypeErrors,
        isCompany,
        isCurrentStepValid,
        stepValidityHandlers,
        setValue,
        heroRef,
        chartRef,
        featuresRef,
        challengesRef,
        benefitsRef,
        contactsRef,
        footerRef,
    };
};

export default useMarketingForm;