'use client';

import { notFound } from 'next/navigation';
import { useEffect, useMemo, use, useState } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Questionnaire } from '@/types';
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 } 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 t = useScopedI18n('app.questionnaire.result');

  const questionnaire = useQuestionnaire(id) as Questionnaire;

  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]);

  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 (!questionnaire || !questionnaire.details) {
    return notFound();
  }

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

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