'use client';

import React, { useState } from 'react';
import { X, Sparkles, CheckCircle2, RotateCcw, MessageSquare } from 'lucide-react';
import {
  calculateNumerology,
  getStaticNumerologyInterpretation,
} from '@/lib/numerology/calculator';
import {
  NumerologyCalculationResult,
  NumerologyInterpretation,
} from '@/lib/numerology/types';
import { numerologyTitle } from '@/lib/numerology/pythagorean';
import { useLocale, useMessages } from '@/i18n/client';

interface NumerologyAssessmentModalProps {
  isOpen: boolean;
  onClose: () => void;
  onOpenChat?: () => void;
  onComplete?: (result: NumerologyCalculationResult) => void;
  /** Pre-fills the form, e.g. with the signed-in user's name. */
  initial?: { name?: string; birthDate?: string };
}

export const NumerologyAssessmentModal: React.FC<NumerologyAssessmentModalProps> = ({
  isOpen,
  onClose,
  onOpenChat,
  onComplete,
  initial,
}) => {
  const locale = useLocale();
  const all = useMessages().assess;
  const t = all.numerology;
  const title = (n: number) => numerologyTitle(n, locale);
  const [fullName, setFullName] = useState(initial?.name ?? '');
  const [birthDate, setBirthDate] = useState(initial?.birthDate ?? '');

  const [result, setResult] = useState<NumerologyCalculationResult | null>(null);
  const [interpretation, setInterpretation] = useState<NumerologyInterpretation | null>(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);

  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsAnalyzing(true);
    try {
      const res = await fetch('/api/numerology/calculate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fullName, birthDate }),
      });
      const json = await res.json();
      if (json.success && json.data) {
        setResult(json.data);
        setInterpretation(json.data.interpretation);
        onComplete?.(json.data);
      } else {
        throw new Error('Fallback');
      }
    } catch {
      const calcResult = calculateNumerology(fullName, birthDate);
      const interp = getStaticNumerologyInterpretation(calcResult, locale);
      setResult(calcResult);
      setInterpretation(interp);
      onComplete?.(calcResult);
    } finally {
      setIsAnalyzing(false);
    }
  };

  const handleReset = () => {
    setResult(null);
    setInterpretation(null);
  };

  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 */}
        <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-amber-500" />
            <span className="text-xs font-bold uppercase tracking-wider text-slate-500">
              {t.header}
            </span>
          </div>

          <button
            onClick={onClose}
            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>

        {/* 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-amber-500/20 border-t-amber-500 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>
        )}

        {/* Input Form State */}
        {!isAnalyzing && !result && (
          <div className="flex-1 p-8 sm:p-12 max-w-xl mx-auto w-full flex flex-col justify-center">
            <div className="mb-8 text-center space-y-2">
              <span className="text-xs font-bold uppercase tracking-wider text-amber-600">
                {t.eyebrow}
              </span>
              <h3 className="text-2xl sm:text-3xl font-bold text-slate-900">
                {t.title}
              </h3>
              <p className="text-xs sm:text-sm text-slate-500">
                {t.text}
              </p>
            </div>

            <form onSubmit={handleSubmit} className="space-y-5">
              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-slate-600 mb-1.5">
                  {t.name}
                </label>
                <input
                  type="text"
                  required
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  placeholder={t.namePlaceholder}
                  className="w-full px-4 py-3 rounded-2xl border border-slate-200 text-sm focus:outline-none focus:border-amber-500 transition-colors"
                />
              </div>

              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-slate-600 mb-1.5">
                  {t.birthDate}
                </label>
                <input
                  type="date"
                  required
                  value={birthDate}
                  onChange={(e) => setBirthDate(e.target.value)}
                  className="w-full px-4 py-3 rounded-2xl border border-slate-200 text-sm focus:outline-none focus:border-amber-500 transition-colors"
                />
              </div>

              <button
                type="submit"
                className="w-full mt-4 py-3.5 rounded-full bg-[#07111F] text-white font-bold text-sm hover:bg-slate-800 transition-colors shadow-lg"
              >
                {t.submit}
              </button>
            </form>
          </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-2 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-[#D9B56D] 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">
                  {result.lifePath} — {title(result.lifePath)}
                </h3>
                <p className="text-slate-400 text-sm max-w-md">
                  {t.normalized}{' '}
                  <span className="text-white font-mono">{result.normalizedName}</span>
                </p>
              </div>

              <div className="w-28 h-28 rounded-full bg-gradient-to-tr from-[#D9B56D]/20 to-[#4C7DFF]/20 border-2 border-white/20 flex flex-col items-center justify-center shrink-0">
                <span className="text-5xl font-extrabold text-white">
                  {result.lifePath}
                </span>
                <span className="text-[9px] text-slate-300 uppercase tracking-widest mt-1">
                  Life Path
                </span>
              </div>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200 text-center">
                <span className="text-3xl font-extrabold text-blue-600 block">
                  {result.destiny}
                </span>
                <span className="text-xs font-bold text-slate-800 block mt-1">
                  Destiny
                </span>
                <span className="text-[11px] text-slate-500 block truncate">
                  {title(result.destiny)}
                </span>
              </div>

              <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200 text-center">
                <span className="text-3xl font-extrabold text-purple-600 block">
                  {result.soulUrge}
                </span>
                <span className="text-xs font-bold text-slate-800 block mt-1">
                  Soul Urge
                </span>
                <span className="text-[11px] text-slate-500 block truncate">
                  {title(result.soulUrge)}
                </span>
              </div>

              <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200 text-center">
                <span className="text-3xl font-extrabold text-amber-600 block">
                  {result.personality}
                </span>
                <span className="text-xs font-bold text-slate-800 block mt-1">
                  Personality
                </span>
                <span className="text-[11px] text-slate-500 block truncate">
                  {title(result.personality)}
                </span>
              </div>

              <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200 text-center">
                <span className="text-3xl font-extrabold text-emerald-600 block">
                  {result.maturity}
                </span>
                <span className="text-xs font-bold text-slate-800 block mt-1">
                  Maturity
                </span>
                <span className="text-[11px] text-slate-500 block truncate">
                  {title(result.maturity)}
                </span>
              </div>
            </div>

            <div className="p-6 rounded-3xl bg-white border border-slate-200 space-y-4">
              <h4 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-amber-500" />
                {t.meaning}
              </h4>
              <p className="text-sm text-slate-600 leading-relaxed">
                {interpretation.lifePathMeaning}
              </p>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                  <span className="text-xs font-bold uppercase text-slate-500 block mb-1">
                    {t.keyStrengths}
                  </span>
                  <ul className="text-xs text-slate-600 space-y-1">
                    {interpretation.strengths.map((str, idx) => (
                      <li key={idx}>• {str}</li>
                    ))}
                  </ul>
                </div>

                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                  <span className="text-xs font-bold uppercase text-slate-500 block mb-1">
                    {t.career}
                  </span>
                  <p className="text-xs text-slate-600">{interpretation.careerAlignment}</p>
                </div>
              </div>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 pt-4 border-t border-slate-200">
              <button
                onClick={handleReset}
                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>{all.recalc}</span>
              </button>

              <div className="flex items-center gap-2">
                {onOpenChat && (
                  <button
                    onClick={() => {
                      onClose();
                      onOpenChat();
                    }}
                    className="px-5 py-2.5 rounded-full bg-amber-600 text-white text-xs font-bold hover:bg-amber-700 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>
  );
};
