import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import TaleButton from "@components/TaleButton";
import { lazily } from "react-lazily";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
import {Link, useLocation, useNavigate, useParams, useSearchParams} from "react-router-dom";
import { Button, Divider } from "@mui/material";
import { TaleDashbaordMainCard } from "@components/TaleDashbaordMainCard";
import { useQuery } from "@tanstack/react-query";
import { BsArrowLeft, BsCheckCircleFill } from "react-icons/bs";
import { useLayoutSidebarVisible } from "@/hooks/useLayoutSidebarVisible";
import { surveysService } from "@/api/surveys";
import { FF } from "@/utils/featureFlip";
import { formatSurveyApiToUi } from "@/utils/surveyFormatApiToUi";
import { formatQuestionUiToApi } from "@/utils/questionFormatApiToUi";
import {assetsService} from "@/api/assets";
import { useTranslation } from "@/hooks/useTranslation";

const { CreateSurveyStep1 } = lazily(() =>
    import("@pages/survey/new/scratch/Step1")
);
const { CreateSurveyStep2 } = lazily(() =>
    import("@pages/survey/new/scratch/Step2")
);
const { CreateSurveyStep3 } = lazily(() =>
    import("@pages/survey/new/scratch/Step3")
);
const { CreateSurveyStep4 } = lazily(() =>
    import("@pages/survey/new/scratch/Step4")
);
const { NotFound } = lazily(() => import("@components/Errors/NotFound"));
const { TaleAreYouSure } = lazily(() => import("@components/TaleAreYouSure"));
const { TaleModal } = lazily(() => import("@components/TaleModal"));

