/**
 * Self-contained campaign email form widget for GrapesJS landing pages.
 * Rendered via createRoot() outside the App's ConfigProvider — uses inline styles only, no Ant Design.
 * Follows the same pattern as DonationWidget, PricingWidget, ProductWidget.
 */
import { useState, useEffect } from 'react';
import axios from 'axios';

const apiBase = '/api';

// Theme colors matching the dark public pages
const COLORS = {
  bg: '#0d1b2a',
  card: '#1b2838',
  primary: '#3498db',
  primaryHover: '#2980b9',
  text: '#fff',
  textMuted: 'rgba(255,255,255,0.65)',
  border: 'rgba(255,255,255,0.15)',
  success: '#52c41a',
  error: '#ff4d4f',
};

const inputStyle: React.CSSProperties = {
  width: '100%',
  padding: '10px 14px',
  border: `1px solid ${COLORS.border}`,
  borderRadius: 6,
  background: 'rgba(255,255,255,0.05)',
  color: COLORS.text,
  fontSize: 14,
  outline: 'none',
  boxSizing: 'border-box',
};

const buttonStyle: React.CSSProperties = {
  padding: '10px 24px',
  background: COLORS.primary,
  color: '#fff',
  border: 'none',
  borderRadius: 6,
  fontWeight: 600,
  fontSize: 14,
  cursor: 'pointer',
};

interface Campaign {
  title: string;
  description: string | null;
  emailSubject: string;
  emailBody: string;
  targetGovernmentLevels: string[];
  allowSmtpEmail: boolean;
  allowMailtoLink: boolean;
  collectUserInfo: boolean;
}

interface Representative {
  name: string;
  email: string | null;
  representativeSetName: string;
}

interface CampaignFormWidgetProps {
  campaignSlug: string;
  compact?: boolean;
}

