'use client';

import React, { useState } from 'react';
import { X, ArrowRight, ArrowLeft, RotateCcw, Sparkles, CheckCircle2, ChevronDown, MessageSquare } from 'lucide-react';
import { AURA_QUESTIONS } from '@/lib/aura/questions';
import { localizeQuestion } from '@/lib/aura/questionsI18n';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import { useLocale, useMessages } from '@/i18n/client';
import {
  calculateAuraScore,
  getStaticAuraInterpretation,
  CHAKRA_METADATA,
} from '@/lib/aura/calculator';
import { AuraCalculationResult, AuraInterpretation, ChakraType } from '@/lib/aura/types';

interface AuraAssessmentModalProps {
  isOpen: boolean;
  onClose: () => void;
  onOpenChat?: () => void;
  onComplete?: (result: AuraCalculationResult) => void;
}

export const AuraAssessmentModal: React.FC<AuraAssessmentModalProps> = ({
  isOpen,
  onClose,
  onOpenChat,
  onComplete,
}) => {
  const locale = useLocale();
  const all = useMessages().assess;
  const t = all.aura;
  const meta = chakraMeta(locale);
  const [currentQuestionIdx, setCurrentQuestionIdx] = useState(0);
  const [answers, setAnswers] = useState<Record<string, number>>({});
  const [result, setResult] = useState<AuraCalculationResult | null>(null);
  const [interpretation, setInterpretation] = useState<AuraInterpretation | null>(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [quickMode, setQuickMode] = useState(false);

  if (!isOpen) return null;

  const questionsList = quickMode
    ? AURA_QUESTIONS.filter((_, idx) => idx % 5 === 0)
    : AURA_QUESTIONS;

  const currentQ = questionsList[currentQuestionIdx];
  const currentText = localizeQuestion(currentQ, locale);
  const progressPercent = Math.round(
    ((currentQuestionIdx + 1) / questionsList.length) * 100
  );

  const handleSelectAnswer = (ansIdx: number) => {
    const updated = { ...answers, [currentQ.id]: ansIdx };
    setAnswers(updated);

    if (currentQuestionIdx < questionsList.length - 1) {
      setCurrentQuestionIdx(currentQuestionIdx + 1);
    } else {
      finishAssessment(updated);
    }
  };

  const finishAssessment = async (finalAnswers: Record<string, number>) => {
    setIsAnalyzing(true);
    try {
      const res = await fetch('/api/aura/calculate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ answers: finalAnswers }),
      });
      const json = await res.json();
      if (json.success && json.data) {
        setResult(json.data);
        setInterpretation(json.data.interpretation);
        onComplete?.(json.data);
      } else {
        throw new Error('API fallback');
      }
    } catch {
      // Local fallback calculation
      const calcResult = calculateAuraScore(finalAnswers);
      const interp = getStaticAuraInterpretation(calcResult, locale);
      setResult(calcResult);
      setInterpretation(interp);
      onComplete?.(calcResult);
    } finally {
      setIsAnalyzing(false);
    }
  };

  const fillQuickAnswers = () => {
    const simulated: Record<string, number> = {};
    for (const q of questionsList) {
      simulated[q.id] = 2;
    }
    setAnswers(simulated);
    finishAssessment(simulated);
  };

  const resetAll = () => {
    setCurrentQuestionIdx(0);
    setAnswers({});
    setResult(null);
    setInterpretation(null);
  };

  const chakrasOrder: ChakraType[] = [
    'crown',
    'third_eye',
    'throat',
    'heart',
    'solar_plexus',
    'sacral',
    'root',
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-4 bg-black/80 backdrop-blur-md animate-fade-in overflow-y-auto">
      <div className="relative w-full max-w-4xl bg-white rounded-3xl overflow-hidden shadow-2xl text-slate-900 my-auto min-h-[560px] flex flex-col">
        {/* Header Bar */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 bg-slate-50/50">
          <div className="flex items-center gap-2">
            <span className="w-2.5 h-2.5 rounded-full bg-[#4C7DFF]" />
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500">
              {t.header}
            </span>
          </div>

          <div className="flex items-center gap-3">
            {!result && (
              <button
                onClick={fillQuickAnswers}
                className="text-xs font-semibold text-[#4C7DFF] hover:underline"
              >
                {t.autofill}
              </button>
            )}
            <button
              onClick={onClose}
              aria-label={all.close}
              className="w-8 h-8 rounded-full bg-slate-200/60 hover:bg-slate-200 text-slate-700 flex items-center justify-center transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Loading State */}
        {isAnalyzing && (
          <div className="flex-1 flex flex-col items-center justify-center p-12 text-center space-y-4">
            <div className="w-16 h-16 rounded-full border-4 border-[#4C7DFF]/20 border-t-[#4C7DFF] animate-spin" />
            <h3 className="text-xl font-bold text-slate-900">
              {t.analyzing}
            </h3>
            <p className="text-sm text-slate-500 max-w-sm">
              {t.analyzingText}
            </p>
          </div>
        )}

        {/* Questionnaire State */}
        {!isAnalyzing && !result && (
          <div className="flex-1 p-6 sm:p-10 flex flex-col justify-between">
            <div>
              <div className="flex justify-between items-center text-xs text-slate-400 font-semibold mb-2">
                <span>
                  {t.progress(currentQuestionIdx + 1, questionsList.length)}
                </span>
                <span>{progressPercent}%</span>
              </div>
              <div className="h-1.5 w-full bg-slate-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#4C7DFF] transition-all duration-300"
                  style={{ width: `${progressPercent}%` }}
                />
              </div>

              <div className="mt-8">
                <span className="text-xs font-bold uppercase tracking-wider text-[#4C7DFF]">
                  {currentText.topic}
                </span>
                <h3 className="text-xl sm:text-2xl font-bold text-slate-900 mt-2 leading-relaxed">
                  {currentText.question}
                </h3>
              </div>
            </div>

            <div className="my-8 space-y-3">
              {currentText.answers.map((ans, idx) => {
                const isSelected = answers[currentQ.id] === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => handleSelectAnswer(idx)}
                    className={`w-full text-left p-4 rounded-2xl border transition-all duration-200 flex items-center justify-between text-sm ${
                      isSelected
                        ? 'border-[#4C7DFF] bg-blue-50/40 text-slate-900 font-semibold shadow-sm'
                        : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50/70 text-slate-700'
                    }`}
                  >
                    <span>{ans}</span>
                    <ArrowRight className="w-4 h-4 text-slate-400 shrink-0 ml-3" />
                  </button>
                );
              })}
            </div>

            <div className="flex items-center justify-between pt-4 border-t border-slate-100">
              <button
                disabled={currentQuestionIdx === 0}
                onClick={() => setCurrentQuestionIdx(currentQuestionIdx - 1)}
                className="flex items-center gap-1.5 text-xs font-semibold text-slate-500 disabled:opacity-30"
              >
                <ArrowLeft className="w-4 h-4" />
                <span>{t.previous}</span>
              </button>

              <button
                onClick={() => setQuickMode(!quickMode)}
                className="text-xs text-slate-400 hover:text-slate-600"
              >
                {quickMode ? t.fullMode : t.quickMode}
              </button>
            </div>
          </div>
        )}

        {/* Results State */}
        {!isAnalyzing && result && interpretation && (
          <div className="flex-1 p-6 sm:p-10 space-y-8 overflow-y-auto">
            <div className="bg-[#07111F] rounded-3xl p-8 text-white flex flex-col md:flex-row items-center justify-between gap-8 shadow-xl">
              <div className="space-y-3 text-center md:text-left">
                <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-white/10 text-xs text-[#4C7DFF] font-semibold">
                  <Sparkles className="w-3.5 h-3.5" />
                  <span>{t.badge}</span>
                </div>
                <h3 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
                  {meta[result.dominantChakra].archetype}
                </h3>
                <p className="text-slate-400 text-sm max-w-md">
                  {t.dominant}{' '}
                  <span className="text-white font-semibold capitalize">
                    {meta[result.dominantChakra].name} (
                    {result.normalizedScores[result.dominantChakra]}%)
                  </span>
                  {' '}• {t.secondary}{' '}
                  <span className="text-white font-semibold capitalize">
                    {meta[result.secondaryChakra].name} (
                    {result.normalizedScores[result.secondaryChakra]}%)
                  </span>
                </p>
              </div>

              <div className="w-28 h-28 rounded-full bg-slate-900 border-2 border-white/10 flex flex-col items-center justify-center shrink-0 shadow-inner">
                <span className="text-3xl font-extrabold text-white">
                  {result.overallEnergyScore}
                </span>
                <span className="text-[10px] text-slate-400 font-semibold tracking-wider uppercase">
                  {t.score}
                </span>
              </div>
            </div>

            <div className="p-6 rounded-3xl bg-slate-50 border border-slate-200/80 space-y-4">
              <h4 className="text-sm font-bold uppercase tracking-wider text-slate-500">
                {t.balance}
              </h4>
              <div className="space-y-3">
                {chakrasOrder.map((chKey) => {
                  const m = meta[chKey];
                  const score = result.normalizedScores[chKey];
                  return (
                    <div key={chKey} className="space-y-1">
                      <div className="flex justify-between items-center text-xs font-semibold text-slate-700">
                        <span className="flex items-center gap-2">
                          <span
                            className="w-2.5 h-2.5 rounded-full"
                            style={{ backgroundColor: m.color }}
                          />
                          {m.name} ({m.sanskrit})
                        </span>
                        <span className="font-mono">{score}%</span>
                      </div>
                      <div className="h-2 w-full bg-slate-200/80 rounded-full overflow-hidden">
                        <div
                          className="h-full rounded-full transition-all duration-700"
                          style={{
                            width: `${score}%`,
                            backgroundColor: m.color,
                          }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="p-6 rounded-3xl bg-white border border-slate-200 space-y-3">
                <h5 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-emerald-500" />
                  {t.strengths}
                </h5>
                <ul className="space-y-2 text-xs sm:text-sm text-slate-600">
                  {interpretation.strengths.map((str, idx) => (
                    <li key={idx} className="flex items-start gap-2">
                      <span className="text-[#4C7DFF] font-bold">•</span>
                      <span>{str}</span>
                    </li>
                  ))}
                </ul>
              </div>

              <div className="p-6 rounded-3xl bg-white border border-slate-200 space-y-3">
                <h5 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                  <Sparkles className="w-4 h-4 text-amber-500" />
                  {t.growth}
                </h5>
                <ul className="space-y-2 text-xs sm:text-sm text-slate-600">
                  {interpretation.growthAreas.map((gr, idx) => (
                    <li key={idx} className="flex items-start gap-2">
                      <span className="text-amber-500 font-bold">•</span>
                      <span>{gr}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 pt-4 border-t border-slate-200">
              <button
                onClick={resetAll}
                className="flex items-center gap-2 text-xs font-semibold text-slate-500 hover:text-slate-800"
              >
                <RotateCcw className="w-3.5 h-3.5" />
                <span>{t.retake}</span>
              </button>

              <div className="flex items-center gap-2">
                {onOpenChat && (
                  <button
                    onClick={() => {
                      onClose();
                      onOpenChat();
                    }}
                    className="px-5 py-2.5 rounded-full bg-[#4C7DFF] text-white text-xs font-bold hover:bg-blue-600 transition-colors flex items-center gap-1.5 shadow-md"
                  >
                    <MessageSquare className="w-3.5 h-3.5" />
                    <span>{all.consult}</span>
                  </button>
                )}
                <button
                  onClick={onClose}
                  className="px-6 py-2.5 rounded-full bg-[#07111F] text-white text-xs font-bold hover:bg-slate-800 transition-colors"
                >
                  {all.done}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
