"use client";

import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import {
  usePMScreeningControllerGetQuestionsV1,
  usePMScreeningControllerStartScreeningV1,
  usePMScreeningControllerSubmitAnswersV1,
} from "@/api/user/practice-manager-screening/practice-manager-screening";
import { toast } from "react-hot-toast";

// Disclaimer Screen Component
function DisclaimerScreen({ t, clientName, onAccept, onBack }: {
  t: any;
  clientName: string;
  onAccept: () => void;
  onBack: () => void;
}) {
  return (
    <div className="pt-24 pb-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Back + Client badge row */}
        <div className="flex items-center justify-between mb-6">
          <button
            onClick={onBack}
            className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 transition cursor-pointer"
          >
            <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("practiceManager.screening.backToClients")}
          </button>
          {clientName && (
            <div className="flex items-center gap-2 bg-white border border-gray-100 rounded-full pl-2 pr-3 py-1.5 shadow-sm">
              <div className="w-6 h-6 rounded-full bg-[#3B9EC9]/10 flex items-center justify-center flex-shrink-0">
                <svg className="w-3.5 h-3.5 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                </svg>
              </div>
              <span className="text-xs text-gray-400">{t("practiceManager.screening.screeningFor")}</span>
              <span className="text-xs font-semibold text-gray-800">{clientName}</span>
            </div>
          )}
        </div>

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          {/* Title */}
          <div className="text-center mb-8">
            <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900 mb-2">
              {t("individual.importantInfo.title")}
            </h1>
            <p className="text-gray-500">
              {t("individual.importantInfo.subtitle")}
            </p>
          </div>

          {/* Crisis Information Box */}
          <div className="bg-red-50 border border-red-100 rounded-xl p-6 mb-8">
            <div className="flex items-start gap-3 mb-4">
              <svg className="w-6 h-6 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
              </svg>
              <h2 className="text-lg font-semibold text-red-600">
                {t("individual.importantInfo.crisisTitle")}
              </h2>
            </div>
            <p className="text-red-700 mb-4">
              {t("individual.importantInfo.crisisText1")}{" "}
              {t("individual.importantInfo.crisisText2")}
            </p>
            <div className="mb-4">
              <h3 className="font-semibold text-red-700 mb-2">
                {t("individual.importantInfo.lifeline")}
              </h3>
              <ul className="space-y-1 text-red-700">
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.dial988")}
                </li>
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.text988")}
                </li>
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.visit988")}
                </li>
              </ul>
            </div>
            <div>
              <h3 className="font-semibold text-red-700 mb-2">
                {t("individual.importantInfo.nami")}
              </h3>
              <ul className="space-y-1 text-red-700">
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.namiCall")}
                </li>
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.namiText")}
                </li>
                <li className="flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></span>
                  {t("individual.importantInfo.namiEmail")}
                </li>
              </ul>
            </div>
          </div>

          {/* Risk Disclaimer & Informed Consent */}
          <div className="mb-8">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">
              {t("individual.importantInfo.disclaimerTitle")}
            </h2>
            <p className="text-gray-600 mb-6">
              {t("individual.importantInfo.disclaimerText")}
            </p>
            <h3 className="font-semibold text-gray-900 mb-3">
              {t("individual.importantInfo.limitationsTitle")}
            </h3>
            <ul className="space-y-2 text-gray-600 mb-6">
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.limitation1")}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.limitation2")}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.limitation3")}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.limitation4")}</span>
              </li>
            </ul>
            <h3 className="font-semibold text-gray-900 mb-3">
              {t("individual.importantInfo.expectTitle")}
            </h3>
            <ul className="space-y-2 text-gray-600">
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.expect1")}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.expect2")}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></span>
                <span>{t("individual.importantInfo.expect3")}</span>
              </li>
            </ul>
          </div>

          {/* Continue Button */}
          <div className="flex justify-center">
            <button
              onClick={onAccept}
              className="px-8 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
            >
              {t("individual.importantInfo.acknowledgeBtn")}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function DynamicScreeningPage() {
  const router = useRouter();
  const params = useParams();
  const t = useTranslations();
  const locale = useLocale();

  const clientId = params.clientId as string;

  // sessionStorage keys — scoped to clientId so different clients don't share state
  const SS_UUID = `pm_suuid_${clientId}`;
  const SS_NAME = `pm_cname_${clientId}`;
  const SS_DISC = `pm_disc_${clientId}`;
  const SS_QNUM = `pm_qnum_${clientId}`;
  const SS_ANS  = `pm_ans_${clientId}`;

  // Initialise state from sessionStorage so locale toggle (which remounts the page)
  // doesn't lose the screening session or reset the disclaimer acceptance
  const [screeningUuid, setScreeningUuid] = useState<string | null>(() =>
    typeof window !== "undefined" ? sessionStorage.getItem(SS_UUID) : null
  );
  const [clientName, setClientName] = useState<string>(() =>
    typeof window !== "undefined" ? sessionStorage.getItem(SS_NAME) ?? "" : ""
  );
  const [disclaimerAccepted, setDisclaimerAccepted] = useState<boolean>(() =>
    typeof window !== "undefined" ? sessionStorage.getItem(SS_DISC) === "true" : false
  );
  const [isStarting, setIsStarting] = useState<boolean>(() =>
    typeof window !== "undefined" ? !sessionStorage.getItem(SS_UUID) : true
  );
  const [startError, setStartError] = useState<string | null>(null);
  const [currentQuestion, setCurrentQuestion] = useState<number>(() =>
    typeof window !== "undefined" ? parseInt(sessionStorage.getItem(SS_QNUM) ?? "0", 10) || 0 : 0
  );
  const [answers, setAnswers] = useState<Record<string, number>>(() => {
    if (typeof window !== "undefined") {
      try { return JSON.parse(sessionStorage.getItem(SS_ANS) ?? "{}"); } catch { return {}; }
    }
    return {};
  });

  // Start screening mutation
  const startScreeningMutation = usePMScreeningControllerStartScreeningV1();

  // Fetch questions from API
  const {
    data: questionsResponse,
    isLoading: isLoadingQuestions,
  } = usePMScreeningControllerGetQuestionsV1();

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

  // Start screening on mount — skipped if session already cached (e.g. after locale change)
  useEffect(() => {
    if (clientId && !sessionStorage.getItem(SS_UUID)) {
      setIsStarting(true);
      startScreeningMutation.mutate(
        { data: { client_uuid: clientId } },
        {
          onSuccess: (response: any) => {
            const data = response?.data;
            if (data) {
              setScreeningUuid(data.screening_uuid);
              setClientName(data.client_name || "");
              sessionStorage.setItem(SS_UUID, data.screening_uuid);
              sessionStorage.setItem(SS_NAME, data.client_name || "");
            }
            setIsStarting(false);
          },
          onError: (error: any) => {
            console.error("Failed to start screening:", error);
            setStartError(
              error?.response?.data?.message || "Failed to start screening session"
            );
            setIsStarting(false);
          },
        }
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [clientId]);

  const questions = (questionsResponse as any)?.data || [];
  // Sort questions by order
  const sortedQuestions = [...questions].sort(
    (a: any, b: any) => (a.order || 0) - (b.order || 0)
  );
  const totalQuestions = sortedQuestions.length;
  const progress =
    totalQuestions > 0
      ? Math.round(((currentQuestion + 1) / totalQuestions) * 100)
      : 0;

  const currentQuestionData = sortedQuestions[currentQuestion];

  // Use locale-aware question text
  const getQuestionText = (question: any) => {
    if (locale === "es" && question?.text_es) {
      return question.text_es;
    }
    return question?.text || "";
  };

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

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

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

  const handleSelectAnswer = (value: number) => {
    if (currentQuestionData) {
      const updated = { ...answers, [currentQuestionData.uuid]: value };
      setAnswers(updated);
      sessionStorage.setItem(SS_ANS, JSON.stringify(updated));
    }
  };

  const handlePrevious = () => {
    if (currentQuestion > 0) {
      const next = currentQuestion - 1;
      setCurrentQuestion(next);
      sessionStorage.setItem(SS_QNUM, String(next));
    }
  };

  const handleNext = () => {
    if (!screeningUuid) return;

    if (currentQuestion < totalQuestions - 1) {
      const next = currentQuestion + 1;
      setCurrentQuestion(next);
      sessionStorage.setItem(SS_QNUM, String(next));
    }
  };

  const handleSubmit = () => {
    if (!screeningUuid) return;

    // Build answers array from all answered questions
    const answersArray = Object.entries(answers).map(([questionUuid, answer]) => ({
      question_uuid: questionUuid,
      answer,
    }));

    submitAnswersMutation.mutate(
      {
        uuid: screeningUuid,
        data: { answers: answersArray },
      },
      {
        onSuccess: (response: any) => {
          const resultUuid = response?.data?.uuid || screeningUuid;
          // Clear session cache after successful submission
          sessionStorage.removeItem(SS_UUID);
          sessionStorage.removeItem(SS_NAME);
          sessionStorage.removeItem(SS_DISC);
          sessionStorage.removeItem(SS_QNUM);
          sessionStorage.removeItem(SS_ANS);
          router.push(`/${locale}/practice-manager/report/${resultUuid}`);
        },
        onError: (error: any) => {
          console.error("Failed to submit screening:", error);
          const errMsg: string = error?.response?.data?.message || "";
          const isAlreadyCompleted =
            errMsg.toLowerCase().includes("already completed") ||
            errMsg === "practice-manager.screening_already_completed";
          // If screening already completed, clear stale session and redirect to report
          if (isAlreadyCompleted) {
            sessionStorage.removeItem(SS_UUID);
            sessionStorage.removeItem(SS_NAME);
            sessionStorage.removeItem(SS_DISC);
            sessionStorage.removeItem(SS_QNUM);
            sessionStorage.removeItem(SS_ANS);
            router.push(`/${locale}/practice-manager/report/${screeningUuid}`);
            return;
          }
          toast.error(
            t("practiceManager.screening.submitError") ||
              "Failed to submit screening. Please try again."
          );
        },
      }
    );
  };

  const isLastQuestion = currentQuestion === totalQuestions - 1;

  const getOptionStyles = (_index: number, isSelected: boolean) => {
    if (isSelected) {
      return "bg-[#E8F7FA] border-[#3B9EC9] text-gray-900";
    }
    return "bg-white border-gray-300 text-gray-700";
  };

  const getRadioStyles = (_index: number, isSelected: boolean) => {
    if (isSelected) {
      return "border-[#3B9EC9] bg-[#3B9EC9]";
    }
    return "border-gray-300 bg-white";
  };

  // Loading state
  if (isStarting || isLoadingQuestions) {
    return (
      <div className="pt-24 pb-8 flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <svg
            className="animate-spin w-10 h-10 text-[#3B9EC9] mx-auto mb-4"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
          >
            <circle
              className="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              strokeWidth="4"
            ></circle>
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            ></path>
          </svg>
          <p className="text-gray-600">
            {t("practiceManager.common.loading")}
          </p>
        </div>
      </div>
    );
  }

  // Error state
  if (startError || !screeningUuid) {
    return (
      <div className="pt-24 pb-8 flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            {t("practiceManager.screening.clientNotFound")}
          </h2>
          <p className="text-gray-600 mb-4">
            {startError ||
              t("practiceManager.screening.clientNotFoundDescription")}
          </p>
          <button
            onClick={() => router.push(`/${locale}/practice-manager/patients`)}
            className="px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition"
          >
            {t("practiceManager.screening.backToClients")}
          </button>
        </div>
      </div>
    );
  }

  // No questions state
  if (totalQuestions === 0) {
    return (
      <div className="pt-24 pb-8 flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            {t("practiceManager.screening.noQuestions") ||
              "No questions available"}
          </h2>
          <p className="text-gray-600 mb-4">
            {t("practiceManager.screening.noQuestionsDescription") ||
              "There are no screening questions available at this time."}
          </p>
          <button
            onClick={() => router.push(`/${locale}/practice-manager/patients`)}
            className="px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition"
          >
            {t("practiceManager.screening.backToClients")}
          </button>
        </div>
      </div>
    );
  }

  // Disclaimer Screen - shown before questions
  if (!disclaimerAccepted) {
    return (
      <DisclaimerScreen
        t={t}
        clientName={clientName}
        onAccept={() => {
          setDisclaimerAccepted(true);
          sessionStorage.setItem(SS_DISC, "true");
        }}
        onBack={() => router.push(`/${locale}/practice-manager/patients`)}
      />
    );
  }

  return (
    <div className="pt-24 pb-8">
      {/* Main Content */}
      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Client Info Card */}
        {clientName && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 mb-6">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 rounded-full bg-[#3B9EC9]/10 flex items-center justify-center flex-shrink-0">
                <svg
                  className="w-7 h-7 text-[#3B9EC9]"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1.5}
                    d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
                  />
                </svg>
              </div>
              <div className="flex-1">
                <p className="text-xs text-gray-500 mb-0.5">{t("practiceManager.screening.screeningFor")}</p>
                <h3 className="text-xl font-semibold text-gray-900">
                  {clientName}
                </h3>
              </div>
            </div>
          </div>
        )}

        {/* Screening Card */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-10">
          {/* Progress Header */}
          <div className="flex items-center justify-between mb-3">
            <span className="text-base font-medium text-gray-700">
              {t("practiceManager.screening.questionOf")} {currentQuestion + 1}{" "}
              {t("practiceManager.screening.of")} {totalQuestions}
            </span>
            <span className="text-base text-gray-500">
              {progress}% {t("practiceManager.screening.complete")}
            </span>
          </div>

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

          {/* Question */}
          <h2 className="text-xl font-semibold text-gray-900 mb-8">
            {getQuestionText(currentQuestionData)}
          </h2>

          {/* Options */}
          <div className="space-y-4 mb-10">
            {answerOptions.map((option, index) => {
              const isSelected = selectedAnswer === option.value;
              return (
                <button
                  key={option.value}
                  onClick={() => handleSelectAnswer(option.value)}
                  className={`w-full flex items-center gap-5 px-6 py-5 rounded-xl border-2 transition ${getOptionStyles(
                    index,
                    isSelected
                  )}`}
                >
                  <div
                    className={`w-7 h-7 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition ${getRadioStyles(
                      index,
                      isSelected
                    )}`}
                  >
                    {isSelected && (
                      <svg
                        className="w-4 h-4 text-white"
                        fill="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                      </svg>
                    )}
                  </div>
                  <span className="text-base font-medium">{option.label}</span>
                </button>
              );
            })}
          </div>

          {/* Navigation Buttons */}
          <div className="flex items-center gap-4">
            <button
              onClick={handlePrevious}
              disabled={currentQuestion === 0}
              className="flex items-center gap-2 px-8 py-4 text-base font-medium text-[#3B9EC9] bg-white border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 disabled:opacity-50 disabled:cursor-not-allowed 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("practiceManager.screening.previous")}
            </button>
            <button
              onClick={isLastQuestion ? handleSubmit : handleNext}
              disabled={
                selectedAnswer === undefined ||
                submitAnswersMutation.isPending
              }
              className="flex-1 flex items-center justify-center gap-2 px-8 py-4 text-base font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] disabled:opacity-50 disabled:cursor-not-allowed transition"
            >
              {submitAnswersMutation.isPending ? (
                <>
                  <svg
                    className="animate-spin w-5 h-5"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    ></circle>
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    ></path>
                  </svg>
                  <span>
                    {t("practiceManager.screening.submitting")}
                  </span>
                </>
              ) : (
                <>
                  {isLastQuestion
                    ? t("practiceManager.screening.submitScreening")
                    : t("practiceManager.screening.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>
      </main>
    </div>
  );
}