export function CampaignFormWidget({ campaignSlug, compact = false }: CampaignFormWidgetProps) {
  const [campaign, setCampaign] = useState<Campaign | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Step 1: postal code + user info
  const [postalCode, setPostalCode] = useState('');
  const [userName, setUserName] = useState('');
  const [userEmail, setUserEmail] = useState('');
  const [lookupLoading, setLookupLoading] = useState(false);

  // Step 2: representatives
  const [representatives, setRepresentatives] = useState<Representative[]>([]);
  const [step, setStep] = useState<'lookup' | 'reps' | 'done'>('lookup');

  // Step 3: sending
  const [sendingTo, setSendingTo] = useState<string | null>(null);
  const [sentTo, setSentTo] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (!campaignSlug) {
      setError('No campaign slug configured');
      setLoading(false);
      return;
    }
    axios.get<Campaign>(`${apiBase}/campaigns/${campaignSlug}/details`)
      .then(({ data }) => setCampaign(data))
      .catch(() => setError('Campaign not found'))
      .finally(() => setLoading(false));
  }, [campaignSlug]);

  const handleLookup = async () => {
    if (!postalCode.trim()) return;
    setLookupLoading(true);
    try {
      const code = postalCode.replace(/\s/g, '').toUpperCase();
      const { data } = await axios.get<{ representatives: Representative[] }>(
        `${apiBase}/representatives/by-postal/${code}`
      );
      let reps = data.representatives;
      if (campaign?.targetGovernmentLevels?.length) {
        const targets = new Set(campaign.targetGovernmentLevels);
        reps = reps.filter(r => {
          const setName = r.representativeSetName?.toLowerCase() || '';
          if (targets.has('FEDERAL') && setName.includes('house of commons')) return true;
          if (targets.has('PROVINCIAL') && (setName.includes('legislative') || setName.includes('national'))) return true;
          if (targets.has('MUNICIPAL') && setName.includes('city')) return true;
          if (targets.has('SCHOOL_BOARD') && setName.includes('school')) return true;
          return false;
        });
      }
      setRepresentatives(reps);
      setStep('reps');
    } catch {
      setError('Could not look up representatives for this postal code');
    } finally {
      setLookupLoading(false);
    }
  };

  const handleSend = async (rep: Representative) => {
    if (!campaign || !rep.email) return;
    setSendingTo(rep.email);
    try {
      await axios.post(`${apiBase}/campaigns/${campaignSlug}/send-email`, {
        userEmail: userEmail || 'anonymous@cmlite.org',
        userName: userName || 'Anonymous',
        postalCode: postalCode.replace(/\s/g, '').toUpperCase(),
        recipientEmail: rep.email,
        recipientName: rep.name,
      });
      setSentTo(prev => new Set(prev).add(rep.email!));
    } catch {
      // Silently fail — user sees button unchanged
    } finally {
      setSendingTo(null);
    }
  };

  const handleMailto = (rep: Representative) => {
    if (!campaign || !rep.email) return;
    const subject = encodeURIComponent(campaign.emailSubject);
    const body = encodeURIComponent(campaign.emailBody);
    window.open(`mailto:${rep.email}?subject=${subject}&body=${body}`, '_blank');
  };

  const allSent = representatives.length > 0 && representatives.every(r => !r.email || sentTo.has(r.email));

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 32, color: COLORS.textMuted }}>
        Loading campaign...
      </div>
    );
  }

  if (error || !campaign) {
    return (
      <div style={{ textAlign: 'center', padding: 32, color: COLORS.error }}>
        {error || 'Campaign unavailable'}
      </div>
    );
  }

  return (
    <div style={{
      maxWidth: compact ? 480 : 600,
      margin: '0 auto',
      background: COLORS.card,
      borderRadius: 12,
      padding: compact ? 20 : 32,
      color: COLORS.text,
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    }}>
      {/* Title */}
      <h3 style={{ margin: '0 0 8px', fontSize: compact ? 18 : 22, fontWeight: 700 }}>
        {campaign.title}
      </h3>
      {campaign.description && !compact && (
        <p style={{ margin: '0 0 20px', color: COLORS.textMuted, fontSize: 14, lineHeight: 1.5 }}>
          {campaign.description}
        </p>
      )}

      {/* Step: Lookup */}
      {step === 'lookup' && (
        <div>
          {campaign.collectUserInfo && (
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              <input
                type="text"
                placeholder="Your name"
                value={userName}
                onChange={e => setUserName(e.target.value)}
                style={{ ...inputStyle, flex: 1 }}
              />
              <input
                type="email"
                placeholder="Your email"
                value={userEmail}
                onChange={e => setUserEmail(e.target.value)}
                style={{ ...inputStyle, flex: 1 }}
              />
            </div>
          )}
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              type="text"
              placeholder="Postal code (e.g. K1A 0A6)"
              value={postalCode}
              onChange={e => setPostalCode(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleLookup()}
              style={{ ...inputStyle, flex: 1 }}
            />
            <button
              onClick={handleLookup}
              disabled={lookupLoading || !postalCode.trim()}
              style={{
                ...buttonStyle,
                opacity: lookupLoading || !postalCode.trim() ? 0.6 : 1,
              }}
            >
              {lookupLoading ? 'Looking up...' : 'Find Reps'}
            </button>
          </div>
        </div>
      )}

      {/* Step: Representatives */}
      {step === 'reps' && (
        <div>
          {allSent ? (
            <div style={{ textAlign: 'center', padding: 20 }}>
              <div style={{ fontSize: 48, marginBottom: 8 }}>&#x2705;</div>
              <p style={{ fontSize: 16, fontWeight: 600, color: COLORS.success }}>
                All messages sent! Thank you.
              </p>
              <button
                onClick={() => { setStep('lookup'); setSentTo(new Set()); setRepresentatives([]); }}
                style={{ ...buttonStyle, background: 'rgba(255,255,255,0.1)', marginTop: 12, fontSize: 13 }}
              >
                Send again with different postal code
              </button>
            </div>
          ) : (
            <>
              <p style={{ margin: '0 0 12px', fontSize: 13, color: COLORS.textMuted }}>
                {representatives.length} representative{representatives.length !== 1 ? 's' : ''} found for {postalCode.toUpperCase()}
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {representatives.map((rep, i) => (
                  <div key={i} style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '10px 14px',
                    background: 'rgba(255,255,255,0.04)',
                    borderRadius: 8,
                    border: `1px solid ${sentTo.has(rep.email || '') ? COLORS.success + '40' : COLORS.border}`,
                  }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{rep.name}</div>
                      <div style={{ fontSize: 12, color: COLORS.textMuted }}>{rep.representativeSetName}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 6 }}>
                      {sentTo.has(rep.email || '') ? (
                        <span style={{ color: COLORS.success, fontSize: 13, fontWeight: 600 }}>Sent &#x2713;</span>
                      ) : (
                        <>
                          {campaign.allowSmtpEmail && rep.email && (
                            <button
                              onClick={() => handleSend(rep)}
                              disabled={sendingTo === rep.email}
                              style={{
                                ...buttonStyle,
                                padding: '6px 14px',
                                fontSize: 12,
                                opacity: sendingTo === rep.email ? 0.6 : 1,
                              }}
                            >
                              {sendingTo === rep.email ? 'Sending...' : 'Send'}
                            </button>
                          )}
                          {campaign.allowMailtoLink && rep.email && (
                            <button
                              onClick={() => handleMailto(rep)}
                              style={{
                                ...buttonStyle,
                                padding: '6px 14px',
                                fontSize: 12,
                                background: 'rgba(255,255,255,0.1)',
                              }}
                            >
                              Email App
                            </button>
                          )}
                        </>
                      )}
                    </div>
                  </div>
                ))}
              </div>
              <button
                onClick={() => setStep('lookup')}
                style={{
                  ...buttonStyle,
                  background: 'transparent',
                  border: `1px solid ${COLORS.border}`,
                  marginTop: 12,
                  fontSize: 13,
                  width: '100%',
                }}
              >
                Change postal code
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}
