import { useState, useEffect } from 'react';
import axios from 'axios';
import type { SubscriptionPlan } from '@/types/api';

interface PricingWidgetProps {
  showYearlyToggle?: boolean;
}

export function PricingWidget({ showYearlyToggle = true }: PricingWidgetProps) {
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [yearly, setYearly] = useState(false);
  const [subscribingId, setSubscribingId] = useState<number | null>(null);
  const [subError, setSubError] = useState<string | null>(null);

  useEffect(() => {
    axios.get('/api/payments/plans')
      .then(({ data }) => setPlans(data))
      .catch(() => setError('Failed to load plans'))
      .finally(() => setLoading(false));
  }, []);

  const handleSubscribe = async (planId: number) => {
    setSubscribingId(planId);
    setSubError(null);
    try {
      // Try authenticated subscribe first — import api dynamically to avoid
      // pulling auth interceptor into public context if user isn't logged in
      const { api } = await import('@/lib/api');
      const { data } = await api.post('/payments/subscribe', {
        planId,
        frequency: yearly ? 'yearly' : 'monthly',
      });
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      if (status === 401) {
        setSubError('Please sign in to subscribe');
      } else {
        const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to start checkout';
        setSubError(msg);
      }
    } finally {
      setSubscribingId(null);
    }
  };

  const styles = {
    container: { maxWidth: 900, margin: '0 auto', padding: '0 16px', color: '#fff' } as React.CSSProperties,
    toggleRow: { display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 12, marginBottom: 32 } as React.CSSProperties,
    toggle: (active: boolean) => ({
      padding: '6px 16px',
      background: active ? '#722ed1' : 'rgba(255,255,255,0.1)',
      color: '#fff',
      border: 'none',
      borderRadius: 20,
      cursor: 'pointer',
      fontWeight: active ? 600 : 400,
      fontSize: '0.9rem',
    } as React.CSSProperties),
    saveBadge: { background: '#52c41a', color: '#fff', padding: '2px 8px', borderRadius: 10, fontSize: '0.75rem', fontWeight: 600 } as React.CSSProperties,
    grid: { display: 'flex', gap: 24, justifyContent: 'center', flexWrap: 'wrap' as const } as React.CSSProperties,
    card: (highlighted: boolean) => ({
      flex: '1 1 250px',
      maxWidth: 300,
      padding: 24,
      background: highlighted ? 'rgba(114,46,209,0.15)' : 'rgba(255,255,255,0.06)',
      border: highlighted ? '2px solid #722ed1' : '1px solid rgba(255,255,255,0.12)',
      borderRadius: 12,
      textAlign: 'center' as const,
      position: 'relative' as const,
    }),
    planName: { fontSize: '1.25rem', fontWeight: 600, marginBottom: 8 } as React.CSSProperties,
    price: { fontSize: '2rem', fontWeight: 700, margin: '8px 0' } as React.CSSProperties,
    period: { fontSize: '0.9rem', opacity: 0.7 } as React.CSSProperties,
    featureList: { textAlign: 'left' as const, padding: '12px 0', listStyle: 'none', margin: 0 } as React.CSSProperties,
    feature: { padding: '4px 0', fontSize: '0.9rem' } as React.CSSProperties,
    checkMark: { color: '#52c41a', marginRight: 8 } as React.CSSProperties,
    subscribeBtn: (subscribing: boolean) => ({
      width: '100%',
      padding: '12px 20px',
      background: '#722ed1',
      color: '#fff',
      border: 'none',
      borderRadius: 8,
      fontWeight: 600,
      cursor: 'pointer',
      marginTop: 16,
      opacity: subscribing ? 0.7 : 1,
    } as React.CSSProperties),
    error: { color: '#ff4d4f', fontSize: '0.85rem', marginTop: 8, textAlign: 'center' as const } as React.CSSProperties,
    popularTag: {
      position: 'absolute' as const,
      top: -12,
      right: 16,
      background: '#722ed1',
      color: '#fff',
      padding: '4px 12px',
      borderRadius: 12,
      fontSize: '0.75rem',
      fontWeight: 600,
    } as React.CSSProperties,
  };

  if (loading) {
    return <div style={{ ...styles.container, textAlign: 'center' }}>Loading plans...</div>;
  }

  if (error) {
    return (
      <div style={{ ...styles.container, textAlign: 'center' }}>
        <p style={{ opacity: 0.7 }}>{error}</p>
        <a href="/pricing" style={{ color: '#722ed1' }}>View pricing page</a>
      </div>
    );
  }

  const hasYearlyPlans = plans.some(p => p.yearlyPriceCAD !== null);

  return (
    <div style={styles.container}>
      {showYearlyToggle && hasYearlyPlans && (
        <div style={styles.toggleRow}>
          <button type="button" style={styles.toggle(!yearly)} onClick={() => setYearly(false)}>Monthly</button>
          <button type="button" style={styles.toggle(yearly)} onClick={() => setYearly(true)}>
            Yearly <span style={styles.saveBadge}>Save 20%</span>
          </button>
        </div>
      )}

      <div style={styles.grid}>
        {/* Free tier */}
        <div style={styles.card(false)}>
          <div style={styles.planName}>Free</div>
          <div style={styles.price}>$0</div>
          <div style={styles.period}>forever</div>
          <ul style={styles.featureList}>
            <li style={styles.feature}><span style={styles.checkMark}>&#x2713;</span>Access public content</li>
            <li style={styles.feature}><span style={styles.checkMark}>&#x2713;</span>Browse campaigns</li>
            <li style={styles.feature}><span style={styles.checkMark}>&#x2713;</span>View public map</li>
          </ul>
        </div>

        {plans.map((plan) => {
          const price = yearly && plan.yearlyPriceCAD ? plan.yearlyPriceCAD : plan.priceCAD;
          const period = yearly && plan.yearlyPriceCAD ? '/year' : '/month';
          const features = (plan.features || []) as string[];
          const isPopular = plan.tier >= 2;

          return (
            <div key={plan.id} style={styles.card(isPopular)}>
              {isPopular && <div style={styles.popularTag}>Popular</div>}
              <div style={styles.planName}>{plan.name}</div>
              <div style={styles.price}>${(price / 100).toFixed(2)}</div>
              <div style={styles.period}>{period}</div>
              {plan.description && (
                <p style={{ fontSize: '0.85rem', opacity: 0.7, margin: '8px 0' }}>{plan.description}</p>
              )}
              <ul style={styles.featureList}>
                {features.map((f, i) => (
                  <li key={i} style={styles.feature}><span style={styles.checkMark}>&#x2713;</span>{f}</li>
                ))}
              </ul>
              <button
                type="button"
                style={styles.subscribeBtn(subscribingId === plan.id)}
                onClick={() => handleSubscribe(plan.id)}
                disabled={subscribingId === plan.id}
              >
                {subscribingId === plan.id ? 'Processing...' : 'Subscribe'}
              </button>
            </div>
          );
        })}
      </div>

      {subError && <div style={styles.error}>{subError}</div>}
    </div>
  );
}
