import { useState } from 'react';
import { motion } from 'framer-motion';

interface LicenseResponse {
  key: string;
  plan: string;
  instructions: string[];
}

type Step = 'email' | 'code' | 'done';

function Recover() {
  const [step, setStep] = useState<Step>('email');
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [license, setLicense] = useState<LicenseResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleRequestCode = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/license/recover-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || `Error ${res.status}`);
      setStep('code');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch('/api/license/recover', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || `Error ${res.status}`);
      setLicense(data);
      setStep('done');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const copyKey = () => {
    if (license?.key) {
      navigator.clipboard.writeText(license.key);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <div className="min-h-screen bg-slate-950 flex items-center justify-center px-4 py-16">
      <motion.div
        initial={{ opacity: 0, y: 30 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6, ease: 'easeOut' }}
        className="max-w-xl w-full"
      >
        {/* Step 1 — Email */}
        {step === 'email' && (
          <div className="bg-slate-800/50 border border-slate-700/50 rounded-2xl p-8">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-white">Recover your license key</h2>
              <p className="text-slate-400 mt-2 text-sm">
                Enter your checkout email and we'll send a verification code.
              </p>
            </div>
            <form onSubmit={handleRequestCode} className="space-y-4">
              <div>
                <label className="text-slate-400 text-xs uppercase tracking-wider mb-2 block">
                  Checkout email
                </label>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="you@example.com"
                  className="w-full bg-slate-900 border border-slate-700/50 rounded-lg px-4 py-3 text-white placeholder-slate-500 focus:outline-none focus:border-sky-400/60 transition-colors"
                />
              </div>
              {error && <p className="text-red-400 text-sm">{error}</p>}
              <button
                type="submit"
                disabled={loading}
                className="w-full bg-sky-500 hover:bg-sky-400 disabled:bg-sky-500/40 disabled:cursor-not-allowed text-white font-semibold py-3 rounded-lg transition-colors"
              >
                {loading ? 'Sending...' : 'Send verification code'}
              </button>
            </form>
            <p className="text-slate-500 text-xs text-center mt-6">
              Can't find it? Email us at hello@pulseos.dev
            </p>
          </div>
        )}

        {/* Step 2 — Code */}
        {step === 'code' && (
          <div className="bg-slate-800/50 border border-slate-700/50 rounded-2xl p-8">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-white">Check your inbox</h2>
              <p className="text-slate-400 mt-2 text-sm">
                We sent a 6-digit code to <span className="text-sky-400">{email}</span>.
                <br />It expires in 5 minutes.
              </p>
            </div>
            <form onSubmit={handleVerifyCode} className="space-y-4">
              <div>
                <label className="text-slate-400 text-xs uppercase tracking-wider mb-2 block">
                  Verification code
                </label>
                <input
                  type="text"
                  required
                  maxLength={6}
                  value={code}
                  onChange={e => setCode(e.target.value.replace(/[^a-fA-F0-9]/g, '').toUpperCase())}
                  placeholder="A1B2C3"
                  className="w-full bg-slate-900 border border-slate-700/50 rounded-lg px-4 py-3 text-white placeholder-slate-500 focus:outline-none focus:border-sky-400/60 transition-colors text-center font-mono text-xl tracking-widest"
                />
              </div>
              {error && (
                <div>
                  <p className="text-red-400 text-sm">{error}</p>
                  <button
                    type="button"
                    onClick={() => { setStep('email'); setCode(''); setError(null); }}
                    className="text-sky-400 text-sm hover:underline mt-1"
                  >
                    Send a new code
                  </button>
                </div>
              )}
              <button
                type="submit"
                disabled={loading || code.length !== 6}
                className="w-full bg-sky-500 hover:bg-sky-400 disabled:bg-sky-500/40 disabled:cursor-not-allowed text-white font-semibold py-3 rounded-lg transition-colors"
              >
                {loading ? 'Verifying...' : 'Recover key'}
              </button>
            </form>
            <button
              onClick={() => { setStep('email'); setCode(''); setError(null); }}
              className="w-full text-slate-500 hover:text-slate-400 text-xs text-center mt-4 transition-colors"
            >
              ← Use a different email
            </button>
          </div>
        )}

        {/* Step 3 — Key */}
        {step === 'done' && license && (
          <div className="bg-slate-800/50 border border-sky-400/30 rounded-2xl p-8 shadow-lg shadow-sky-500/10">
            <div className="text-center mb-6">
              <div className="text-4xl mb-3">&#10003;</div>
              <h2 className="text-2xl font-bold text-white">Here's your key</h2>
              <p className="text-slate-400 mt-1">{license.plan.toUpperCase()} plan</p>
            </div>
            <div className="mb-6">
              <label className="text-slate-400 text-xs uppercase tracking-wider mb-2 block">
                Your License Key
              </label>
              <div
                onClick={copyKey}
                className="bg-slate-900 rounded-lg p-4 border border-slate-700/50 cursor-pointer hover:border-sky-400/50 transition-colors flex items-center justify-between group"
              >
                <code className="text-sky-400 font-mono text-sm break-all">{license.key}</code>
                <span className="text-slate-500 group-hover:text-sky-400 ml-3 flex-shrink-0 text-sm">
                  {copied ? 'Copied!' : 'Copy'}
                </span>
              </div>
            </div>
            <div className="space-y-3">
              <label className="text-slate-400 text-xs uppercase tracking-wider mb-2 block">
                Activate
              </label>
              {license.instructions.map((step, i) => (
                <div key={i} className="flex items-start gap-3">
                  <span className="bg-sky-500/10 text-sky-400 text-xs font-bold w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                    {i + 1}
                  </span>
                  <code className="text-slate-300 font-mono text-sm bg-slate-900 rounded px-3 py-2 flex-1 border border-slate-700/50">
                    {step}
                  </code>
                </div>
              ))}
            </div>
            <p className="text-slate-500 text-xs text-center mt-6">
              Key works on all your machines. Questions? hello@pulseos.dev
            </p>
          </div>
        )}
      </motion.div>
    </div>
  );
}

export default Recover;
