import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession, signIn } from 'next-auth/react';
import { Check, Crown, Zap, Star, Sparkles } from 'lucide-react';

interface Plan {
  id: string;
  name: string;
  slug: string;
  price: number;
  features: { features: string[] };
  queryLimit: number | null;
  stripePriceId: string | null;
}

export default function SignUpPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [providers, setProviders] = useState<any>(null);
  const [plans, setPlans] = useState<Plan[]>([]);
  const [selectedPlan, setSelectedPlan] = useState<string>('free');
  const [step, setStep] = useState<'plan' | 'account'>('plan');

  // Get plan from URL query
  useEffect(() => {
    if (router.query.plan && typeof router.query.plan === 'string') {
      setSelectedPlan(router.query.plan);
      setStep('account');
    }
  }, [router.query.plan]);

  useEffect(() => {
    if (status === 'authenticated') {
      // If user selected a paid plan, redirect to checkout
      if (selectedPlan && selectedPlan !== 'free') {
        handleCheckout();
      } else {
        router.replace('/');
      }
    }
  }, [status]);

  useEffect(() => {
    async function fetchProviders() {
      try {
        const r = await fetch('/api/auth/providers');
        if (r.ok) setProviders(await r.json());
      } catch {}
    }
    fetchProviders();
  }, []);

  // Load plans
  useEffect(() => {
    async function loadPlans() {
      try {
        const r = await fetch('/api/subscription/plans');
        if (r.ok) {
          const data = await r.json();
          setPlans(data.plans || []);
        }
      } catch {}
    }
    loadPlans();
  }, []);

  async function handleCheckout() {
    if (selectedPlan === 'free') return;
    
    try {
      const plan = plans.find(p => p.slug === selectedPlan);
      const response = await fetch('/api/subscription/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          planSlug: selectedPlan,
          priceId: plan?.stripePriceId
        })
      });

      const data = await response.json();
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err) {
      console.error('Checkout error:', err);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const r = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username || null, email, password }),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || 'Sign up failed');
      
      // Auto sign-in after signup
      const idOrEmail = email || username;
      if (idOrEmail) {
        const signInResult = await signIn('credentials', { redirect: false, username: idOrEmail, password });
        
        if (signInResult?.ok) {
          // If paid plan selected, redirect to checkout
          if (selectedPlan && selectedPlan !== 'free') {
            // Small delay to ensure session is ready
            setTimeout(() => handleCheckout(), 500);
          } else {
            router.push('/');
          }
        } else {
          router.push('/');
        }
      } else {
        router.push('/');
      }
    } catch (err: any) {
      setError(err?.message || 'Sign up failed');
    } finally {
      setLoading(false);
    }
  }

  async function handleGoogle() {
    // Store selected plan in localStorage for after OAuth redirect
    if (selectedPlan && selectedPlan !== 'free') {
      localStorage.setItem('pendingPlan', selectedPlan);
    }
    await signIn('google');
  }

  function getPlanIcon(slug: string) {
    switch (slug) {
      case 'silver': return <Zap size={20} />;
      case 'gold': return <Crown size={20} />;
      case 'premium': return <Sparkles size={20} />;
      default: return <Star size={20} />;
    }
  }

  function getPlanColor(slug: string) {
    switch (slug) {
      case 'silver': return { bg: '#f3f4f6', border: '#9ca3af', accent: '#6b7280' };
      case 'gold': return { bg: '#fef3c7', border: '#f59e0b', accent: '#d97706' };
      case 'premium': return { bg: '#ede9fe', border: '#8b5cf6', accent: '#7c3aed' };
      default: return { bg: '#f0fdf4', border: '#22c55e', accent: '#16a34a' };
    }
  }

  return (
    <>
      <Head>
        <title>Sign up - Gregory AI</title>
      </Head>
      <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(180deg,#f8fafc,#f1f5f9)', padding: '40px 20px' }}>
        <div style={{ width: '100%', maxWidth: step === 'plan' ? 900 : 480 }}>
          {/* Header */}
          <div style={{ textAlign: 'center', marginBottom: 24 }}>
            <a href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
              <img src="/logo.png" alt="Gregory AI" width={40} height={40} style={{ borderRadius: 12 }} />
              <span style={{ fontSize: 22, fontWeight: 700, color: '#111827' }}>Gregory AI</span>
            </a>
          </div>

          {step === 'plan' ? (
            /* Step 1: Plan Selection */
            <div>
              <h1 style={{ textAlign: 'center', fontSize: 28, fontWeight: 700, color: '#111827', marginBottom: 8 }}>
                Choose your plan
              </h1>
              <p style={{ textAlign: 'center', color: '#6b7280', marginBottom: 32 }}>
                Start free or unlock more with a premium plan
              </p>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16, marginBottom: 24 }}>
                {plans.map((plan) => {
                  const colors = getPlanColor(plan.slug);
                  const isSelected = selectedPlan === plan.slug;
                  const isPopular = plan.slug === 'gold';

                  return (
                    <div
                      key={plan.slug}
                      onClick={() => setSelectedPlan(plan.slug)}
                      style={{
                        background: '#fff',
                        borderRadius: 16,
                        border: isSelected ? '2px solid #3b82f6' : '1px solid #e5e7eb',
                        padding: 20,
                        cursor: 'pointer',
                        position: 'relative',
                        transition: 'all 0.2s',
                        boxShadow: isSelected ? '0 8px 20px rgba(59, 130, 246, 0.15)' : '0 2px 8px rgba(0,0,0,0.05)'
                      }}
                    >
                      {isPopular && (
                        <div style={{
                          position: 'absolute',
                          top: -10,
                          left: '50%',
                          transform: 'translateX(-50%)',
                          background: colors.accent,
                          color: '#fff',
                          padding: '4px 12px',
                          borderRadius: 12,
                          fontSize: 11,
                          fontWeight: 600
                        }}>
                          Popular
                        </div>
                      )}

                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                        <div style={{
                          width: 36,
                          height: 36,
                          borderRadius: 10,
                          background: colors.bg,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          color: colors.accent
                        }}>
                          {getPlanIcon(plan.slug)}
                        </div>
                        <div>
                          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: '#111827' }}>{plan.name}</h3>
                          <p style={{ margin: 0, fontSize: 12, color: '#6b7280' }}>
                            {plan.queryLimit === null ? 'Unlimited' : `${plan.queryLimit} queries/day`}
                          </p>
                        </div>
                      </div>

                      <div style={{ marginBottom: 12 }}>
                        <span style={{ fontSize: 28, fontWeight: 700, color: '#111827' }}>${plan.price}</span>
                        {plan.price > 0 && <span style={{ fontSize: 14, color: '#6b7280' }}>/mo</span>}
                      </div>

                      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                        {plan.features?.features?.slice(0, 3).map((feature, idx) => (
                          <li key={idx} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, fontSize: 13, color: '#4b5563' }}>
                            <Check size={14} style={{ color: '#22c55e' }} />
                            {feature}
                          </li>
                        ))}
                      </ul>

                      {isSelected && (
                        <div style={{
                          position: 'absolute',
                          top: 12,
                          right: 12,
                          width: 24,
                          height: 24,
                          borderRadius: '50%',
                          background: '#3b82f6',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}>
                          <Check size={14} style={{ color: '#fff' }} />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              <div style={{ textAlign: 'center' }}>
                <button
                  onClick={() => setStep('account')}
                  style={{
                    padding: '14px 48px',
                    background: '#111827',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 12,
                    fontSize: 16,
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  Continue with {plans.find(p => p.slug === selectedPlan)?.name || 'Free'}
                </button>
                <p style={{ marginTop: 16, color: '#6b7280', fontSize: 14 }}>
                  Already have an account? <a href="/auth/signin" style={{ color: '#3b82f6', textDecoration: 'none' }}>Sign in</a>
                </p>
              </div>
            </div>
          ) : (
            /* Step 2: Account Creation */
            <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:16, padding:24, boxShadow:'0 12px 30px rgba(2,6,23,0.08)' }}>
              {/* Selected Plan Badge */}
              {selectedPlan !== 'free' && (
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '12px 16px',
                  background: getPlanColor(selectedPlan).bg,
                  borderRadius: 10,
                  marginBottom: 20
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ color: getPlanColor(selectedPlan).accent }}>
                      {getPlanIcon(selectedPlan)}
                    </div>
                    <span style={{ fontWeight: 600, color: '#111827' }}>
                      {plans.find(p => p.slug === selectedPlan)?.name}
                    </span>
                  </div>
                  <button
                    onClick={() => setStep('plan')}
                    style={{
                      background: 'transparent',
                      border: 'none',
                      color: '#3b82f6',
                      fontSize: 14,
                      cursor: 'pointer'
                    }}
                  >
                    Change
                  </button>
                </div>
              )}

              <h1 style={{ margin: '0 0 8px', fontSize: 22, fontWeight: 600 }}>Create your account</h1>
              <p style={{ marginTop: 0, color: '#6b7280', fontSize: 14, marginBottom: 20 }}>
                {selectedPlan === 'free' 
                  ? 'Enjoy 5 free queries per day. Upgrade anytime for more.'
                  : 'Create your account, then complete payment to activate your plan.'}
              </p>

              <form onSubmit={handleSubmit}>
                <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                  <input 
                    value={username} 
                    onChange={e=>setUsername(e.target.value)} 
                    placeholder="Username (optional)" 
                    style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb', fontSize: 15 }} 
                  />
                  <input 
                    value={email} 
                    onChange={e=>setEmail(e.target.value)} 
                    placeholder="Email" 
                    type="email" 
                    required 
                    style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb', fontSize: 15 }} 
                  />
                  <input 
                    value={password} 
                    onChange={e=>setPassword(e.target.value)} 
                    placeholder="Password (min 6 characters)" 
                    type="password" 
                    required
                    minLength={6}
                    style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb', fontSize: 15 }} 
                  />
                  {error && <div style={{ color:'#ef4444', fontSize:13, padding: '8px 12px', background: '#fef2f2', borderRadius: 8 }}>{error}</div>}
                  <button 
                    type="submit" 
                    disabled={loading} 
                    style={{ 
                      padding:'14px', 
                      borderRadius:10, 
                      border:'none', 
                      background: selectedPlan === 'free' ? '#10b981' : '#3b82f6', 
                      color:'#fff', 
                      cursor:'pointer',
                      fontSize: 16,
                      fontWeight: 600,
                      opacity: loading ? 0.7 : 1
                    }}
                  >
                    {loading 
                      ? 'Creating account...' 
                      : selectedPlan === 'free' 
                        ? 'Create Free Account' 
                        : 'Create Account & Continue to Payment'}
                  </button>
                  
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '8px 0' }}>
                    <div style={{ flex: 1, height: 1, background: '#e5e7eb' }} />
                    <span style={{ color: '#9ca3af', fontSize: 13 }}>or</span>
                    <div style={{ flex: 1, height: 1, background: '#e5e7eb' }} />
                  </div>

                  {providers?.google && (
                    <button 
                      type="button" 
                      onClick={handleGoogle} 
                      style={{ 
                        padding:'14px', 
                        borderRadius:10, 
                        border:'1px solid #e5e7eb', 
                        background:'#fff', 
                        cursor:'pointer',
                        fontSize: 15,
                        fontWeight: 500,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: 10
                      }}
                    >
                      <svg width="18" height="18" viewBox="0 0 24 24">
                        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                      </svg>
                      Continue with Google
                    </button>
                  )}
                </div>
              </form>

              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <button
                  onClick={() => setStep('plan')}
                  style={{
                    background: 'transparent',
                    border: 'none',
                    color: '#6b7280',
                    fontSize: 14,
                    cursor: 'pointer',
                    marginRight: 16
                  }}
                >
                  ← Back to plans
                </button>
                <span style={{ color:'#6b7280', fontSize:14 }}>
                  Already have an account? <a href="/auth/signin" style={{ color:'#3b82f6', textDecoration:'none' }}>Sign in</a>
                </span>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