function CreateSurveyLayout({ isEditing = false, basePath = "/survey", listPath = "/surveys" }) {
    const { t } = useTranslation();
    useLayoutSidebarVisible(false);

    const location = useLocation();
    const params = useParams();
    const [searchParams] = useSearchParams();
    const isTaleScan = searchParams.get("source") === "talescan";

    const steps = useMemo(() => {
        const withSource = (url) => (isTaleScan ? `${url}?source=talescan` : url);

        const initStep = {
            title: t("surveyBuilder.stepper.initTitle"),
            slogan: "init",
            activeColor: "#00BDA9",
            completedColor: "#10b981",
            icon: "📝",
            description: t("surveyBuilder.stepper.initDescription"),
            url: withSource(`${basePath}/${params.surveyId}/edit/init`),
        };
        const questionsStep = {
            title: t("surveyBuilder.stepper.questionsTitle"),
            slogan: "questions",
            activeColor: "#00BDA9",
            completedColor: "#10b981",
            icon: "❓",
            description: t("surveyBuilder.stepper.questionsDescription"),
            url: withSource(`${basePath}/${params.surveyId}/edit/questions`),
        };
        const reviewStep = {
            title: t("surveyBuilder.stepper.reviewTitle"),
            slogan: "review",
            activeColor: "#00BDA9",
            completedColor: "#10b981",
            icon: "👁️",
            description: t("surveyBuilder.stepper.reviewDescription"),
            url: withSource(`${basePath}/${params.surveyId}/edit/review`),
        };
        const targetingSteps = FF.CREATE_SURVEY_USE_TARGETING
            ? [
                {
                    title: t("surveyBuilder.stepper.targetingTitle"),
                    slogan: "targeting",
                    activeColor: "#00BDA9",
                    completedColor: "#10b981",
                    icon: "🎯",
                    description: t("surveyBuilder.stepper.targetingDescription"),
                    url: withSource(`${basePath}/${params.surveyId}/edit/targeting`),
                },
            ]
            : [];
        const paymentSteps = FF.CREATE_SURVEY_USE_PAYMENT
            ? [
                {
                    title: t("surveyBuilder.stepper.paymentTitle"),
                    slogan: "payment",
                    activeColor: "#00BDA9",
                    completedColor: "#10b981",
                    icon: "💳",
                    description: t("surveyBuilder.stepper.paymentDescription"),
                    url: withSource(`${basePath}/${params.surveyId}/edit/payment`),
                },
            ]
            : [];

        // TaleScan lands on Question Development first; Survey Initiation moves to
        // right after Review (surveyId already exists by then) - it must not land
        // after Targeting/Payment, which stay the flow's actual last step(s).
        return isTaleScan
            ? [questionsStep, reviewStep, initStep, ...targetingSteps, ...paymentSteps]
            : [initStep, questionsStep, reviewStep, ...targetingSteps, ...paymentSteps];
    }, [params.surveyId, basePath, t, isTaleScan]);

    const currentStep = useMemo(
        () =>
            !params.stepName
                ? 0
                : steps.findIndex((step) => step.slogan === params.stepName),
        [params.stepName, steps]
    );

    const { isPending, data, error } = useQuery({
        queryKey: ["survey", params.surveyId],
        queryFn: async () =>
            !params.surveyId ? null : await surveysService.getSurvey(params.surveyId),
        retry: false,
    });

    const [survey, setSurvey] = useState({
        surveyId: params.surveyId,
        title: location.state?.title ?? "",
        logo: null,
        description: location.state?.description ?? "",
        category: location.state?.category ?? "",
        is_from_template: !!location.state?.title,
        startDate: new Date().toISOString(),
        endDate: null,
        createdBy: null,
        createdDate: new Date().toISOString(),
        status: null,
        surveyRequirements: null,
        surveyInsights: null,
        participants: [],
        campaign: null,
        company: null,
        ourDatabases: null,
        questions: location.state?.initialQuestions ?? [],
        analytics: null,
        products: [],
        language: location.state?.language ?? null,
        coverPhoto: null,
        copyQuestions: false,
        useAudiencePanel: false,
        distribution_metadata: {
            method: undefined,
            link_name: "",
            targetingOptions: {
                responses: 50,
                criterias: {},
            },
        },
        loading: false,
    });

    useEffect(() => {
        if (!data) return;
        const formatted = formatSurveyApiToUi(data, survey);
        //setSurvey(formatted);
        setSurvey((prev) => ({
            ...formatted,
            distribution_metadata: {
                ...formatted.distribution_metadata,
                link_name: data.slug ?? prev.distribution_metadata.link_name,
            },
        }));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    const isQuestionGood = useCallback((q) => {
        const errorMessagesToReturn = [
            {
                condition: !q.question_text,
                message: t("surveyBuilder.stepper.errors.missingLabelText"),
            },
            {
                condition: ![
                    "1-10",
                    "smile",
                    "star",
                    "comment",
                    "checkbox",
                    "radio",
                ].includes(q.format),
                message: t("surveyBuilder.stepper.errors.missingFormat"),
            },
            {
                condition:
                    ["checkbox", "radio"].includes(q.format) &&
                    !q.possible_responses?.length,
                message: t("surveyBuilder.stepper.errors.missingOptions", { format: q.format }),
            },
            {
                condition:
                    q.responseType === "IMAGE" &&
                    !q.assets.find((asset) => asset.description === "QUESTION_IMAGE"),
                message: t("surveyBuilder.stepper.errors.missingImage"),
            },
            {
                condition:
                    q.responseType === "SOUND" &&
                    !q.assets.find((asset) => asset.description === "QUESTION_SOUND"),
                message: t("surveyBuilder.stepper.errors.missingSound"),
            },
            {
                condition:
                    q.responseType === "VIDEO" &&
                    q.video_source === "url" &&
                    !q.youtube_video,
                message: t("surveyBuilder.stepper.errors.missingVideoUrl"),
            },
            {
                condition:
                    q.responseType === "VIDEO" &&
                    q.video_source === "upload" &&
                    !q.assets.find((asset) => asset.description === "QUESTION_VIDEO"),
                message: t("surveyBuilder.stepper.errors.missingVideoUpload"),
            },
        ];
        const response = !!errorMessagesToReturn.every(
            (message) => !message.condition
        );
        return {
            return: response,
            errorMessages: errorMessagesToReturn.filter(
                (message) => message.condition
            ),
        };
    }, [t]);

    const draftQuestions = useMemo(() => {
        if (steps[currentStep]?.slogan !== "questions") return [];
        return survey.questions
            .map((q) => ({ question: q, response: isQuestionGood(q) }))
            .filter((data) => !data.response.return)
            .reduce(
                (t, n) =>
                    (t = {
                        ...t,
                        [n.question.id]: { messages: n.response.errorMessages },
                    }),
                {}
            );
    }, [currentStep, isQuestionGood, survey.questions, steps]);

    const nextButtonConditions = useMemo(
        () => ({
            init: survey.title && survey.category && survey.language,
            questions: survey.questions.length > 0 && !Object.keys(draftQuestions).length,
            review: true,
            targeting:
                (["embedding", "socialMedia", "sharing"].includes(
                        survey.distribution_metadata.method
                    ) &&
                    !!survey.distribution_metadata.link_name) ||
                survey.distribution_metadata.method === "targeting",
            payment: true,
        }),
        [survey, draftQuestions]
    );

    const isNextButtonEnabled = useMemo(() => {
        return nextButtonConditions[steps[currentStep]?.slogan];
    }, [currentStep, nextButtonConditions, steps]);

    const navigate = useNavigate();

    const [showCancelConfirm, setShowCancelConfirm] = useState(false);

    const hasUnsavedData = useMemo(
        () =>
            !!survey.title ||
            !!survey.description ||
            !!survey.category ||
            survey.questions.length > 0,
        [survey.title, survey.description, survey.category, survey.questions]
    );

    // Tracks "this exact session created the survey, and it's not finished
    // yet" — independent of isEditing, which becomes true for every step
    // after the first once we navigate to /survey/:id/edit/:step, even mid
    // fresh creation (that route is shared with genuinely re-opening an
    // already-finished survey). Set to true right when creatingSurvey
    // succeeds in handleNext below.
    const createdInThisSessionRef = useRef(false);

    // A survey created by handleNext's creatingSurvey branch but never finished:
    // cancelling out must not leave it orphaned in the backend. Editing an
    // existing (already-finished) survey must never trigger this.
    const deleteAbandonedSurvey = useCallback(async () => {
        if (!survey.surveyId || !createdInThisSessionRef.current) return;
        try {
            await surveysService.deleteSurvey(survey.surveyId);
        } catch (error) {
            console.error(error);
        }
    }, [survey.surveyId]);

    const handleCancel = useCallback(async () => {
        if (hasUnsavedData) {
            setShowCancelConfirm(true);
            return;
        }
        await deleteAbandonedSurvey();
        navigate(listPath);
    }, [hasUnsavedData, deleteAbandonedSurvey, navigate, listPath]);

    const handleNext = useCallback(async () => {
        let surveyId = params.surveyId;
        console.log(`survey id from CreateSurveyLayout : ${surveyId}`);
        const creatingSurvey = !isEditing && currentStep === 0 && !survey.surveyId;
        const updatingSurveyInit = isEditing && steps[currentStep]?.slogan === "init";
        const isLastStep = currentStep === steps.length - 1;

        const savingSlug = steps[currentStep]?.slogan === "targeting" && ["sharing", "embedding", "socialMedia"].includes(survey.distribution_metadata.method) && survey.distribution_metadata.link_name !== data?.slug;

        const isPublicChoice = ["sharing", "embedding", "socialMedia"].includes(survey.distribution_metadata.method) && !!survey.distribution_metadata.link_name;

        setSurvey((prev) => ({
            ...prev,
            loading: true,
        }));
        try {
            if (creatingSurvey) {
                const storedUser = JSON.parse(localStorage.getItem('user'));
                const isAdmin = storedUser?.userType === "ADMIN" || (storedUser?.roles || []).includes("ADMIN");
                const companyId = storedUser?.companyId || survey.company?.id;

                if (!companyId && !isAdmin) {
                    throw new Error(t("surveyBuilder.stepper.errors.companyRequired"));
                }
                const newSurvey = await surveysService.createSurvey({
                    title: survey.title,
                    description: survey.description,
                    language: survey.language,
                    category: survey.category,
                    companyId: companyId ?? null,
                    productIds: survey.products || [],
                    logo: survey.logo,
                    rewardPoints: survey.rewardPoints,
                });

                surveyId = newSurvey.id;
                if (survey.coverPhoto?.[0] instanceof File) {
                    const newBanner = await assetsService.uploadAsset({
                        file: survey.coverPhoto[0],
                        contentType: "IMAGE",
                        entityType: "SURVEY",
                        entityId: surveyId,
                        description: "SURVEY_BANNER",
                    });
                    setSurvey((prev) => ({ ...prev, banner: newBanner }));
                }
                if (survey.questions.length > 0) {
                    const batchPayload = survey.questions.map((q, index) => {
                        const apiQuestion = formatQuestionUiToApi({ ...q });
                        delete apiQuestion.id; // server assigns ids on create; our UUID isn't a valid Long
                        apiQuestion.mandatory = q.mandatory ?? false;
                        apiQuestion.questionOrder = index + 1;
                        return apiQuestion;
                    });
                    await surveysService.addBatchQuestionsToSurvey(surveyId, batchPayload);
                }
                const formatted = formatSurveyApiToUi(newSurvey, {
                    ...survey,
                    surveyId: newSurvey.id,
                    company: companyId
                        ? {
                            id: companyId,
                            companyName: storedUser?.companyName || survey.company?.companyName,
                        }
                        : null,
                });
                // formatSurveyApiToUi rebuilds `questions` from newSurvey's API
                // response, which has none yet (batch call above is separate) —
                // keep the pre-filled local ones instead of losing them.
                if (survey.questions.length > 0) {
                    formatted.questions = survey.questions;
                }
                createdInThisSessionRef.current = true;
                setSurvey(formatted);
            } else if (updatingSurveyInit) {
                const storedUser = JSON.parse(localStorage.getItem('user'));
                const isAdmin = storedUser?.userType === "ADMIN" || (storedUser?.roles || []).includes("ADMIN");
                const companyId = storedUser?.companyId || survey.company?.id;

                if ((!companyId && !isAdmin) ) {
                    throw new Error(t("surveyBuilder.stepper.errors.companyRequiredUpdate"));
                }

                await surveysService.updateSurvey({
                    id: params.surveyId,
                    title: survey.title,
                    description: survey.description || "",
                    language: survey.language,
                    category: survey.category,
                    productIds: survey.products,
                    companyId: companyId ?? null,
                    rewardPoints: survey.rewardPoints,
                });
            } else if (savingSlug) {
                await surveysService.updateSurvey({
                    id: surveyId,
                    slug: survey.distribution_metadata.link_name,
                    privacy: "Public",
                });
            } else if (steps[currentStep]?.slogan === "targeting" && !isPublicChoice) {
                await surveysService.updateSurvey({
                    id: surveyId,
                    privacy: "Private",
                });
            }
        } catch (error) {
            console.log(error.response?.data);
            alert(`${t("surveyBuilder.stepper.errorPrefix")} ${error.response?.data?.message || error.message}`);
            return;
        } finally {
            setSurvey((prev) => ({
                ...prev,
                loading: false,
            }));
        }
        if (isLastStep) {
            navigate(listPath);
            return;
        }
        if (!surveyId) {
            console.error("Survey ID is undefined, cannot navigate to next step");
            return;
        }
        const nextStep = steps.at(currentStep + 1);
        // steps[].url was built from params.surveyId, which is still undefined right after
        // creatingSurvey (we haven't navigated off /new/scratch yet) - use the freshly
        // created id in that one case instead of the (stale) precomputed url.
        const nextUrl = creatingSurvey
            ? `${basePath}/${surveyId}/edit/${nextStep.slogan}${isTaleScan ? "?source=talescan" : ""}`
            : nextStep.url;
        navigate(nextUrl);
    }, [params.surveyId, isEditing, currentStep, survey, steps, navigate, basePath, listPath, t, isTaleScan]);

    const handleUpdate = useCallback(async () => {
        const savingSlug = steps[currentStep]?.slogan === "targeting" && ["sharing", "embedding", "socialMedia"].includes(survey.distribution_metadata.method) && survey.distribution_metadata.link_name !== data?.slug;

        const isPublicChoice = ["sharing", "embedding", "socialMedia"].includes(survey.distribution_metadata.method) && !!survey.distribution_metadata.link_name;

        setSurvey((prev) => ({ ...prev, loading: true }));
        try {
            if (steps[currentStep]?.slogan === "init") {
                const storedUser = JSON.parse(localStorage.getItem('user'));
                const isAdmin = storedUser?.userType === "ADMIN" || (storedUser?.roles || []).includes("ADMIN");
                const companyId = storedUser?.companyId || survey.company?.id;
                if (!companyId && !isAdmin) throw new Error(t("surveyBuilder.stepper.errors.companyRequiredUpdate"));
                await surveysService.updateSurvey({
                    id: params.surveyId,
                    title: survey.title,
                    description: survey.description || "",
                    language: survey.language,
                    category: survey.category,
                    productIds: survey.products,
                    companyId: companyId ?? null,
                    rewardPoints: survey.rewardPoints,
                });
            } else if (savingSlug) {
                await surveysService.updateSurvey({
                    id: params.surveyId,
                    slug: survey.distribution_metadata.link_name,
                    privacy: "Public",
                });
            } else if (steps[currentStep]?.slogan === "targeting" && !isPublicChoice) {
                await surveysService.updateSurvey({
                    id: params.surveyId,
                    privacy: "Private",
                });
            }
        } catch (error) {
            alert(`${t("surveyBuilder.stepper.errorPrefix")} ${error.response?.data?.message || error.message}`);
            return;
        } finally {
            setSurvey((prev) => ({ ...prev, loading: false }));
        }
        navigate(listPath);
    }, [currentStep, survey, params.surveyId, data?.slug, navigate, listPath, t, steps]);

    const stepsMapper = useMemo(
        () => ({
            init: (
                <CreateSurveyStep1
                    key="init"
                    is_from_template={survey.is_from_template}
                    language={survey.language}
                    setLanguage={(v) => setSurvey((prev) => ({ ...prev, language: v }))}
                    coverPhoto={survey.coverPhoto}
                    setCoverPhoto={(v) => setSurvey((prev) => ({ ...prev, coverPhoto: v }))}
                    copyQuestions={survey.copyQuestions}
                    setCopyQuestions={(v) =>
                        setSurvey((prev) => ({ ...prev, copyQuestions: v }))
                    }
                    survey={survey}
                    setSurvey={setSurvey}
                    useAudiencePanel={survey.useAudiencePanel}
                    setUseAudiencePanel={(v) =>
                        setSurvey((prev) => ({ ...prev, useAudiencePanel: v }))
                    }
                />
            ),
            questions: (
                <CreateSurveyStep2
                    key="questions"
                    questions={survey.questions}
                    setQuestions={(v) => setSurvey((prv) => ({ ...prv, questions: v }))}
                    importQuestions={survey.copyQuestions}
                    draftQuestions={draftQuestions}
                    surveyId={survey.surveyId}
                    surveyLanguage={survey.language}
                    surveyTitle={survey.title}
                    surveyCategory={survey.category}
                    enableAiAssistant={isTaleScan}
                />
            ),
            review: (
                <CreateSurveyStep3
                    key="review"
                    questions={survey.questions}
                    surveyLanguage={survey.language}
                />
            ),
            targeting: (
                <CreateSurveyStep4
                    key="targeting"
                    company={data?.company}
                    distributionMethod={survey.distribution_metadata.method}
                    setDistributionMethod={(v) =>
                        setSurvey((p) => ({
                            ...p,
                            distribution_metadata: { ...p.distribution_metadata, method: v },
                        }))
                    }
                    targetingCriterias={
                        survey.distribution_metadata.targetingOptions.criterias
                    }
                    setTargetingCriterias={(v) =>
                        setSurvey((p) => ({
                            ...p,
                            distribution_metadata: {
                                ...p.distribution_metadata,
                                targetingOptions: {
                                    ...p.distribution_metadata.targetingOptions,
                                    criterias: v,
                                },
                            },
                        }))
                    }
                    targetedResponses={
                        survey.distribution_metadata.targetingOptions.responses
                    }
                    setTargetedResponses={(v) =>
                        setSurvey((p) => ({
                            ...p,
                            distribution_metadata: {
                                ...p.distribution_metadata,
                                targetingOptions: {
                                    ...p.distribution_metadata.targetingOptions,
                                    responses: v,
                                },
                            },
                        }))
                    }
                    questionsCount={survey.questions.length}
                    linkName={survey.distribution_metadata.link_name}
                    setLinkName={(v) =>
                        setSurvey((p) => ({
                            ...p,
                            distribution_metadata: {
                                ...p.distribution_metadata,
                                link_name: v,
                            },
                        }))
                    }
                    slug={data?.slug}
                    surveyTitle={survey.title}
                    surveyBannerUrl={
                        survey.banner?.url ??
                        data?.assets?.find((a) => a.description === "SURVEY_BANNER")?.url
                    }
                />
            ),
            payment: (
                <div key="payment" className="flex flex-col items-center justify-center py-20 gap-4">
                    <h2 className="text-2xl font-bold">{t("surveyBuilder.stepper.paymentTitle")}</h2>
                    <p className="text-gray-600">{t("surveyBuilder.stepper.paymentPanelSubtitle")}</p>
                    <div className="bg-gray-100 p-6 rounded-lg">
                        <p><strong>{t("surveyBuilder.stepper.surveyLabel")}</strong> {survey.title}</p>
                        <p><strong>{t("surveyBuilder.stepper.questionsLabel")}</strong> {survey.questions.length}</p>
                        <p><strong>{t("surveyBuilder.stepper.distributionLabel")}</strong> {survey.distribution_metadata.method || t("surveyBuilder.stepper.notSelected")}</p>
                    </div>
                </div>
            ),
        }),
        [draftQuestions, survey, t, data?.company, isTaleScan]
    );

    const lowerPart = useMemo(
        () => (
            <div className="justify-between flex items-center w-full">
                <div className="flex items-center gap-3">
                    {currentStep ? (
                        <Button
                            variant="outlined"
                            onClick={() => {
                                navigate(steps.at(currentStep - 1).url);
                                if (survey.distribution_metadata.method)
                                    setSurvey((prev) => ({
                                        ...prev,
                                        distribution_metadata: {
                                            ...prev.distribution_metadata,
                                            method: undefined,
                                        },
                                    }));
                            }}
                            className="!font-semibold !border-2 !border-[#111] !text-[#111] !h-[51px] !w-[147px] !rounded-lg !normal-case hover:!bg-gray-50 transition-colors"
                        >
                            {t("actions.previous")}
                        </Button>
                    ) : null}
                    <Button
                        variant="outlined"
                        onClick={handleCancel}
                        className="!font-semibold !border-2 !border-red-500 !text-red-500 !h-[51px] !w-[147px] !rounded-lg !normal-case hover:!bg-red-50 hover:!border-red-600 transition-colors"
                    >
                        {t("surveyBuilder.stepper.cancel")}
                    </Button>
                </div>
                <div className="flex items-center gap-3">
                    {isEditing && currentStep !== steps.length - 1 && survey.distribution_metadata.method !== "targeting" && (
                        <TaleButton
                            loading={survey.loading}
                            role="normal"
                            variant="outlined"
                            onClick={handleUpdate}
                            disabled={!isNextButtonEnabled}
                            className={`!font-semibold !w-[147px] transition-all ${
                                !isNextButtonEnabled
                                    ? "!text-[#666] !bg-gray-100 !cursor-not-allowed"
                                    : "hover:scale-[1.02]"
                            }`}
                        >
                            {t("surveyBuilder.stepper.update")}
                        </TaleButton>
                    )}
                    {steps[currentStep]?.slogan === "targeting" &&
                    survey.distribution_metadata.method === "targeting" ? null : (
                        <TaleButton
                            loading={survey.loading}
                            role="normal"
                            onClick={handleNext}
                            disabled={!isNextButtonEnabled}
                            className={`!font-semibold !w-[147px] transition-all ${
                                !isNextButtonEnabled
                                    ? "!text-[#666] !bg-gray-100 !cursor-not-allowed"
                                    : "hover:scale-[1.02]"
                            }`}
                        >
                            {currentStep === steps.length - 1 ? (
                                <span className="flex items-center gap-2">
                                <BsCheckCircleFill /> {t("surveyBuilder.stepper.confirm")}
                            </span>
                            ) : (
                                t("actions.next")
                            )}
                        </TaleButton>
                    )}
                </div>
            </div>
        ),
        [
            currentStep,
            handleCancel,
            handleNext,
            handleUpdate,
            isEditing,
            isNextButtonEnabled,
            navigate,
            steps,
            survey.distribution_metadata.method,
            survey.loading,
            t,
        ]
    );

    if (params.surveyId && isPending)
        return <TaleLoadingFallback className="h-[60vh]" />;

    if (params.surveyId && currentStep === -1) {
        return navigate(listPath, { replace: true });
    }

    // Enhanced Stepper with Progress Bar integrated in steps
    const EnhancedStepper = ({ steps, currentStep }) => {
        // const progressPercentage = ((currentStep + 1) / steps.length) * 100;

        return (
            <div className="w-full">
                {/* Steps container */}
                <div className="relative flex justify-center items-start z-20 gap-8 md:gap-32">
                    {steps.map((step, index) => {
                        const isActive = index === currentStep;
                        const isCompleted = index < currentStep;
                        // const isUpcoming = index > currentStep;

                        return (
                            <div
                                key={index}
                                className="flex flex-col items-center relative"
                            >
                                {/* Step connector - left side */}
                                {index > 0 && (
                                    <div className="absolute top-7 -left-1/2 w-full h-0.5 z-0">
                                        <div
                                            className={`h-full ${(isCompleted || isActive) ? 'bg-gradient-to-r from-[#00BDA9] to-[#00C0FC]' : 'bg-gradient-to-r from-[#00BDA913] to-[#00C0FC13]'}`}
                                        />
                                    </div>
                                )}

                                {/* Step connector - right side */}
                                {index < steps.length - 1 && (
                                    <div className="absolute top-7 -right-1/2 w-full h-0.5 z-0">
                                        <div
                                            className={`h-full ${isCompleted || isActive ? 'bg-gradient-to-r from-[#00C0FC] to-[#00BDA9]' : 'bg-gradient-to-r from-[#00C0FC13] to-[#00BDA913]'}`}
                                        />
                                    </div>
                                )}

                                {/* Step circle */}
                                <div className="relative mb-3">
                                    <div
                                        className={`w-14 h-14 rounded-full  flex items-center justify-center transition-all duration-300 ${
                                            isCompleted
                                                ? 'bg-gradient-to-br from-[#00C0FC] to-[#00BDA9] border-transparent'
                                                : isActive
                                                    ? 'bg-gradient-to-br from-[#00C0FC] to-[#00BDA9] border-transparent shadow-lg shadow-[#00BDA9]/20'
                                                    : 'bg-gradient-to-br from-[#00C0FC13] to-[#00BDA913] border-gray-200'
                                        }`}
                                    >
                                        {/* Inner content */}
                                        <div className="relative z-10">
                                            {isCompleted ? (
                                                <div className="bg-white rounded-full p-1">
 <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#00C0FC] to-[#00BDA9] font-bold">
                                                        ✔️
                                                    </span>                                                </div>
                                            ) : isActive ? (
                                                <div className="bg-white rounded-full w-6 h-6 flex items-center justify-center">
                                                    <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#00C0FC] to-[#00BDA9] font-bold">
                                                        {index + 1}
                                                    </span>
                                                </div>
                                            ) : (
                                                <div className="bg-gray-50 rounded-full w-6 h-6 flex items-center justify-center">
                                                    <span className="text-gray-600 font-semibold">
                                                        {index + 1}
                                                    </span>
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    {/* Step status indicator */}
                                    <div className={`absolute -bottom-2 left-1/2 -translate-x-1/2 whitespace-nowrap px-2 py-1 rounded-full text-xs font-medium ${
                                        isActive
                                            ? 'bg-gradient-to-r from-[#00C0FC] to-[#00BDA9] text-white'
                                            : isCompleted
                                                ? 'bg-gradient-to-r from-[#00C0FC] to-[#00BDA9] text-white'
                                                : 'bg-gradient-to-r from-[#00C0FC13] to-[#00BDA913] text-gray-500'
                                    }`}>
                                        {isActive ? t("surveyBuilder.stepper.current") : isCompleted ? t("surveyBuilder.stepper.completed") : t("surveyBuilder.stepper.upcoming")}
                                    </div>
                                </div>

                                {/* Step info */}
                                <div className="mt-8 text-center max-w-[160px]">
                                    <div className={`font-semibold mb-1 ${
                                        isActive ? 'text-gray-900' :
                                            isCompleted ? 'text-transparent bg-clip-text bg-gradient-to-r from-[#00C0FC] to-[#00BDA9]' :
                                                'text-gray-500'
                                    }`}>
                                        {step.title}
                                    </div>
                                    <div className="text-xs text-gray-500">
                                        {step.description}
                                    </div>


                                </div>

                                {/* Clickable area */}
                                {isCompleted && (
                                    <button
                                        onClick={() => navigate(step.url)}
                                        className="absolute inset-0 w-full h-full cursor-pointer"
                                        aria-label={t("surveyBuilder.stepper.goToStep", { title: step.title })}
                                    />
                                )}
                            </div>
                        );
                    })}
                </div>

                {/* Progress indicator below */}

            </div>
        );
    };

    return (
        <div className="flex flex-col gap-6">
            <Suspense fallback={null}>
                {showCancelConfirm ? (
                    <TaleModal className="flex items-center justify-center">
                        <TaleAreYouSure
                            onCancel={() => setShowCancelConfirm(false)}
                            onConfirm={async () => {
                                setShowCancelConfirm(false);
                                await deleteAbandonedSurvey();
                                navigate(listPath);
                            }}
                            text={t("surveyBuilder.stepper.cancelConfirmMessage")}
                            title={t("surveyBuilder.stepper.cancelConfirmTitle")}
                        />
                    </TaleModal>
                ) : null}
            </Suspense>
            <TaleDashbaordMainCard
                className={`survey-section flex flex-col gap-10 p-8 bg-white rounded-2xl shadow-sm ${
                    steps[currentStep]?.slogan === "review" && !error
                        ? "!min-h-0"
                        : error
                            ? "justify-center"
                            : ""
                }`}
            >
                {error ? (
                    <Suspense fallback={<TaleLoadingFallback className="h-[60vh]" />}>
                        <NotFound />
                    </Suspense>
                ) : (
                    <>
                        <div className="flex flex-col gap-4">
                            <div className="flex items-center gap-3">
                                <Link
                                    to={listPath}
                                    className="cursor-pointer p-2 rounded-lg hover:bg-gray-100 transition-colors"
                                    aria-label={t("surveyBuilder.stepper.returnToSurveysList")}
                                    title={t("surveyBuilder.stepper.returnToSurveysList")}
                                >
                                    <BsArrowLeft className="w-5 h-5" />
                                </Link>
                                <div>
                                    <h1 className="text-2xl font-bold text-gray-900">
                                        {survey.title || t("surveyBuilder.stepper.creatingNewSurvey")}
                                    </h1>
                                    <p className="text-gray-600 mt-1">
                                        {isEditing ? t("surveyBuilder.stepper.editYourSurvey") : t("surveyBuilder.stepper.createAndConfigure")}
                                    </p>
                                </div>
                            </div>
                        </div>

                        {/* Enhanced Stepper with gradient colors */}
                        <EnhancedStepper steps={steps} currentStep={currentStep} />

                        {steps[currentStep]?.slogan === "review" ? null : (
                            <>
                                <Suspense
                                    fallback={<TaleLoadingFallback className="h-[60vh]" />}
                                >
                                    {stepsMapper[steps[currentStep]?.slogan]}
                                </Suspense>
                                <div className="flex gap-6 flex-col grow justify-end mt-12">
                                    {steps[currentStep]?.slogan === "questions" && <Divider />}
                                    {lowerPart}
                                </div>
                            </>
                        )}
                    </>
                )}
            </TaleDashbaordMainCard>
            {error ? null : steps[currentStep]?.slogan === "review" ? (
                <>
                    <Suspense fallback={<TaleLoadingFallback className="h-[60vh]" />}>
                        {stepsMapper[steps[currentStep]?.slogan]}
                    </Suspense>
                    <div className={`p-6 bg-white rounded-2xl shadow-sm mt-4`}>
                        {lowerPart}
                    </div>
                </>
            ) : null}
        </div>
    );
}
export default CreateSurveyLayout;