import React, { useState } from 'react';
import type { ScoreResult, UserAnswer } from '../types';
import { submitLead } from '../api/submitLead';
import { Mail, Lock } from 'lucide-react';
import { Turnstile } from '@marsidev/react-turnstile';
import styles from '../styles/results.module.css';

const config = window.noon_audit_config;

interface EmailGateProps {
  auditId: number;
  scoreResult: ScoreResult;
  answers: UserAnswer[];
  onComplete: () => void;
}

export const EmailGate: React.FC<EmailGateProps> = ({
  auditId,
  scoreResult,
  answers,
  onComplete,
}) => {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [company, setCompany] = useState('');
  const [websiteUrl, setWebsiteUrl] = useState(''); // Honeypot
  const [consent, setConsent] = useState(false);
  const [marketingOptin, setMarketingOptin] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [turnstileToken, setTurnstileToken] = useState<string>('');

  const agencyName = config.consultantName || 'us';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !consent) return;

    setSubmitting(true);
    setError('');

    try {
      await submitLead({
        audit_id: auditId,
        email,
        name,
        company,
        score: scoreResult.rawScore,
        risk_band: scoreResult.riskBand,
        category_scores: scoreResult.categoryScores,
        answers,
        website_url: websiteUrl,
        turnstile_token: turnstileToken,
        consented_at: new Date().toISOString(),
        marketing_optin: marketingOptin,
      });
      onComplete();
    } catch (err) {
      setError('Something went wrong. Please try again.');
      console.error('Lead submission error:', err);
    } finally {
      setSubmitting(false);
    }
  };

  // Build the required consent label with dynamic policy links
  const buildConsentLabel = () => {
    const hasPrivacy = !!config.privacyUrl;
    const hasTerms = !!config.termsUrl;
    const policyLinks = [];

    if (hasTerms) {
      policyLinks.push(
        <a key="terms" href={config.termsUrl} target="_blank" rel="noopener noreferrer">
          Terms &amp; Conditions
        </a>
      );
    }
    if (hasPrivacy) {
      policyLinks.push(
        <a key="privacy" href={config.privacyUrl} target="_blank" rel="noopener noreferrer">
          Privacy Policy
        </a>
      );
    }

    return (
      <>
        I consent to {agencyName} processing my data and contacting me
        regarding my audit results
        {policyLinks.length > 0 && (
          <>
            . I have read the{' '}
            {policyLinks.reduce<React.ReactNode[]>((acc, link, i) => {
              if (i > 0) acc.push(' and ');
              acc.push(link);
              return acc;
            }, [])}
          </>
        )}
      </>
    );
  };

  return (
    <div className={styles.emailGate}>
      <span className={styles.gateIcon}>
        <Mail size={48} color="var(--noon-accent)" />
      </span>
      <h3 className={styles.gateTitle}>Your audit is ready!</h3>
      <p className={styles.gateSubtitle}>
        Enter your details below to unlock your personalised audit report
        and improvement roadmap.
      </p>

      <form className={styles.gateForm} onSubmit={handleSubmit}>
        {/* Anti-spam Honeypot: Visually hidden but visible to CSS-ignorant bots */}
        <div style={{ position: 'absolute', left: '-9999px', top: '-9999px', opacity: 0 }} aria-hidden="true">
          <label htmlFor="website_url">Website URL (leave blank)</label>
          <input
            type="text"
            id="website_url"
            name="website_url"
            value={websiteUrl}
            onChange={(e) => setWebsiteUrl(e.target.value)}
            tabIndex={-1}
            autoComplete="off"
          />
        </div>

        <input
          type="email"
          className={styles.gateInput}
          placeholder="Work email *"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          id="noon-audit-email"
        />
        <input
          type="text"
          className={styles.gateInput}
          placeholder="Your name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          id="noon-audit-name"
        />
        <input
          type="text"
          className={styles.gateInput}
          placeholder="Company"
          value={company}
          onChange={(e) => setCompany(e.target.value)}
          id="noon-audit-company"
        />

        {/* Required: Consent to contact about audit results */}
        <label className={styles.consentLabel} id="noon-audit-consent-label">
          <input
            type="checkbox"
            checked={consent}
            onChange={(e) => setConsent(e.target.checked)}
            className={styles.consentCheckbox}
            id="noon-audit-consent"
            required
          />
          <span>{buildConsentLabel()} *</span>
        </label>

        {/* Optional: Marketing opt-in */}
        <label className={styles.consentLabel} id="noon-audit-marketing-label">
          <input
            type="checkbox"
            checked={marketingOptin}
            onChange={(e) => setMarketingOptin(e.target.checked)}
            className={styles.consentCheckbox}
            id="noon-audit-marketing"
          />
          <span>
            I'd also like to receive tips and updates from {agencyName}
          </span>
        </label>

        {config.turnstileSiteKey && (
          <div style={{ margin: '1rem 0', display: 'flex', justifyContent: 'center' }}>
            <Turnstile
              siteKey={config.turnstileSiteKey}
              onSuccess={(token) => setTurnstileToken(token)}
              onError={() => setError('Security check failed. Please refresh and try again.')}
              onExpire={() => setTurnstileToken('')}
            />
          </div>
        )}

        <button
          type="submit"
          className={styles.gateSubmit}
          disabled={submitting || !email || !consent || (!!config.turnstileSiteKey && !turnstileToken)}
          id="noon-audit-submit"
        >
          {submitting ? 'Unlocking…' : 'Unlock My Results →'}
        </button>
        {error && <p style={{ color: 'var(--noon-danger)', fontSize: '0.85rem' }}>{error}</p>}
      </form>

      <p className={styles.gateDisclaimer}>
        <Lock size={12} style={{ display: 'inline', marginRight: '4px', verticalAlign: 'text-bottom' }} />
        Your details are kept secure and are never shared with third parties.
      </p>
    </div>
  );
};
