import { useState, useEffect } from 'react';
import { Drawer, Radio, InputNumber, Spin, Typography, Space, Button, theme, Grid } from 'antd';
import { HeartOutlined, DollarOutlined, AppstoreOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Text, Paragraph } = Typography;

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

export type DonateVariant = 'simple' | 'set-amount' | 'full';

export interface DonateInsertResult {
  variant: DonateVariant;
  amount?: number; // cents, for set-amount variant
  config?: PaymentConfig; // for full variant
}

interface DonateInsertModalProps {
  open: boolean;
  onClose: () => void;
  onInsert: (result: DonateInsertResult) => void;
}

export function DonateInsertModal({ open, onClose, onInsert }: DonateInsertModalProps) {
  const [variant, setVariant] = useState<DonateVariant>('simple');
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [amount, setAmount] = useState<number | null>(25);
  const [config, setConfig] = useState<PaymentConfig | null>(null);
  const [configLoading, setConfigLoading] = useState(false);
  const [configError, setConfigError] = useState<string | null>(null);
  const { token } = theme.useToken();

  // Fetch payment config when "full" variant is selected
  useEffect(() => {
    if (variant === 'full' && !config && open) {
      setConfigLoading(true);
      setConfigError(null);
      axios.get('/api/payments/config')
        .then(({ data }) => setConfig(data))
        .catch(() => setConfigError('Failed to load donation settings. The full card will use default values.'))
        .finally(() => setConfigLoading(false));
    }
  }, [variant, config, open]);

  // Reset when modal opens
  useEffect(() => {
    if (open) {
      setVariant('simple');
      setAmount(25);
      setConfigError(null);
    }
  }, [open]);

  const handleOk = () => {
    const result: DonateInsertResult = { variant };
    if (variant === 'set-amount' && amount) {
      result.amount = Math.round(amount * 100); // dollars to cents
    }
    if (variant === 'full') {
      result.config = config || undefined;
    }
    onInsert(result);
    onClose();
  };

  const cardStyle = (selected: boolean) => ({
    padding: '16px',
    borderRadius: 8,
    border: `2px solid ${selected ? token.colorPrimary : token.colorBorderSecondary}`,
    background: selected ? token.colorPrimaryBg : token.colorBgContainer,
    cursor: 'pointer',
    transition: 'all 0.2s',
  });

  return (
    <Drawer
      title="Insert Donate Block"
      open={open}
      onClose={onClose}
      width={isMobile ? '95vw' : 520}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button
          type="primary"
          onClick={handleOk}
          disabled={variant === 'set-amount' && (!amount || amount <= 0)}
        >
          Insert
        </Button>
      }
    >
      <Paragraph type="secondary" style={{ marginBottom: 16 }}>
        Choose a donation block style to insert into your document.
      </Paragraph>

      <Radio.Group
        value={variant}
        onChange={(e) => setVariant(e.target.value)}
        style={{ width: '100%' }}
      >
        <Space direction="vertical" style={{ width: '100%' }} size={12}>
          {/* Simple CTA */}
          <div style={cardStyle(variant === 'simple')} onClick={() => setVariant('simple')}>
            <Radio value="simple">
              <Space>
                <HeartOutlined style={{ fontSize: 18, color: '#eb2f96' }} />
                <div>
                  <Text strong>Simple CTA Button</Text>
                  <br />
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    A styled button linking to the donate page
                  </Text>
                </div>
              </Space>
            </Radio>
          </div>

          {/* Set Amount */}
          <div style={cardStyle(variant === 'set-amount')} onClick={() => setVariant('set-amount')}>
            <Radio value="set-amount">
              <Space>
                <DollarOutlined style={{ fontSize: 18, color: '#52c41a' }} />
                <div>
                  <Text strong>Set Amount Card</Text>
                  <br />
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    A card pre-configured for a specific dollar amount
                  </Text>
                </div>
              </Space>
            </Radio>
            {variant === 'set-amount' && (
              <div style={{ marginTop: 12, marginLeft: 32 }}>
                <Text style={{ marginRight: 8 }}>Amount:</Text>
                <InputNumber
                  prefix="$"
                  min={1}
                  max={100000}
                  value={amount}
                  onChange={(v) => setAmount(v)}
                  style={{ width: 140 }}
                  size="small"
                />
              </div>
            )}
          </div>

          {/* Full Standard */}
          <div style={cardStyle(variant === 'full')} onClick={() => setVariant('full')}>
            <Radio value="full">
              <Space>
                <AppstoreOutlined style={{ fontSize: 18, color: '#722ed1' }} />
                <div>
                  <Text strong>Full Donate Card</Text>
                  <br />
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    Shows your configured title, description, and suggested amounts
                  </Text>
                </div>
              </Space>
            </Radio>
            {variant === 'full' && (
              <div style={{ marginTop: 12, marginLeft: 32 }}>
                {configLoading && <Spin size="small" />}
                {configError && <Text type="warning" style={{ fontSize: 12 }}>{configError}</Text>}
                {config && (
                  <div style={{ fontSize: 12 }}>
                    <Text type="secondary">Title: </Text><Text>{config.donationPageTitle}</Text>
                    <br />
                    <Text type="secondary">Amounts: </Text>
                    <Text>{config.donationSuggestedAmounts.map(a => `$${(a / 100).toFixed(0)}`).join(', ')}</Text>
                  </div>
                )}
              </div>
            )}
          </div>
        </Space>
      </Radio.Group>
    </Drawer>
  );
}
