import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';
import { Check, Crown, Zap, Star, Sparkles } from 'lucide-react';

interface Plan {
  id: string;
  name: string;
  slug: string;
  price: number;
  priceCents: number;
  currency: string;
  billingInterval: string;
  features: { features: string[] };
  queryLimit: number | null;
  stripeProductId: string;
  stripePriceId: string | null;
}

interface SubscriptionStatus {
  plan: string;
  planName: string;
  status: string | null;
  queryLimit: number;
  isSubscribed: boolean;
  currentPeriodEnd?: string;
  cancelAtPeriodEnd?: boolean;
}

export default function PricingPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [plans, setPlans] = useState<Plan[]>([]);
  const [currentSubscription, setCurrentSubscription] = useState<SubscriptionStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [checkoutLoading, setCheckoutLoading] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const isAuthed = status === 'authenticated' && !!session?.user;

  // Check for success/cancel from Stripe redirect
  useEffect(() => {
    async function verifyPayment() {
      if (router.query.success === 'true' && router.query.session_id) {
        try {
          // Verify the session and update subscription in database
          const response = await fetch('/api/subscription/verify-session', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ sessionId: router.query.session_id })
          });
          
          const data = await response.json();
          
          if (response.ok) {
            setSuccessMessage(`Payment successful! Your ${data.plan || ''} subscription is now active.`);
            // Reload subscription status after a short delay to ensure DB is updated
            setTimeout(async () => {
              const statusRes = await fetch('/api/subscription/status');
              if (statusRes.ok) {
                setCurrentSubscription(await statusRes.json());
              }
            }, 500);
            // Auto-redirect to chat after 5 seconds
            setTimeout(() => {
              router.push('/');
            }, 5000);
          } else {
            setErrorMessage(data.error || 'Failed to verify payment');
          }
        } catch (err) {
          console.error('Verify error:', err);
          setSuccessMessage('Payment successful! Your subscription is now active.');
          // Auto-redirect to chat after 5 seconds
          setTimeout(() => {
            router.push('/');
          }, 5000);
        }
        // Clear the query params
        router.replace('/pricing', undefined, { shallow: true });
      } else if (router.query.canceled === 'true') {
        setErrorMessage('Payment was canceled. You can try again anytime.');
        router.replace('/pricing', undefined, { shallow: true });
      }
    }
    
    verifyPayment();
  }, [router.query]);

  // Load plans and subscription status
  useEffect(() => {
    async function loadData() {
      try {
        const [plansRes, statusRes] = await Promise.all([
          fetch('/api/subscription/plans'),
          isAuthed ? fetch('/api/subscription/status') : Promise.resolve(null)
        ]);

        const plansData = await plansRes.json();
        setPlans(plansData.plans || []);

        if (statusRes) {
          const statusData = await statusRes.json();
          setCurrentSubscription(statusData);
        }
      } catch (error) {
        console.error('Error loading pricing data:', error);
      } finally {
        setLoading(false);
      }
    }

    loadData();
  }, [isAuthed]);

  async function handleSubscribe(plan: Plan) {
    if (!isAuthed) {
      // Redirect to signup with plan selection
      router.push(`/auth/signup?plan=${plan.slug}`);
      return;
    }

    if (plan.slug === 'free') {
      return; // Can't subscribe to free
    }

    setCheckoutLoading(plan.slug);
    setErrorMessage(null);

    try {
      const response = await fetch('/api/subscription/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          planSlug: plan.slug,
          priceId: plan.stripePriceId
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to create checkout session');
      }

      // Redirect to Stripe Checkout
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (error: any) {
      setErrorMessage(error.message || 'Failed to start checkout');
    } finally {
      setCheckoutLoading(null);
    }
  }

  async function handleManageSubscription() {
    setCheckoutLoading('manage');
    setErrorMessage(null);

    try {
      const response = await fetch('/api/subscription/portal', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to open billing portal');
      }

      if (data.url) {
        window.location.href = data.url;
      }
    } catch (error: any) {
      setErrorMessage(error.message || 'Failed to open billing portal');
    } finally {
      setCheckoutLoading(null);
    }
  }

  function getPlanIcon(slug: string) {
    switch (slug) {
      case 'silver': return <Zap size={24} />;
      case 'gold': return <Crown size={24} />;
      case 'premium': return <Sparkles size={24} />;
      default: return <Star size={24} />;
    }
  }

  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' };
    }
  }

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(180deg, #f8fafc, #f1f5f9)' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 40, height: 40, border: '3px solid #e5e7eb', borderTopColor: '#3b82f6', borderRadius: '50%', animation: 'spin 1s linear infinite', margin: '0 auto 16px' }} />
          <p style={{ color: '#6b7280' }}>Loading plans...</p>
        </div>
        <style jsx>{`
          @keyframes spin {
            to { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  return (
    <>
      <Head>
        <title>Pricing - Gregory AI</title>
        <meta name="description" content="Choose the perfect plan for your needs" />
      </Head>

      <div style={{ minHeight: '100vh', background: 'linear-gradient(180deg, #f8fafc, #f1f5f9)', padding: '40px 20px' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
          {/* Header */}
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <a href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 12, textDecoration: 'none', marginBottom: 24 }}>
              <img src="/logo.png" alt="Gregory AI" width={48} height={48} style={{ borderRadius: 12 }} />
              <span style={{ fontSize: 24, fontWeight: 700, color: '#111827' }}>Gregory AI</span>
            </a>
            <h1 style={{ fontSize: 36, fontWeight: 700, color: '#111827', marginBottom: 12 }}>
              Choose Your Plan
            </h1>
            <p style={{ fontSize: 18, color: '#6b7280', maxWidth: 600, margin: '0 auto' }}>
              Unlock the full potential of Gregory AI with our flexible pricing plans
            </p>
          </div>

          {/* Success Message with redirect */}
          {successMessage && (
            <div style={{ maxWidth: 600, margin: '0 auto 24px', padding: '20px 24px', background: '#dcfce7', border: '1px solid #22c55e', borderRadius: 16, color: '#166534', textAlign: 'center' }}>
              <p style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>{successMessage}</p>
              <p style={{ margin: '8px 0 16px', fontSize: 14 }}>Redirecting to chat in a few seconds...</p>
              <button
                onClick={() => router.push('/')}
                style={{
                  padding: '12px 32px',
                  background: '#16a34a',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 10,
                  fontSize: 14,
                  fontWeight: 600,
                  cursor: 'pointer'
                }}
              >
                Go to Chat Now →
              </button>
            </div>
          )}
          {errorMessage && (
            <div style={{ maxWidth: 600, margin: '0 auto 24px', padding: '16px 20px', background: '#fef2f2', border: '1px solid #ef4444', borderRadius: 12, color: '#991b1b', textAlign: 'center' }}>
              {errorMessage}
            </div>
          )}

          {/* Current Subscription Banner */}
          {currentSubscription?.isSubscribed && (
            <div style={{ maxWidth: 600, margin: '0 auto 32px', padding: '20px 24px', background: '#fff', border: '2px solid #3b82f6', borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
              <div>
                <p style={{ margin: 0, fontSize: 14, color: '#6b7280' }}>Current Plan</p>
                <p style={{ margin: '4px 0 0', fontSize: 20, fontWeight: 600, color: '#111827' }}>{currentSubscription.planName}</p>
                {currentSubscription.currentPeriodEnd && (
                  <p style={{ margin: '4px 0 0', fontSize: 12, color: currentSubscription.cancelAtPeriodEnd ? '#ef4444' : '#6b7280' }}>
                    {currentSubscription.cancelAtPeriodEnd 
                      ? `Expires on ${new Date(currentSubscription.currentPeriodEnd).toLocaleDateString()}`
                      : `Renews on ${new Date(currentSubscription.currentPeriodEnd).toLocaleDateString()}`
                    }
                  </p>
                )}
              </div>
              <button
                onClick={handleManageSubscription}
                disabled={checkoutLoading === 'manage'}
                style={{
                  padding: '12px 24px',
                  background: '#3b82f6',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 10,
                  fontSize: 14,
                  fontWeight: 500,
                  cursor: 'pointer',
                  opacity: checkoutLoading === 'manage' ? 0.7 : 1
                }}
              >
                {checkoutLoading === 'manage' ? 'Loading...' : 'Manage Subscription'}
              </button>
            </div>
          )}

          {/* Plans Grid */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 24, maxWidth: 1200, margin: '0 auto' }}>
            {plans.map((plan) => {
              const colors = getPlanColor(plan.slug);
              const isCurrentPlan = currentSubscription?.plan === plan.slug;
              const isPopular = plan.slug === 'gold';

              return (
                <div
                  key={plan.slug}
                  style={{
                    background: '#fff',
                    borderRadius: 20,
                    border: isCurrentPlan ? '2px solid #3b82f6' : isPopular ? `2px solid ${colors.border}` : '1px solid #e5e7eb',
                    padding: 32,
                    position: 'relative',
                    boxShadow: isPopular ? '0 20px 40px rgba(0,0,0,0.1)' : '0 4px 12px rgba(0,0,0,0.05)',
                    transform: isPopular ? 'scale(1.02)' : 'none'
                  }}
                >
                  {/* Popular Badge */}
                  {isPopular && (
                    <div style={{
                      position: 'absolute',
                      top: -12,
                      left: '50%',
                      transform: 'translateX(-50%)',
                      background: colors.accent,
                      color: '#fff',
                      padding: '6px 16px',
                      borderRadius: 20,
                      fontSize: 12,
                      fontWeight: 600
                    }}>
                      Most Popular
                    </div>
                  )}

                  {/* Current Plan Badge */}
                  {isCurrentPlan && (
                    <div style={{
                      position: 'absolute',
                      top: -12,
                      right: 16,
                      background: '#3b82f6',
                      color: '#fff',
                      padding: '6px 12px',
                      borderRadius: 20,
                      fontSize: 12,
                      fontWeight: 600
                    }}>
                      Current
                    </div>
                  )}

                  {/* Plan Icon & Name */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                    <div style={{
                      width: 48,
                      height: 48,
                      borderRadius: 12,
                      background: colors.bg,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: colors.accent
                    }}>
                      {getPlanIcon(plan.slug)}
                    </div>
                    <h3 style={{ margin: 0, fontSize: 20, fontWeight: 600, color: '#111827' }}>
                      {plan.name}
                    </h3>
                  </div>

                  {/* Price */}
                  <div style={{ marginBottom: 24 }}>
                    <span style={{ fontSize: 40, fontWeight: 700, color: '#111827' }}>
                      ${plan.price}
                    </span>
                    {plan.price > 0 && (
                      <span style={{ fontSize: 16, color: '#6b7280' }}>/month</span>
                    )}
                    {plan.price === 0 && (
                      <span style={{ fontSize: 16, color: '#6b7280', marginLeft: 8 }}>Forever free</span>
                    )}
                  </div>

                  {/* Query Limit */}
                  <div style={{
                    padding: '12px 16px',
                    background: colors.bg,
                    borderRadius: 10,
                    marginBottom: 24,
                    textAlign: 'center'
                  }}>
                    <span style={{ fontSize: 14, fontWeight: 600, color: colors.accent }}>
                      {plan.queryLimit === null ? 'Unlimited queries' : `${plan.queryLimit} queries/day`}
                    </span>
                  </div>

                  {/* Features */}
                  <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 24px', minHeight: 180 }}>
                    {plan.features?.features?.map((feature, idx) => (
                      <li key={idx} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 12 }}>
                        <Check size={18} style={{ color: '#22c55e', flexShrink: 0, marginTop: 2 }} />
                        <span style={{ fontSize: 14, color: '#4b5563' }}>{feature}</span>
                      </li>
                    ))}
                  </ul>

                  {/* CTA Button */}
                  {plan.slug === 'free' ? (
                    <button
                      disabled
                      style={{
                        width: '100%',
                        padding: '14px 24px',
                        background: isCurrentPlan ? '#e5e7eb' : '#f3f4f6',
                        color: '#6b7280',
                        border: 'none',
                        borderRadius: 12,
                        fontSize: 16,
                        fontWeight: 600,
                        cursor: 'not-allowed'
                      }}
                    >
                      {isCurrentPlan ? 'Current Plan' : 'Free Forever'}
                    </button>
                  ) : isCurrentPlan ? (
                    <button
                      onClick={handleManageSubscription}
                      disabled={checkoutLoading === 'manage'}
                      style={{
                        width: '100%',
                        padding: '14px 24px',
                        background: '#3b82f6',
                        color: '#fff',
                        border: 'none',
                        borderRadius: 12,
                        fontSize: 16,
                        fontWeight: 600,
                        cursor: 'pointer',
                        opacity: checkoutLoading === 'manage' ? 0.7 : 1
                      }}
                    >
                      {checkoutLoading === 'manage' ? 'Loading...' : 'Manage Plan'}
                    </button>
                  ) : (
                    <button
                      onClick={() => handleSubscribe(plan)}
                      disabled={checkoutLoading === plan.slug}
                      style={{
                        width: '100%',
                        padding: '14px 24px',
                        background: isPopular ? colors.accent : '#111827',
                        color: '#fff',
                        border: 'none',
                        borderRadius: 12,
                        fontSize: 16,
                        fontWeight: 600,
                        cursor: 'pointer',
                        opacity: checkoutLoading === plan.slug ? 0.7 : 1,
                        transition: 'transform 0.2s, box-shadow 0.2s'
                      }}
                      onMouseOver={(e) => {
                        e.currentTarget.style.transform = 'translateY(-2px)';
                        e.currentTarget.style.boxShadow = '0 8px 20px rgba(0,0,0,0.15)';
                      }}
                      onMouseOut={(e) => {
                        e.currentTarget.style.transform = 'none';
                        e.currentTarget.style.boxShadow = 'none';
                      }}
                    >
                      {checkoutLoading === plan.slug ? 'Loading...' : (
                        currentSubscription?.isSubscribed ? 'Upgrade' : 'Get Started'
                      )}
                    </button>
                  )}
                </div>
              );
            })}
          </div>

          {/* FAQ Section */}
          <div style={{ maxWidth: 800, margin: '64px auto 0', textAlign: 'center' }}>
            <h2 style={{ fontSize: 28, fontWeight: 700, color: '#111827', marginBottom: 32 }}>
              Frequently Asked Questions
            </h2>
            <div style={{ textAlign: 'left' }}>
              {[
                {
                  q: 'Can I cancel my subscription anytime?',
                  a: 'Yes! You can cancel your subscription at any time. Your access will continue until the end of your billing period.'
                },
                {
                  q: 'What payment methods do you accept?',
                  a: 'We accept all major credit cards including Visa, Mastercard, and American Express through our secure Stripe payment processing.'
                },
                {
                  q: 'Can I upgrade or downgrade my plan?',
                  a: 'Absolutely! You can change your plan at any time. When upgrading, you\'ll be charged the prorated difference. When downgrading, the change takes effect at your next billing cycle.'
                },
                {
                  q: 'Is there a free trial?',
                  a: 'Our Free plan lets you try Gregory AI with 5 queries per day. No credit card required!'
                }
              ].map((faq, idx) => (
                <div key={idx} style={{ marginBottom: 24, padding: '20px 24px', background: '#fff', borderRadius: 12, border: '1px solid #e5e7eb' }}>
                  <h4 style={{ margin: '0 0 8px', fontSize: 16, fontWeight: 600, color: '#111827' }}>{faq.q}</h4>
                  <p style={{ margin: 0, fontSize: 14, color: '#6b7280', lineHeight: 1.6 }}>{faq.a}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Back to Home */}
          <div style={{ textAlign: 'center', marginTop: 48 }}>
            <a href="/" style={{ color: '#3b82f6', textDecoration: 'none', fontSize: 14, fontWeight: 500 }}>
              ← Back to Gregory AI
            </a>
          </div>
        </div>
      </div>
    </>
  );
}
