import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Typography, Button, Tag, Spin, App, Switch, Space, Grid } from 'antd';
import { ArrowLeftOutlined, CheckOutlined, CrownOutlined, StarOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { api } from '@/lib/api';
import type { SubscriptionPlan } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

export default function PlanDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [plan, setPlan] = useState<SubscriptionPlan | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [yearly, setYearly] = useState(false);
  const [subscribing, setSubscribing] = useState(false);
  const [mySubStatus, setMySubStatus] = useState<string>('none');
  const [myPlanId, setMyPlanId] = useState<number | null>(null);
  const { isAuthenticated } = useAuthStore();
  const { message } = App.useApp();
  const { settings: siteSettings } = useSettingsStore();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  useEffect(() => {
    if (!slug) return;
    setLoading(true);
    axios.get(`/api/payments/plans/${slug}`)
      .then(({ data }) => setPlan(data))
      .catch((err) => {
        if (err.response?.status === 404) {
          setNotFound(true);
        } else {
          message.error('Failed to load plan');
        }
      })
      .finally(() => setLoading(false));
  }, [slug]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (plan) {
      document.title = `${plan.name} | ${siteSettings?.organizationName || 'Pricing'}`;
    }
  }, [plan, siteSettings?.organizationName]);

  useEffect(() => {
    if (isAuthenticated) {
      api.get('/payments/my-subscription')
        .then(({ data }) => {
          setMySubStatus(data.status || 'none');
          setMyPlanId(data.planId || null);
        })
        .catch(() => {});
    }
  }, [isAuthenticated]);

  const handleSubscribe = async () => {
    if (!plan) return;
    if (!isAuthenticated) {
      message.info('Please sign in to subscribe');
      return;
    }
    setSubscribing(true);
    try {
      const { data } = await api.post('/payments/subscribe', {
        planId: plan.id,
        frequency: yearly ? 'yearly' : 'monthly',
      });
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to start checkout';
      message.error(msg);
    } finally {
      setSubscribing(false);
    }
  };

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;

  if (notFound || !plan) {
    return (
      <div style={{ textAlign: 'center', padding: '80px 16px' }}>
        <Title level={3}>Plan not found</Title>
        <Button onClick={() => navigate('/pricing')}>Back to Pricing</Button>
      </div>
    );
  }

  const price = yearly && plan.yearlyPriceCAD ? plan.yearlyPriceCAD : plan.priceCAD;
  const period = yearly && plan.yearlyPriceCAD ? '/year' : '/month';
  const features = (plan.features || []) as string[];
  const isCurrent = mySubStatus === 'active' && myPlanId === plan.id;
  const ctaText = plan.ctaText || (isAuthenticated ? 'Subscribe Now' : 'Sign In to Subscribe');

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', padding: isMobile ? '16px' : '24px 16px' }}>
      {/* Back link */}
      <Button
        type="link"
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/pricing')}
        style={{ padding: 0, marginBottom: 16 }}
      >
        Back to Pricing
      </Button>

      <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 32 }}>
        {/* Left column — media + description */}
        <div style={{ flex: isMobile ? undefined : '0 0 55%', maxWidth: isMobile ? '100%' : '55%' }}>
          {/* Cover photo */}
          {plan.coverPhoto ? (
            <div
              style={{
                position: 'relative',
                paddingBottom: '56.25%',
                overflow: 'hidden',
                borderRadius: 8,
                background: '#1b2838',
                marginBottom: 24,
              }}
            >
              <img
                src={plan.coverPhoto}
                alt={plan.name}
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                }}
              />
              {plan.highlightPlan && (
                <Tag
                  color="gold"
                  style={{ position: 'absolute', top: 12, right: 12, fontSize: 14, padding: '4px 12px' }}
                >
                  <StarOutlined /> Featured
                </Tag>
              )}
            </div>
          ) : (
            <div
              style={{
                paddingBottom: '40%',
                position: 'relative',
                borderRadius: 8,
                background: 'linear-gradient(135deg, #1b2838 0%, #2a3f5f 100%)',
                marginBottom: 24,
              }}
            >
              <div
                style={{
                  position: 'absolute',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  textAlign: 'center',
                }}
              >
                <CrownOutlined style={{ fontSize: 48, opacity: 0.2, color: '#fff' }} />
              </div>
              {plan.highlightPlan && (
                <Tag
                  color="gold"
                  style={{ position: 'absolute', top: 12, right: 12, fontSize: 14, padding: '4px 12px' }}
                >
                  <StarOutlined /> Featured
                </Tag>
              )}
            </div>
          )}

          {/* Plan name and description */}
          {plan.tier >= 2 && (
            <Tag color="purple" style={{ marginBottom: 12 }}>
              <CrownOutlined /> Premium
            </Tag>
          )}
          <Title level={2} style={{ marginTop: 0 }}>{plan.name}</Title>

          {plan.description && (
            <Paragraph style={{ fontSize: 16, lineHeight: 1.7, opacity: 0.85 }}>
              {plan.description}
            </Paragraph>
          )}

          {/* Rich description */}
          {plan.richDescription && (
            <div style={{ marginTop: 16 }}>
              <Paragraph style={{ fontSize: 15, lineHeight: 1.8, opacity: 0.9, whiteSpace: 'pre-wrap' }}>
                {plan.richDescription}
              </Paragraph>
            </div>
          )}
        </div>

        {/* Right column — pricing card */}
        <div style={{ flex: 1 }}>
          <div
            style={{
              padding: 24,
              borderRadius: 12,
              background: 'rgba(255,255,255,0.04)',
              border: plan.highlightPlan ? '2px solid #722ed1' : '1px solid rgba(255,255,255,0.08)',
              position: isMobile ? undefined : 'sticky',
              top: isMobile ? undefined : 80,
            }}
          >
            {/* Pricing toggle */}
            {plan.yearlyPriceCAD && (
              <Space style={{ marginBottom: 20, display: 'flex', justifyContent: 'center' }}>
                <Text>Monthly</Text>
                <Switch checked={yearly} onChange={setYearly} />
                <Text>Yearly <Tag color="green" style={{ marginLeft: 4 }}>Save</Tag></Text>
              </Space>
            )}

            {/* Price display */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Text style={{ fontSize: 42, fontWeight: 700 }}>
                ${(price / 100).toFixed(2)}
              </Text>
              <Text type="secondary" style={{ fontSize: 18 }}>{period}</Text>
            </div>

            {/* Feature checklist */}
            {features.length > 0 && (
              <div style={{ marginBottom: 24 }}>
                {features.map((f, i) => (
                  <div key={i} style={{ padding: '6px 0', display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                    <CheckOutlined style={{ color: '#52c41a', marginTop: 4, flexShrink: 0 }} />
                    <Text>{f}</Text>
                  </div>
                ))}
              </div>
            )}

            {/* CTA */}
            {isCurrent ? (
              <div style={{ textAlign: 'center' }}>
                <Tag color="green" style={{ fontSize: 16, padding: '6px 20px' }}>Current Plan</Tag>
              </div>
            ) : (
              <div>
                <Button
                  type="primary"
                  size="large"
                  block
                  onClick={handleSubscribe}
                  loading={subscribing}
                >
                  {ctaText}
                </Button>
                {plan.ctaSubtext && (
                  <Text
                    type="secondary"
                    style={{ display: 'block', textAlign: 'center', marginTop: 8, fontSize: 13 }}
                  >
                    {plan.ctaSubtext}
                  </Text>
                )}
              </div>
            )}

            {/* Subscriber count */}
            {plan.activeSubscribers !== undefined && plan.activeSubscribers > 0 && (
              <Text
                type="secondary"
                style={{ display: 'block', textAlign: 'center', marginTop: 16, fontSize: 13 }}
              >
                {plan.activeSubscribers} active subscriber{plan.activeSubscribers !== 1 ? 's' : ''}
              </Text>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
