import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useSearchParams, Link } from 'react-router-dom';

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

function Success() {
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get('session_id');
  const [license, setLicense] = useState<LicenseResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (!sessionId) {
      setError('No session ID found. Please complete checkout first.');
      setLoading(false);
      return;
    }

    fetch('/api/license/generate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ session_id: sessionId }),
    })
      .then(async res => {
        if (!res.ok) {
          const body = await res.json().catch(() => ({}));
          throw new Error(body.error || `Server returned ${res.status}`);
        }
        return res.json();
      })
      .then((data: LicenseResponse) => {
        setLicense(data);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message || 'Could not reach the license server.');
        setLoading(false);
      });
  }, [sessionId]);

  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"
      >
        {loading && (
          <div className="text-center">
            <div className="text-sky-400 text-xl font-semibold mb-2">Generating your license...</div>
            <div className="text-slate-400">Talking to Stripe...</div>
          </div>
        )}

        {error && (
          <div className="bg-slate-800/50 border border-slate-700/50 rounded-2xl p-8">
            <h2 className="text-2xl font-bold text-white mb-4">Almost there!</h2>
            <p className="text-slate-300 mb-6">{error}</p>
            <Link
              to="/recover"
              className="block w-full text-center bg-sky-500 hover:bg-sky-400 text-white font-semibold py-3 rounded-lg transition-colors mb-4"
            >
              Recover your license key
            </Link>
            <p className="text-slate-500 text-xs text-center">
              Or email us at hello@pulseos.dev
            </p>
          </div>
        )}

        {license && (
          <div className="bg-slate-800/50 border border-sky-400/30 rounded-2xl p-8 shadow-lg shadow-sky-500/10">
            {/* Header */}
            <div className="text-center mb-6">
              <div className="text-4xl mb-3">&#10003;</div>
              <h2 className="text-2xl font-bold text-white">You're in!</h2>
              <p className="text-slate-400 mt-1">
                {license.plan.toUpperCase()} plan activated with 7-day free trial
              </p>
            </div>

            {/* License Key */}
            <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>

            {/* Install Steps */}
            <div className="space-y-3">
              <label className="text-slate-400 text-xs uppercase tracking-wider mb-2 block">
                Get Started
              </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>

            {/* Footer */}
            <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 Success;
