import TaleButton from "@components/TaleButton";
import { Button } from "@mui/material";
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { SingleQuestion } from "@pages/survey/surveyId/questions/SingleQuestion";
import { TaleDashbaordMainCard } from "@components/TaleDashbaordMainCard";
import { useNavigate, useParams } from "react-router-dom";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
import { lazily } from "react-lazily";
import { useQuery } from "@tanstack/react-query";
import { useSelector } from "react-redux";
import { ErrorBoundary } from "react-error-boundary";
import {
  FiCheckCircle,
  FiClock,
  FiStar,
  FiChevronRight,
  FiChevronLeft,
  FiUserCheck, FiAlertCircle
} from "react-icons/fi";
import { surveysService } from "@/api/surveys";
import { newMetaEventId, trackSurveyAnswered } from "@/utils/metaPixel";
import { formatQuestionApiToUi } from "@/utils/questionFormatApiToUi";
import { isJSON } from "@/utils/isJSON";
import { ErrorWrapper } from "@/components/ErrorWrapper";
import { useTranslation } from "@/hooks/useTranslation";

// Import React Icons
// import {BsStarFill,} from "react-icons/bs";

const { NotFound } = lazily(() => import("@components/Errors/NotFound"));

const SurveyQuestions = () => {
  const { t } = useTranslation();
  const nav = useNavigate();
  const { surveyId } = useParams();
  const user = useSelector((state) => state.auth.user);

  const [answerState, setAnswerState] = useState({});
  const [currentStep, setCurrentStep] = useState(0); // Start from 0 by default
  const [formattedQuestion, setFormattedQuestion] = useState({});
  const [originalQuestionAnswerMapping, setOriginalQuestionAnswerMapping] = useState({});
  //const [existingQuestionAnswerMapping, setExistingQuestionAnswerMapping] = useState({});
  const [showProgressAnimation, setShowProgressAnimation] = useState(false);

  // Determine role from Redux user
  const isCompany = useMemo(() => {
    const userType = user?.userType || user?.roles?.[0];
    return userType === "COMPANY_USER";
  }, [user]);

  const isUser = useMemo(() => {
    const userType = user?.userType || user?.roles?.[0];
    return userType === "NORMAL_USER";
  }, [user]);

  const {
    isPending: loading,
    data,
    error,
  } = useQuery({
    queryKey: ["survey-questions", surveyId, "user", user?.userId || user?.id],
    queryFn: async () => {
      if (!user?.userId && !user?.id)
        return {
          company: {},
          questions: [{}],
        };

      const [
        { questions: rawQuestions, company, assets, ...survey },
        userResponsesInSurvey,
      ] = await Promise.all([
        surveysService.getSurvey(surveyId),
        isUser
            ? surveysService.getUserResponsesToSurveyQuestions({ surveyId })
            : []
      ]);

      const questions = rawQuestions.filter(
          (q) => q.text && q.questionType
      );

      setOriginalQuestionAnswerMapping(
          surveysService.mappers.createSurveyRedirectionsFromQuestions(questions)
      );

      const quickAccessMap =
          surveysService.mappers.createSurveyQuestionsResponseAndConditionsMap(
              userResponsesInSurvey
          );
      //setExistingQuestionAnswerMapping(quickAccessMap);

      const serverAnsweredQuestionIds = userResponsesInSurvey
          .filter((r) => {
            const answer = r.answer;
            if (answer === null || answer === undefined) return false;
            const trimmed = String(answer).trim();
            return trimmed !== "" && trimmed !== "null" && trimmed !== "[]";
          })
          .map((r) => r.questionId);

      // Set answer state from existing responses
      setAnswerState(
          questions.reduce(
              (t, n) =>
                  (t = {
                    ...t,
                    [n.id]: {
                      values: {
                        radio: quickAccessMap[n.id]?.currentAnswer?.index ?? null,
                        checkbox: isJSON(quickAccessMap[n.id]?.currentAnswer?.value)
                            ? JSON.parse(quickAccessMap[n.id].currentAnswer.value)
                            : [],
                        star: quickAccessMap[n.id]?.currentAnswer?.index ?? null,
                        smile: quickAccessMap[n.id]?.currentAnswer?.index ?? null,
                        comment: quickAccessMap[n.id]?.currentAnswer?.value ?? null,
                        "1-10": quickAccessMap[n.id]?.currentAnswer?.index ?? null,
                      },
                    },
                  }),
              {}
          )
      );

      // Determine current step based on responses
      let targetQuestionIndex = 0;

      if (isUser && userResponsesInSurvey?.length > 0) {
        // Find the last answered question
        const lastAnsweredQuestionId = userResponsesInSurvey[userResponsesInSurvey.length - 1]?.questionId;

        // Check if survey is already completed
        const isCompleted = survey.status === "COMPLETED"

        if (isCompleted) {
          // User has completed the survey
          throw new Error(
              JSON.stringify({
                company: company,
                survey: survey,
                message: "USER_COMPLETED_SURVEY",
                already: true,
              })
          );
        }

        // Find next unanswered question after the last answered one
        const lastAnsweredIndex = questions.findIndex(q => q.id === lastAnsweredQuestionId);
        targetQuestionIndex = lastAnsweredIndex !== -1 ? lastAnsweredIndex + 1 : 0;

        // If we've answered all questions but survey isn't marked completed
        if (targetQuestionIndex >= questions.length) {
          targetQuestionIndex = questions.length - 1; // Go to last question
        }
      }

      // Check if survey status prevents participation
      if (["DRAFT", "COMPLETED"].includes(survey?.status) && isUser) {
        throw new Error(
            JSON.stringify({
              company: company,
              survey: survey,
              message: "BAD_SURVEY_STATUS",
            })
        );
      }

      setCurrentStep(targetQuestionIndex);
      setFormattedQuestion(
          formatQuestionApiToUi(questions[targetQuestionIndex] || questions[0] || {})
      );

      return {
        company,
        questions,
        userResponsesInSurvey,
        survey,
        assets,
        serverAnsweredQuestionIds,
      };
    },
    retry: false,
  });

  const isSurveyEmpty = useMemo(() => {
    // If any question was validly answered on the server, survey is not empty
    if (data?.serverAnsweredQuestionIds?.length > 0) return false;

    if (!answerState || Object.keys(answerState).length === 0) return false;

    return !Object.entries(answerState).some(([questionId, q]) => {
      const values = q.values || {};

      return Object.values(values).some((v) => {
        if (Array.isArray(v)) return v.length > 0;

        if (v === null || v === undefined) return false;

        if (typeof v === "number") return !isNaN(v);

        if (typeof v === "string") {
          const trimmed = v.trim();
          if (trimmed === "" || trimmed === "null" || trimmed === "[]") return false;
          return true;
        }

        return true;
      });
    });
  }, [answerState, data?.serverAnsweredQuestionIds]);

  const steps = useMemo(
      () => (loading || !data ? 0 : data.questions.length),
      [data, loading]
  );

  useEffect(() => {
    if (currentStep === null || !data?.questions) return;

    const question = data.questions[currentStep];
    if (question) {
      setFormattedQuestion(formatQuestionApiToUi(question));
      setShowProgressAnimation(true);
      const timer = setTimeout(() => setShowProgressAnimation(false), 500);
      return () => clearTimeout(timer);
    }
  }, [currentStep, data]);

  const emptySurvey = useMemo(
      () => !loading && data?.questions && !data.questions.length,
      [data, loading]
  );

  useEffect(() => {
    if (!emptySurvey) return;
    if (isCompany) nav(`/survey/${surveyId}/edit/questions`);
    else if (isUser) nav(`/surveys`);
  }, [emptySurvey, isCompany, isUser, nav, surveyId]);

  const handleNext = useCallback(async () => {
    const isLast = currentStep === steps - 1;
    const question_response_holder = formattedQuestion.format;
    const currentResponse =
        answerState[formattedQuestion.id]?.values[question_response_holder];

    const nextQuestionId =
        originalQuestionAnswerMapping[formattedQuestion.id]?.[
            formattedQuestion.possible_responses[currentResponse]
            ] ??
        (isLast ? null : data.questions[currentStep + 1].id);

    const nextQuestionIndex = data.questions.findIndex(
        (q) => q.id === nextQuestionId
    );

    const isAlreadyAnsweredOnServer = data.serverAnsweredQuestionIds?.includes(formattedQuestion.id);

    if (isUser && !isAlreadyAnsweredOnServer) {
      const questionResponseObject = {
        otherAnswer: !!formattedQuestion.other_value,
        answer:
            formattedQuestion.other_value ||
            (formattedQuestion.format === "comment"
                ? answerState[formattedQuestion.id]?.values[question_response_holder]
                : JSON.stringify(
                    answerState[formattedQuestion.id]?.values[question_response_holder]
                )),
      };

      await surveysService.respondToQuestion({
        surveyId: parseInt(surveyId),
        questionId: formattedQuestion.id,
        userId: user?.userId || user?.id,
        response: questionResponseObject,
      });
    }

    // Always update checkpoint when isUser, but only mark complete (isLast) regardless of whether question was already answered
    if (isUser) {
      // One id for both reports of this lead: the browser pixel's below, and the server's, which
      // reports it through the Conversions API when it marks the response complete.
      const metaEventId = isLast ? newMetaEventId() : undefined;
      await surveysService.updateUserQuestionCheckpoint(
          user?.userId || user?.id,
          surveyId,
          null,
          formattedQuestion.id,
          isLast,
          metaEventId
      );
      // Reached only once the server has marked the response complete - a failure above throws past
      // this. Respondents only: company staff and admins walking through a survey are not leads.
      if (isLast) {
        trackSurveyAnswered(data.company, data.survey, metaEventId);
      }
    }

    if (isLast) {
      nav(`/survey/${surveyId}/completed`);
      return;
    }

    if (nextQuestionIndex !== undefined && nextQuestionIndex !== -1) {
      setCurrentStep(nextQuestionIndex);
    } else {
      setCurrentStep((prev) => prev + 1);
    }
  }, [
    currentStep,
    steps,
    formattedQuestion,
    answerState,
    originalQuestionAnswerMapping,
    data,
    isUser,
    surveyId,
    user,
    nav,
  ]);

  const handlePrevious = useCallback(async () => {
    const isFirst = currentStep === 0;
    if (isFirst) return;

    const previousQuestionIndex = currentStep - 1;

    if (isUser && previousQuestionIndex >= 0) {
      await surveysService.updateUserQuestionCheckpoint(
          user?.userId || user?.id,
          surveyId,
          null,
          data.questions[previousQuestionIndex].id,
          false
      );
    }

    setCurrentStep(previousQuestionIndex);
  }, [currentStep, data, isUser, surveyId, user]);

  const isQuestionGood = useMemo(() => {
    if (loading || !data || error || !formattedQuestion || emptySurvey || currentStep === null) {
      return false;
    }

    const currentValues = answerState[formattedQuestion.id]?.values;
    if (!currentValues) return false;

    const format = formattedQuestion.format;
    const value = currentValues[format];

    switch (format) {
      case 'radio':
      case 'checkbox':
        if (value === "other") {
          return !!formattedQuestion.other_value;
        }
        return Array.isArray(value) ? value.length > 0 : value !== null && value !== undefined;
      case 'comment':
        return value && value.trim() !== '';
      case 'star':
      case 'smile':
      case '1-10':
        return value !== null && value !== undefined;
      default:
        return false;
    }
  }, [answerState, currentStep, data, emptySurvey, error, formattedQuestion, loading]);

  const progressPercentage = useMemo(() => {
    if (steps === 0) return 0;
    return ((currentStep + 1) / steps) * 100;
  }, [currentStep, steps]);

  const loadingItem = useMemo(
      () => <TaleLoadingFallback className="py-20" />,
      []
  );

  return (
      <div className="min-h-screen bg-white">
        {/* Header Card */}
        <div className="bg-white rounded-2xl overflow-hidden">
          <div className="pb-0 md:pb-6 p-3 md:p-6">
            <div className="flex flex-col sm:flex-row items-start justify-between md:mb-6 gap-3">
              <div className="min-w-0 flex-1">
                <div className="flex items-start gap-3 mb-3">
                  <button
                      onClick={() => nav("/surveys")}
                      className="w-9 h-9 rounded-xl border-2 border-gray-800 flex items-center justify-center text-gray-500 hover:bg-gray-50 disabled:opacity-30 disabled:cursor-not-allowed shrink-0"
                  >
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M5.83333 0.5L0.5 5.83333M0.5 5.83333L5.83333 11.1667M0.5 5.83333H11.1667" stroke="#333333" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                  <h1 className="hidden md:block text-xl md:text-3xl font-bold text-gray-900 break-words min-w-0">
                    {data?.survey?.title}
                  </h1>
                </div>
                <div className="hidden md:flex flex-wrap items-center gap-4 text-gray-600">
                  <div className="relative">
                    <img alt={data?.company?.companyName || t("surveyBuilder.questionsManage.companyFallback")} className="w-10 h-10 md:w-14 md:h-14 rounded-full border-2 border-white shadow-lg" src={(data?.assets ?? []).find((asset) => asset.description === "SURVEY_LOGO")?.url ?? data?.company?.assets?.[0]?.url ?? "/assets/survey/respond/no-image.png"} />
                    <div className="absolute -bottom-1 -right-1 bg-gradient-to-r from-green-500 to-teal-500 text-white p-1 rounded-full">
                      <FiCheckCircle className="w-3 h-3" />
                    </div>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <span className="font-medium">{data?.company?.companyName}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <FiStar className="w-4 h-4 text-amber-500" />
                    <span className="font-semibold text-amber-600">
                    {t("home.normal.pointsCount", { count: data?.survey?.rewardPoints || "--" })}
                  </span>
                  </div>
                </div>
              </div>

              {/* User Info */}
              <div className="md:flex items-center gap-3 hidden">
                <div className="p-2 rounded-lg bg-gradient-to-br from-blue-50 to-indigo-50">
                  <FiUserCheck className="w-5 h-5 text-blue-600" />
                </div>
                <div className="text-right rtl:text-left">
                  <div className="text-sm font-medium text-gray-900">
                    {user?.username || t("surveyBuilder.questionsManage.userFallback")}
                  </div>
                  <div className="text-xs text-gray-500">
                    {isUser ? t("surveyBuilder.questionsManage.participantLabel") : t("surveyBuilder.questionsManage.companyUserLabel")}
                  </div>
                </div>
              </div>
            </div>

            {/* Progress Section */}
            <div>
              <div className="flex items-center justify-between text-sm text-gray-600 mb-3">
                <div className="flex items-center gap-2">
                  <FiClock className="w-4 h-4" />
                  <span>{t("survey.question_of", { current: currentStep + 1, total: steps })}</span>
                </div>
                <span className="font-semibold">
                {t("survey.percent_complete", { percent: Math.round(progressPercentage) })}
              </span>
              </div>

              {/* Progress Bar */}
              <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                <div
                    className={`h-full bg-gradient-to-r from-teal-500 to-blue-500 rounded-full transition-all duration-500 ${
                        showProgressAnimation ? 'animate-pulse' : ''
                    }`}
                    style={{ width: `${progressPercentage}%` }}
                />
              </div>
            </div>


          </div>
        </div>

        {/* Main Question Card */}
        <TaleDashbaordMainCard className="md:pt-0 !min-h-0 !rounded-2xl !border-0 overflow-hidden">
          {(loading || !answerState[formattedQuestion?.id]) && !error && loadingItem}
          {error && !loading && (
              <Suspense fallback={loadingItem}>
                <NotFound />
              </Suspense>
          )}

          {!(loading || error || !answerState[formattedQuestion?.id]) && (
              <div>
                <SingleQuestion
                    language={data?.survey?.language}
                    question={formattedQuestion}
                    setQuestion={setFormattedQuestion}
                    currentIndex={currentStep}
                    questions={data.questions}
                    showCompanyLogo={true}
                    showOptions={false}
                    showProgress={false}
                    totalSteps={steps}
                    company={data.company}
                    state={answerState[formattedQuestion.id]}
                    setstate={(v) =>
                        setAnswerState((prev) => ({
                          ...prev,
                          [formattedQuestion.id]:
                              typeof v === "function" ? v(prev[formattedQuestion.id]) : v,
                        }))
                    }
                    onAutoNext={handleNext}
                />

                {/* Action Buttons */}
                <div className="md:pt-8 border-t border-gray-200">{/* Question Info Cards */}
                  <div className="grid grid-cols-1 gap-2 mb-6 md:grid md:grid-cols-1 md:gap-4 md:mb-8">

                    {formattedQuestion.mandatory && !data?.serverAnsweredQuestionIds?.includes(formattedQuestion.id) ? (
                        <div className="flex-1 bg-gradient-to-r from-red-50 to-red-50 rounded-xl p-2 md:p-4 border border-red-200">
                          <div className="flex items-center gap-2">
                            <div className="p-1.5 md:p-2 rounded-lg bg-red-100 shrink-0">
                              <FiAlertCircle className="w-3.5 h-3.5 md:w-4 md:h-4 text-red-600" />
                            </div>
                            <p className="text-sm text-red-600">
                              {t("surveyBuilder.questionsManage.requiredQuestionWarning")}
                            </p>
                          </div>
                        </div>
                    ) : (
                        <div>
                        </div>
                    )}
                    {currentStep === steps - 1 && isSurveyEmpty && (
                        <div className="flex-1 bg-gradient-to-r from-red-50 to-red-50 rounded-xl p-2 md:p-4 border border-red-200">
                          <div className="flex items-center gap-2">
                            <div className="p-1.5 md:p-2 rounded-lg bg-red-100 shrink-0">
                              <FiAlertCircle className="w-3.5 h-3.5 md:w-4 md:h-4 text-red-600" />
                            </div>
                            <p className="text-sm text-red-600">
                              {t("question.at_least_one_required")}
                            </p>
                          </div>
                        </div>
                    )}
                    {data?.serverAnsweredQuestionIds?.includes(formattedQuestion.id) && (
                      <div className="flex-1 bg-gradient-to-r from-blue-50 to-blue-50 rounded-xl p-2 md:p-4 border border-blue-200">
                        <div className="flex items-center gap-2">
                          <div className="p-1.5 md:p-2 rounded-lg bg-blue-100 shrink-0">
                            <FiAlertCircle className="w-3.5 h-3.5 md:w-4 md:h-4 text-blue-600" />
                          </div>
                          <p className="text-sm text-blue-500">
                            {currentStep === steps - 1 ? t("surveyBuilder.questionsManage.alreadyAnsweredFinishMessage") : t("surveyBuilder.questionsManage.alreadyAnsweredNextMessage")}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                  <div className={`flex flex-wrap ${currentStep === 0 ? "justify-end" : "justify-between"} items-center gap-3`}>
                    {currentStep > 0 && (
                        <Button
                            variant="outlined"
                            onClick={handlePrevious}
                            className="!font-semibold !border-2 !border-gray-300 !text-gray-700 !h-[51px] !min-w-[110px] sm:!min-w-[140px] !rounded-xl !normal-case hover:!border-gray-400 hover:!bg-gray-50 transition-all"
                            startIcon={<FiChevronLeft className="w-4 h-4 rtl:-scale-x-100" />}
                        >
                          {t("actions.previous")}
                        </Button>
                    )}

                    <div className="flex flex-col items-end gap-2">
                      <TaleButton
                          onClick={handleNext}
                          role="normal"
                          variant="filled"
                          disabled={
                              (formattedQuestion.mandatory && !isQuestionGood) ||
                              (currentStep === steps - 1 && isSurveyEmpty)
                          }
                          className={`!font-semibold !min-w-[110px] sm:!min-w-[140px] !h-[51px] !rounded-xl ${
                              currentStep === steps - 1
                                  ? '!from-green-600 !to-emerald-600 hover:!from-green-700 hover:!to-emerald-700'
                                  : ''
                          }`}
                          endIcon={currentStep === steps - 1 ? null : <FiChevronRight className="w-4 h-4 rtl:-scale-x-100" />}
                      >
                        {currentStep === steps - 1 ? (
                            t("surveyBuilder.questionsManage.finishSurvey")
                        ) : formattedQuestion.mandatory || isQuestionGood ? (
                            t("surveyBuilder.questionsManage.nextQuestion")
                        ) : (
                            t("surveyBuilder.questionsManage.skipQuestion")
                        )}
                      </TaleButton>
                    </div>
                  </div>
                </div>

                {/* Survey Tips
                <div className="mt-8 p-5 bg-white rounded-xl border border-gray-200">
                  <div className="flex items-start gap-4">
                    <div className="p-2 rounded-lg bg-white border border-teal-200">
                      <BsStarFill className="w-5 h-5 text-teal-600" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900 mb-2">Earn {data?.survey?.rewardPoints || '--'} Points</h4>
                      <p className="text-sm text-gray-600">
                        Complete all questions to earn your points. Your responses help improve products and services.
                        {currentStep === steps - 1 && " This is the final question!"}
                      </p>
                    </div>
                  </div>
                </div> */}
              </div>
          )}
        </TaleDashbaordMainCard>

        {/* Footer
        <div className="p-4 bg-white rounded-2xl shadow-sm border border-gray-200">
          <div className="flex flex-col md:flex-row items-center justify-between gap-4">
            <div className="text-sm text-gray-600">
              Survey ID: <span className="font-mono font-medium">#{surveyId?.slice(0, 8)}...</span>
            </div>
            <div className="flex items-center gap-4">
            <span className="text-sm text-gray-600">
              Status: <span className={`font-medium ${
                data?.survey?.status === 'IN_PROGRESS' ? 'text-green-600' :
                    data?.survey?.status === 'COMPLETED' ? 'text-amber-600' :
                        'text-gray-600'
            }`}>
                {data?.survey?.status || "Loading..."}
              </span>
            </span>
              <span className="text-gray-400">•</span>
              <span className="text-sm text-gray-600">
              Points: <span className="font-semibold text-amber-600">{data?.survey?.rewardPoints || '--'}</span>
            </span>
            </div>
          </div>
        </div> */}
      </div>
  );
};

const ErrorWrapped = () => {
  return (
      <ErrorBoundary
          FallbackComponent={ErrorWrapper}
          onError={(err, info) => console.log(err, info)}
      >
        <SurveyQuestions />
      </ErrorBoundary>
  );
};

export default ErrorWrapped;
