import { useState, useEffect } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { Card, Button, Input, InputNumber, Typography, Form, Checkbox, Space, Spin, App, Progress, theme } from 'antd';
import { HeartOutlined, TeamOutlined, DollarOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import type { DonationPage } from '@/types/api';

const { Title, Paragraph, Text } = Typography;

interface PaymentConfig {
  enableDonations: boolean;
  donationSuggestedAmounts: number[];
  donationMinimum: number;
  donationPageTitle: string;
  donationPageDescription: string | null;
}

export default function DonatePage() {
  const { slug } = useParams<{ slug: string }>();
  const [config, setConfig] = useState<PaymentConfig | null>(null);
  const [donationPage, setDonationPage] = useState<DonationPage | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [customAmount, setCustomAmount] = useState<number | null>(null);
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const { settings: siteSettings } = useSettingsStore();
  const [searchParams] = useSearchParams();
  const { token } = theme.useToken();
  const donateAds = usePageAds('donate');

  // Determine page-specific or global settings
  const pageTitle = donationPage?.title ?? config?.donationPageTitle ?? 'Donate';
  const pageDescription = donationPage?.description ?? config?.donationPageDescription;
  const suggestedAmounts = donationPage?.suggestedAmounts ?? config?.donationSuggestedAmounts ?? [];
  const minimumAmount = donationPage?.minimumAmount ?? config?.donationMinimum ?? 500;

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

  useEffect(() => {
    if (slug) {
      // Slug-based mode: fetch from donation pages API
      axios.get<DonationPage>(`/api/donation-pages/${slug}`)
        .then(({ data }) => {
          setDonationPage(data);
          const amounts = data.suggestedAmounts || [];
          initializeAmount(amounts);
        })
        .catch(() => message.error('Donation page not found'))
        .finally(() => setLoading(false));
    } else {
      // Global mode: fetch from payment config
      axios.get('/api/payments/config')
        .then(({ data }) => {
          setConfig(data);
          const amounts = data.donationSuggestedAmounts || [];
          initializeAmount(amounts);
        })
        .catch(() => message.error('Failed to load donation settings'))
        .finally(() => setLoading(false));
    }
  }, [slug]); // eslint-disable-line react-hooks/exhaustive-deps

  const initializeAmount = (amounts: number[]) => {
    // Check for ?amount= query param
    const amountParam = searchParams.get('amount');
    if (amountParam) {
      const parsed = parseInt(amountParam, 10);
      if (!isNaN(parsed) && parsed > 0) {
        if (amounts.includes(parsed)) {
          setSelectedAmount(parsed);
        } else {
          setSelectedAmount(null);
          setCustomAmount(parsed / 100);
        }
        return;
      }
    }
    if (amounts.length > 0) setSelectedAmount(amounts[0] ?? null);
  };

  const handleDonate = async () => {
    const values = await form.validateFields();
    const amountCents = selectedAmount || (customAmount ? Math.round(customAmount * 100) : 0);
    if (!amountCents || amountCents < minimumAmount) {
      message.error(`Minimum donation is $${(minimumAmount / 100).toFixed(2)}`);
      return;
    }

    setSubmitting(true);
    try {
      // Use page-specific endpoint or global
      const url = slug
        ? `/api/donation-pages/${slug}/donate`
        : '/api/payments/donate';

      const { data } = await axios.post(url, {
        amountCents,
        email: values.email,
        name: values.name || undefined,
        message: values.message || undefined,
        isAnonymous: values.isAnonymous || false,
      });
      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 donation';
      message.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

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

  // Global mode: check if donations are enabled
  if (!slug && !config?.enableDonations) {
    return (
      <Card style={{ textAlign: 'center', padding: 40 }}>
        <Title level={3}>Donations are currently disabled</Title>
      </Card>
    );
  }

  return (
    <div style={{ maxWidth: 500, margin: '0 auto' }}>
      {/* Hero section */}
      <div style={{ textAlign: 'center', marginBottom: 32 }}>
        {donationPage?.coverPhoto && (
          <div style={{
            height: 200,
            marginBottom: 24,
            borderRadius: 12,
            backgroundImage: `url(${donationPage.coverPhoto})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
          }} />
        )}
        <HeartOutlined style={{ fontSize: 48, color: '#eb2f96', marginBottom: 16 }} />
        <Title level={2}>{pageTitle}</Title>
        {pageDescription && (
          <Paragraph style={{ fontSize: 16, opacity: 0.8 }}>{pageDescription}</Paragraph>
        )}

        {/* Goal progress */}
        {donationPage?.goalAmount && donationPage.totalRaised != null && (
          <div style={{ maxWidth: 400, margin: '16px auto 0' }}>
            <Progress
              percent={Math.min(100, Math.round((donationPage.totalRaised / donationPage.goalAmount) * 100))}
              strokeColor={token.colorPrimary}
            />
            <Text style={{ opacity: 0.7, fontSize: 13 }}>
              ${(donationPage.totalRaised / 100).toLocaleString()} raised of ${(donationPage.goalAmount / 100).toLocaleString()} goal
            </Text>
          </div>
        )}

        {/* Stats */}
        {donationPage && (
          <div style={{ display: 'flex', justifyContent: 'center', gap: 24, marginTop: 12, flexWrap: 'wrap' }}>
            {donationPage.showDonorCount && donationPage.donorCount != null && donationPage.donorCount > 0 && (
              <span style={{ color: token.colorPrimary, fontSize: 14 }}>
                <TeamOutlined style={{ marginRight: 4 }} />
                {donationPage.donorCount} {donationPage.donorCount === 1 ? 'donor' : 'donors'}
              </span>
            )}
            {donationPage.showTotalRaised && donationPage.totalRaised != null && donationPage.totalRaised > 0 && (
              <span style={{ color: token.colorSuccess, fontSize: 14 }}>
                <DollarOutlined style={{ marginRight: 4 }} />
                ${(donationPage.totalRaised / 100).toLocaleString()} raised
              </span>
            )}
          </div>
        )}
      </div>

      <AdBanner ads={donateAds} placement="donate" />

      <Card>
        <div style={{ marginBottom: 24 }}>
          <Text strong style={{ display: 'block', marginBottom: 8 }}>Select an amount</Text>
          <Space wrap>
            {suggestedAmounts.map((amt) => (
              <Button
                key={amt}
                type={selectedAmount === amt ? 'primary' : 'default'}
                size="large"
                onClick={() => { setSelectedAmount(amt); setCustomAmount(null); }}
              >
                ${(amt / 100).toFixed(0)}
              </Button>
            ))}
            <Button
              type={!selectedAmount ? 'primary' : 'default'}
              size="large"
              onClick={() => setSelectedAmount(null)}
            >
              Custom
            </Button>
          </Space>
        </div>

        {!selectedAmount && (
          <div style={{ marginBottom: 24 }}>
            <InputNumber
              size="large"
              prefix="$"
              min={minimumAmount / 100}
              step={1}
              value={customAmount}
              onChange={(v) => setCustomAmount(v)}
              style={{ width: '100%' }}
              placeholder={`Minimum $${(minimumAmount / 100).toFixed(2)}`}
            />
          </div>
        )}

        <Form form={form} layout="vertical">
          <Form.Item name="email" label="Email" rules={[{ required: true, type: 'email' }]}>
            <Input size="large" placeholder="your@email.com" />
          </Form.Item>
          <Form.Item name="name" label="Name (optional)">
            <Input size="large" />
          </Form.Item>
          <Form.Item name="message" label="Message (optional)">
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item name="isAnonymous" valuePropName="checked">
            <Checkbox>Make my donation anonymous</Checkbox>
          </Form.Item>
        </Form>

        <Button
          type="primary"
          size="large"
          block
          icon={<HeartOutlined />}
          onClick={handleDonate}
          loading={submitting}
        >
          Donate {selectedAmount ? `$${(selectedAmount / 100).toFixed(0)}` : customAmount ? `$${customAmount.toFixed(2)}` : ''}
        </Button>
      </Card>
    </div>
  );
}
