'use client';

import { notFound } from 'next/navigation';
import { useEffect, useState, useMemo, use, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Questionnaire } from '@/types';
import Link from 'next/link';
import { ResultContainer } from '@/components/questionnaire/result/public/ResultContainer';
import { AnswerList } from '@/components/questionnaire/result/public/AnswerList';
import { ResultAnalysis } from '@/components/questionnaire/result/analysis/ResultAnalysis';
import { useQuestionnaire } from '@/hooks/useQuestionnaire';
import { useScopedI18n } from '@/locales/client';
import { loadResult } from '@/lib/result-storage';
import { AssessmentRecord } from '@/lib/assessment-types';
import { getProfiles, getRecords, updateRecordAnalysis } from '@/lib/assessment-db';

export default function QuestionnaireResultPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const [loading, setLoading] = useState(true);
  const [decodedAnswers, setDecodedAnswers] = useState<string[] | null>(null);
  const [record, setRecord] = useState<AssessmentRecord | null>(null);
  const [profileName, setProfileName] = useState('未命名档案');
  const analysisRef = useRef<HTMLDivElement>(null);
  const t = useScopedI18n('app.questionnaire.result');

  // Get the questionnaire with specified id from questionnaire data
  const questionnaire = useQuestionnaire(id) as Questionnaire;
  const recordId = record?.id;

  // Load results from tab-local storage. Answers are intentionally not kept in the URL.
  useEffect(() => {
    if (!questionnaire || !questionnaire.details) {
      return;
    }

    const stored = loadResult(id);
    setDecodedAnswers(stored?.answers || null);
    async function loadRecord() {
      if (stored?.profileId) {
        const profiles = await getProfiles();
        setProfileName(profiles.find((profile) => profile.id === stored.profileId)?.name || '未命名档案');
      }
      if (stored?.recordId) {
        const records = await getRecords(stored.profileId);
        setRecord(records.find((item) => item.id === stored.recordId) || null);
      }
      setLoading(false);
    }
    void loadRecord();
  }, [id, questionnaire]);

  useEffect(() => {
    if (!recordId || !analysisRef.current) return;
    const timer = window.setTimeout(() => {
      const text = analysisRef.current?.innerText.trim() || '';
      if (!text) return;
      setRecord((current) => current ? { ...current, analysisText: text } : current);
      void updateRecordAnalysis(recordId, text);
    }, 100);
    return () => window.clearTimeout(timer);
  }, [recordId]);

  // Construct question-option text pairs for copying result data
  const questionnaireResults: Record<string, string> = useMemo(() => {
    if (!questionnaire || !decodedAnswers) return {};
    const obj: Record<string, string> = {};
    questionnaire.questions.forEach((q, idx) => {
      const val = decodedAnswers[idx];
      if (val === undefined) return;
      const option = questionnaire.renderOptions(q.id).find(
        (o) => String(o.value) === String(val)
      );
      obj[q.content] = option ? option.content : String(val);
    });
    return obj;
  }, [decodedAnswers, questionnaire]);

  // If data not found, show 404 page
  if (!questionnaire || !questionnaire.details) {
    return notFound();
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (!decodedAnswers || decodedAnswers.length !== questionnaire.questions.length) {
    return (
      <div className="flex justify-center items-center min-h-screen  md:p-4 p-2">
        <div className="max-w-6xl w-full bg-white rounded-lg shadow-lg md:p-8 p-4 border">
          <h1 className="text-2xl font-bold mb-6">
            {questionnaire.title} - {t('resultNotFoundTitle')}
          </h1>
          <p className="text-gray-700 mb-6">{t('resultNotFoundDesc')}</p>
          <Button>
            <Link href={`/questionnaire/${id}`}>{t('retryTest')}</Link>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <ResultContainer 
      title={questionnaire.title} 
      id={id}
      questionnaire={questionnaire}
      answers={decodedAnswers}
      questionnaireResults={questionnaireResults}
      record={record || undefined}
      profileName={profileName}
    >
      <AnswerList
        questions={questionnaire.questions}
        answers={decodedAnswers}
        renderOptions={questionnaire.renderOptions}
      />
      <div ref={analysisRef}>
        <ResultAnalysis questionnaireId={id} answers={decodedAnswers} />
      </div>
    </ResultContainer>
  );
}
