"use client";

import { useState, useEffect } from "react";
import { useRouter } from "@/i18n/navigation";
import { useSearchParams } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import { usePaymentControllerVerifyPaymentV1 } from "@/api/user/individual-payment/individual-payment";
import { useGetQuestions, useSubmitAnswers } from "@/api/user/individual-screening/individual-screening";
import { instance } from "@/config/axios";
import { toast } from "react-hot-toast";

interface QuestionsProps {
  screeningUuid: string;
}

export default function Questions({ screeningUuid }: QuestionsProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations("individual.questions");
  const locale = useLocale();

  const sessionId = searchParams.get("session_id");
  // PM/practitioner-assigned, therapist-invited, OR already-paid self-screenings skip Stripe re-verification
  const source = searchParams.get("source");
  const isAssigned = source === "assigned" || source === "paid" || source === "trial";

  // Initialize paymentVerified immediately for assigned screenings — avoids "Access Denied" flash
  const [paymentVerified, setPaymentVerified] = useState(isAssigned);
  const [currentQuestion, setCurrentQuestion] = useState(() => {
    // Initialize from URL query param if available
    const questionParam = searchParams.get("q");
    return questionParam ? parseInt(questionParam, 10) : 0;
  });
  const [answers, setAnswers] = useState<Record<string, number>>({});
  const [hasSetInitialQuestion, setHasSetInitialQuestion] = useState(false);
  // Update URL when current question changes
  useEffect(() => {
    const currentPath = window.location.pathname;
    const params = new URLSearchParams(window.location.search);

    // Update or add the question parameter
    if (currentQuestion > 0) {
      params.set("q", currentQuestion.toString());
    } else {
      params.delete("q");
    }

    const newUrl = `${currentPath}${params.toString() ? '?' + params.toString() : ''}`;

    // Use replaceState to update URL without triggering navigation
    if (window.location.pathname + window.location.search !== newUrl) {
      window.history.replaceState({}, '', newUrl);
    }
  }, [currentQuestion]);

  // Verify payment (skipped for PM/practitioner-assigned screenings)
  const {
    data: verificationData,
    isLoading: isVerifying,
    error: verificationError,
  } = usePaymentControllerVerifyPaymentV1(
    { session_id: sessionId || screeningUuid },
    {
      query: {
        enabled: !isAssigned && (!!sessionId || !!screeningUuid),
        retry: 2,
      },
    }
  );

  // Load questions
  const {
    data: questionsData,
    isLoading: isLoadingQuestions,
    error: questionsError,
  } = useGetQuestions(screeningUuid, {
    query: {
      enabled: paymentVerified,
    },
  });

  // Submit answers mutation
  const submitAnswersMutation = useSubmitAnswers();


  // Check payment verification
  useEffect(() => {
    // PM/practitioner-assigned screenings don't require Stripe payment
    if (isAssigned) {
      setPaymentVerified(true);
      return;
    }
    const data = verificationData as any;
    if (data?.data?.verified) {
      setPaymentVerified(true);
    } else if (verificationError) {
      // Payment not verified, redirect to payment page
      router.push(`/individual/screening/payment?error=payment_required`);
    }
  }, [verificationData, verificationError, router, isAssigned]);

  // Fetch existing answers from backend and check screening status
  useEffect(() => {
    const fetchExistingAnswers = async () => {
      if (!paymentVerified || !screeningUuid) return;

      try {
        const response = await instance.get(
          `/v1/individual/screening/${screeningUuid}/answers`
        );

        // Check if screening is already completed
        if (response.data?.data?.status === "completed") {
          // Redirect to reports page
          router.push(`/individual/screening/${screeningUuid}/reports`);
          return;
        }

        if (response.data?.data?.answers) {
          const existingAnswers: Record<string, number> = {};
          response.data.data.answers.forEach((item: { question_uuid: string; answer: number }) => {
            existingAnswers[item.question_uuid] = item.answer;
          });
          setAnswers(existingAnswers);
        }
      } catch (error) {
        console.error("Failed to fetch existing answers:", error);
        // If fetch fails, try loading from localStorage as fallback
        const saved = localStorage.getItem(`screening_${screeningUuid}_answers`);
        if (saved) {
          try {
            setAnswers(JSON.parse(saved));
          } catch (e) {
            console.error("Failed to parse saved answers:", e);
          }
        }
      }
    };

    fetchExistingAnswers();
  }, [paymentVerified, screeningUuid, router]);

  // Check for screening completion when window regains focus or on page visibility change
  useEffect(() => {
    if (!paymentVerified || !screeningUuid) return;

    const checkScreeningStatus = async () => {
      try {
        const response = await instance.get(
          `/v1/individual/screening/${screeningUuid}/answers`
        );

        if (response.data?.data?.status === "completed") {
          router.push(`/individual/screening/${screeningUuid}/reports`);
        }
      } catch (error) {
        // Ignore errors in periodic check
      }
    };

    // Check when window regains focus
    const handleFocus = () => {
      checkScreeningStatus();
    };

    // Check when page becomes visible
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        checkScreeningStatus();
      }
    };

    window.addEventListener("focus", handleFocus);
    document.addEventListener("visibilitychange", handleVisibilityChange);

    // Cleanup listeners on unmount
    return () => {
      window.removeEventListener("focus", handleFocus);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [paymentVerified, screeningUuid, router]);

  const questions =
    (questionsData as any)?.data?.questions ||
    (questionsData as any)?.data?.data?.questions ||
    (Array.isArray((questionsData as any)?.data) ? (questionsData as any)?.data : null) ||
    [];

  // Set current question to first unanswered question when questions load (only once)
  useEffect(() => {
    if (!hasSetInitialQuestion && questions.length > 0) {
      // Only jump to first unanswered if there are existing answers AND no question param in URL
      const questionParam = searchParams.get("q");
      if (!questionParam && Object.keys(answers).length > 0) {
        const firstUnanswered = questions.findIndex((q: any) => answers[q.uuid] === undefined);
        if (firstUnanswered !== -1) {
          setCurrentQuestion(firstUnanswered);
        }
      }
      // Set the flag regardless to prevent future auto-jumps
      setHasSetInitialQuestion(true);
    }
  }, [questions, answers, hasSetInitialQuestion, searchParams]);

  // Save answers to localStorage
  useEffect(() => {
    if (Object.keys(answers).length > 0) {
      localStorage.setItem(`screening_${screeningUuid}_answers`, JSON.stringify(answers));
    }
  }, [answers, screeningUuid]);
  const totalQuestions = questions.length;
  const progress = totalQuestions > 0 ? Math.round(((currentQuestion + 1) / totalQuestions) * 100) : 0;

  // Check if we're on question 29 (the last question)
  const isQuestion29 = currentQuestion === 28 && totalQuestions === 29;

  const handleAnswer = (value: number) => {
    const currentQuestionUuid = questions[currentQuestion]?.uuid;
    if (currentQuestionUuid) {
      setAnswers((prev) => ({
        ...prev,
        [currentQuestionUuid]: value,
      }));
    }
  };

  const handlePrevious = () => {
    if (currentQuestion > 0) {
      setCurrentQuestion(currentQuestion - 1);
    }
  };

  const handleNext = () => {
    // Get current question's answer
    const currentQuestionUuid = questions[currentQuestion]?.uuid;
    const currentAnswer = answers[currentQuestionUuid];

    if (currentAnswer === undefined) {
      return; // No answer selected
    }

    // Save current answer to database
    submitAnswersMutation.mutate(
      {
        uuid: screeningUuid,
        data: {
          answers: [
            {
              question_uuid: currentQuestionUuid,
              answer: currentAnswer,
            },
          ],
        },
      },
      {
        onSuccess: () => {
          if (currentQuestion < totalQuestions - 1) {
            // Move to next question
            setCurrentQuestion(currentQuestion + 1);
          } else {
            // Last question - redirect to reports
            localStorage.removeItem(`screening_${screeningUuid}_answers`);
            router.push(`/individual/screening/${screeningUuid}/reports`);
          }
        },
        onError: (error: any) => {
          console.error("Failed to save answer:", error);

          // Check if screening is already completed
          if (error?.response?.data?.message === "individual.screening_already_completed") {
            router.push(`/individual/screening/${screeningUuid}/reports`);
            return;
          }

          toast.error(t("submitError"));
        },
      }
    );
  };

  const currentQuestionData = questions[currentQuestion];
  const selectedAnswer = currentQuestionData ? answers[currentQuestionData.uuid] : undefined;

  // Check if current question uses count-type response (Q29)
  const isCountType = currentQuestionData?.response_type === "count" || isQuestion29;

  const answerOptions = isCountType
    ? [
        { value: 0, label: t("countOption0") },
        { value: 1, label: t("countOption1") },
        { value: 2, label: t("countOption2") },
        { value: 3, label: t("countOption3") },
      ]
    : [
        { value: 0, label: t("option0") },
        { value: 1, label: t("option1") },
        { value: 2, label: t("option2") },
        { value: 3, label: t("option3") },
      ];

  // Loading state
  if (isVerifying || isLoadingQuestions) {
    return (
      <main className="pt-20 pb-8">
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 text-center">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
            <p className="mt-4 text-gray-600">
              {isVerifying ? t("verifyingPayment") : t("loadingQuestions")}
            </p>
          </div>
        </div>
      </main>
    );
  }

  // Payment not verified (self-paid screenings only)
  if (!paymentVerified) {
    return (
      <main className="pt-20 pb-8">
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 text-center">
            <div className="text-[#D12E34] mb-4">
              <svg className="w-12 h-12 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 className="text-xl font-semibold text-gray-900 mb-2">
              {t("accessDenied")}
            </h2>
            <p className="text-gray-600 mb-6">
              {t("paymentRequired")}
            </p>
            <button
              onClick={() => router.push(`/individual/screening/payment`)}
              className="px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition cursor-pointer"
            >
              {t("goToPayment")}
            </button>
          </div>
        </div>
      </main>
    );
  }

  // Questions failed to load
  if (questionsError || !currentQuestionData) {
    return (
      <main className="pt-20 pb-8">
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 text-center">
            <div className="text-[#D12E34] mb-4">
              <svg className="w-12 h-12 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 className="text-xl font-semibold text-gray-900 mb-2">
              {t("loadError")}
            </h2>
            <p className="text-gray-600 mb-6">
              {t("questionsLoadError")}
            </p>
            <button
              onClick={() => router.push(`/individual`)}
              className="px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition cursor-pointer"
            >
              {t("backToDashboard")}
            </button>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Main Card */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          {/* Progress Header */}
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-900">
              {t("questionOf")} {currentQuestion + 1} {t("of")} {totalQuestions}
            </span>
            <span className="text-sm text-gray-500">{progress}% {t("complete")}</span>
          </div>

          {/* Progress Bar */}
          <div className="h-2 bg-gray-200 rounded-full mb-8">
            <div
              className="h-2 bg-[#3B9EC9] rounded-full transition-all duration-300"
              style={{ width: `${progress}%` }}
            />
          </div>

          {/* Question */}
          <h2 className="text-xl font-medium text-gray-900 mb-6">
            {locale === "es" && currentQuestionData.text_es
              ? currentQuestionData.text_es
              : currentQuestionData.text}
          </h2>

          {/* Answer Options */}
          <div className="space-y-3 mb-8">
            {answerOptions.map((option) => {
              const isSelected = selectedAnswer === option.value;
              return (
                <button
                  key={option.value}
                  onClick={() => handleAnswer(option.value)}
                  className={`w-full flex items-center gap-4 p-4 rounded-xl border-2 transition cursor-pointer ${
                    isSelected
                      ? "bg-[#E8F7FA] border-[#3B9EC9] text-gray-900"
                      : "bg-white border-gray-300 text-gray-700"
                  }`}
                >
                  <div
                    className={`w-6 h-6 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition ${
                      isSelected
                        ? "border-[#3B9EC9] bg-[#3B9EC9]"
                        : "border-gray-300 bg-white"
                    }`}
                  >
                    {isSelected && <div className="w-2 h-2 rounded-full bg-white" />}
                  </div>
                  <span className="text-sm text-gray-700">{option.label}</span>
                </button>
              );
            })}
          </div>

          {/* Navigation Buttons */}
          <div className="flex gap-4">
            <button
              onClick={handlePrevious}
              disabled={currentQuestion === 0}
              className="flex items-center justify-center gap-2 px-6 py-3 text-sm font-medium text-[#3B9EC9] bg-white border-2 border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
              </svg>
              {t("previous")}
            </button>
            <button
              onClick={handleNext}
              disabled={selectedAnswer === undefined || submitAnswersMutation.isPending}
              className="flex-1 flex items-center justify-center gap-2 px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition"
            >
              {submitAnswersMutation.isPending ? (
                <>
                  <div className="inline-block animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  <span>{t("submitting")}</span>
                </>
              ) : (
                <>
                  {currentQuestion === totalQuestions - 1 ? t("completeScreening") : t("nextQuestion")}
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                  </svg>
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </main>
  );
}
