import { useState, useEffect } from 'react';
import axios from 'axios';

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

interface DonationWidgetProps {
  buttonText?: string;
  showAmounts?: boolean;
}

export function DonationWidget({ buttonText = 'Donate Now', showAmounts = true }: DonationWidgetProps) {
  const [config, setConfig] = useState<PaymentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [customAmount, setCustomAmount] = useState('');
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');
  const [isAnonymous, setIsAnonymous] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  useEffect(() => {
    axios.get('/api/payments/config')
      .then(({ data }) => {
        setConfig(data);
        if (data.donationSuggestedAmounts?.length > 0) {
          setSelectedAmount(data.donationSuggestedAmounts[0]);
        }
      })
      .catch(() => setError('Failed to load donation settings'))
      .finally(() => setLoading(false));
  }, []);

  const handleDonate = async () => {
    if (!email) {
      setSubmitError('Email is required');
      return;
    }
    const amountCents = selectedAmount || (customAmount ? Math.round(parseFloat(customAmount) * 100) : 0);
    const minimum = config?.donationMinimum || 500;
    if (!amountCents || amountCents < minimum) {
      setSubmitError(`Minimum donation is $${(minimum / 100).toFixed(2)}`);
      return;
    }

    setSubmitting(true);
    setSubmitError(null);
    try {
      const { data } = await axios.post('/api/payments/donate', {
        amountCents,
        email,
        name: name || undefined,
        message: message || undefined,
        isAnonymous,
      });
      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';
      setSubmitError(msg);
    } finally {
      setSubmitting(false);
    }
  };

  const styles = {
    container: { maxWidth: 500, margin: '0 auto', padding: '24px', color: '#fff' } as React.CSSProperties,
    card: { background: 'rgba(255,255,255,0.08)', borderRadius: 12, padding: 24 } as React.CSSProperties,
    amountBtn: (active: boolean) => ({
      display: 'inline-block',
      padding: '10px 20px',
      margin: '4px',
      background: active ? '#eb2f96' : 'rgba(255,255,255,0.1)',
      color: '#fff',
      border: active ? '2px solid #eb2f96' : '2px solid rgba(255,255,255,0.2)',
      borderRadius: 8,
      cursor: 'pointer',
      fontWeight: 600,
      fontSize: '1rem',
    } as React.CSSProperties),
    input: {
      width: '100%',
      padding: '10px 14px',
      background: 'rgba(255,255,255,0.08)',
      border: '1px solid rgba(255,255,255,0.2)',
      borderRadius: 8,
      color: '#fff',
      fontSize: '0.95rem',
      boxSizing: 'border-box' as const,
      marginBottom: 12,
    } as React.CSSProperties,
    label: { display: 'block', marginBottom: 4, fontSize: '0.85rem', opacity: 0.8 } as React.CSSProperties,
    submitBtn: {
      width: '100%',
      padding: '14px 24px',
      background: '#eb2f96',
      color: '#fff',
      border: 'none',
      borderRadius: 8,
      fontWeight: 600,
      fontSize: '1.05rem',
      cursor: 'pointer',
      opacity: submitting ? 0.7 : 1,
    } as React.CSSProperties,
    error: { color: '#ff4d4f', fontSize: '0.9rem', marginBottom: 12 } as React.CSSProperties,
    checkboxRow: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, fontSize: '0.9rem' } as React.CSSProperties,
  };

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

  if (error || !config?.enableDonations) {
    return (
      <div style={{ ...styles.container, textAlign: 'center' }}>
        <p style={{ opacity: 0.7 }}>{error || 'Donations are currently disabled'}</p>
        <a href="/donate" style={{ color: '#eb2f96' }}>Go to donation page</a>
      </div>
    );
  }

  const suggestedAmounts = config.donationSuggestedAmounts || [];

  return (
    <div style={styles.container}>
      <div style={styles.card}>
        {showAmounts && suggestedAmounts.length > 0 && (
          <div style={{ marginBottom: 20, textAlign: 'center' }}>
            <div style={{ fontWeight: 600, marginBottom: 8 }}>Select an amount</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center' }}>
              {suggestedAmounts.map((amt) => (
                <button
                  key={amt}
                  type="button"
                  style={styles.amountBtn(selectedAmount === amt)}
                  onClick={() => { setSelectedAmount(amt); setCustomAmount(''); }}
                >
                  ${(amt / 100).toFixed(0)}
                </button>
              ))}
              <button
                type="button"
                style={styles.amountBtn(!selectedAmount)}
                onClick={() => setSelectedAmount(null)}
              >
                Custom
              </button>
            </div>
          </div>
        )}

        {(!selectedAmount || !showAmounts) && (
          <div style={{ marginBottom: 12 }}>
            <label style={styles.label}>Amount ($)</label>
            <input
              type="number"
              min={(config.donationMinimum || 500) / 100}
              step="1"
              value={customAmount}
              onChange={(e) => { setCustomAmount(e.target.value); setSelectedAmount(null); }}
              placeholder={`Minimum $${((config.donationMinimum || 500) / 100).toFixed(2)}`}
              style={styles.input}
            />
          </div>
        )}

        <div>
          <label style={styles.label}>Email *</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="your@email.com"
            style={styles.input}
          />
        </div>

        <div>
          <label style={styles.label}>Name (optional)</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            style={styles.input}
          />
        </div>

        <div>
          <label style={styles.label}>Message (optional)</label>
          <textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            rows={2}
            style={{ ...styles.input, resize: 'vertical' }}
          />
        </div>

        <div style={styles.checkboxRow}>
          <input
            type="checkbox"
            checked={isAnonymous}
            onChange={(e) => setIsAnonymous(e.target.checked)}
            id="donate-anon"
          />
          <label htmlFor="donate-anon">Make my donation anonymous</label>
        </div>

        {submitError && <div style={styles.error}>{submitError}</div>}

        <button
          type="button"
          style={styles.submitBtn}
          onClick={handleDonate}
          disabled={submitting}
        >
          {submitting ? 'Processing...' : `${buttonText} ${selectedAmount ? `$${(selectedAmount / 100).toFixed(0)}` : customAmount ? `$${parseFloat(customAmount).toFixed(2)}` : ''}`}
        </button>
      </div>
    </div>
  );
}
