import { useState, useEffect } from 'react';
import { Card, Button, Row, Col, Typography, Tag, Switch, Space, Spin, App } from 'antd';
import { CheckOutlined, CrownOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import type { SubscriptionPlan } from '@/types/api';
import { api } from '@/lib/api';

const { Title, Text, Paragraph } = Typography;

export default function PricingPage() {
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [yearly, setYearly] = useState(false);
  const [mySubStatus, setMySubStatus] = useState<string>('none');
  const [myPlanId, setMyPlanId] = useState<number | null>(null);
  const [subscribingPlanId, setSubscribingPlanId] = useState<number | null>(null);
  const { isAuthenticated } = useAuthStore();
  const { message } = App.useApp();
  const { settings: siteSettings } = useSettingsStore();
  const navigate = useNavigate();
  const pricingAds = usePageAds('pricing');

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

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

    if (isAuthenticated) {
      api.get('/payments/my-subscription')
        .then(({ data }) => {
          setMySubStatus(data.status || 'none');
          setMyPlanId(data.planId || null);
        })
        .catch(() => {});
    }
  }, [isAuthenticated]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleSubscribe = async (planId: number) => {
    if (!isAuthenticated) {
      message.info('Please sign in to subscribe');
      return;
    }
    setSubscribingPlanId(planId);
    try {
      const { data } = await api.post('/payments/subscribe', {
        planId,
        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 {
      setSubscribingPlanId(null);
    }
  };

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

  return (
    <div style={{ textAlign: 'center' }}>
      <Title level={2}>Choose Your Plan</Title>
      <Paragraph style={{ fontSize: 16, opacity: 0.8 }}>
        Get access to exclusive content and features
      </Paragraph>

      <Space style={{ marginBottom: 32 }}>
        <Text>Monthly</Text>
        <Switch checked={yearly} onChange={setYearly} />
        <Text>Yearly <Tag color="green">Save up to 20%</Tag></Text>
      </Space>

      <Row gutter={[24, 24]} justify="center">
        {/* Free tier */}
        <Col xs={24} sm={12} md={8}>
          <Card
            style={{ height: '100%', textAlign: 'center' }}
            hoverable
          >
            <Title level={3}>Free</Title>
            <div style={{ margin: '16px 0' }}>
              <Text style={{ fontSize: 36, fontWeight: 700 }}>$0</Text>
              <Text type="secondary">/forever</Text>
            </div>
            <div style={{ textAlign: 'left', padding: '0 16px' }}>
              <p><CheckOutlined style={{ color: '#52c41a', marginRight: 8 }} />Access public content</p>
              <p><CheckOutlined style={{ color: '#52c41a', marginRight: 8 }} />Browse campaigns</p>
              <p><CheckOutlined style={{ color: '#52c41a', marginRight: 8 }} />View public map</p>
            </div>
            {mySubStatus === 'none' && (
              <Tag color="blue" style={{ marginTop: 16 }}>Current Plan</Tag>
            )}
          </Card>
        </Col>

        {plans.map((plan) => {
          const price = yearly && plan.yearlyPriceCAD ? plan.yearlyPriceCAD : plan.priceCAD;
          const period = yearly && plan.yearlyPriceCAD ? '/year' : '/month';
          const isCurrent = mySubStatus === 'active' && myPlanId === plan.id;
          const features = (plan.features || []) as string[];

          return (
            <Col xs={24} sm={12} md={8} key={plan.id}>
              <Card
                style={{
                  height: '100%',
                  textAlign: 'center',
                  border: plan.tier >= 2 ? '2px solid #722ed1' : undefined,
                }}
                hoverable
              >
                {plan.tier >= 2 && (
                  <Tag color="purple" style={{ position: 'absolute', top: 12, right: 12 }}>
                    <CrownOutlined /> Popular
                  </Tag>
                )}
                <Title level={3}>{plan.name}</Title>
                <div style={{ margin: '16px 0' }}>
                  <Text style={{ fontSize: 36, fontWeight: 700 }}>${(price / 100).toFixed(2)}</Text>
                  <Text type="secondary">{period}</Text>
                </div>
                {plan.description && (
                  <Paragraph type="secondary" style={{ marginBottom: 16 }}>{plan.description}</Paragraph>
                )}
                <div style={{ textAlign: 'left', padding: '0 16px' }}>
                  {features.map((f, i) => (
                    <p key={i}><CheckOutlined style={{ color: '#52c41a', marginRight: 8 }} />{f}</p>
                  ))}
                </div>
                {isCurrent ? (
                  <Tag color="green" style={{ marginTop: 16 }}>Current Plan</Tag>
                ) : (
                  <Button
                    type="primary"
                    size="large"
                    style={{ marginTop: 16, width: '100%' }}
                    onClick={() => handleSubscribe(plan.id)}
                    loading={subscribingPlanId === plan.id}
                  >
                    {isAuthenticated ? 'Subscribe' : 'Sign In to Subscribe'}
                  </Button>
                )}
                {plan.slug && (
                  <Button
                    type="link"
                    size="small"
                    icon={<ArrowRightOutlined />}
                    onClick={() => navigate(`/pricing/${plan.slug}`)}
                    style={{ marginTop: 8 }}
                  >
                    Learn more
                  </Button>
                )}
              </Card>
            </Col>
          );
        })}
      </Row>

      <AdBanner ads={pricingAds} placement="pricing" />
    </div>
  );
}
