'use client';

import { ChangeEvent, FormEvent, ReactNode, useState } from 'react';
import { useTurnstile } from '@/hooks/useTurnstile';
import { Language, t } from '@/lib/translations/dealer-template';

interface ContactFormState {
  status: 'idle' | 'submitting' | 'success' | 'error';
  message?: string | ReactNode;
}

interface ContactSectionProps {
  dealerName?: string;
  dealerNumber?: string;
  subdomain?: string;
  /**
   * Parent-domain tuple for the dealer this form targets. Included in the POST
   * body so the route can identify the dealer on hosts where the proxy does
   * not inject x-dealer-* headers (e.g., the dev server at
   * amsoil-dlp.acdev3.com, which serves dealer pages via the direct-path
   * /sites/{subdomain}/{domainSlug}/... format and has no wildcard DNS).
   * The route still prefers proxy-injected headers when present.
   */
  domainPrefix?: string;
  domain?: string;
  isEnabled?: boolean;
  turnstileSiteKey?: string | null;
  language?: Language;
}

const initialState: ContactFormState = { status: 'idle' };

function formatPhoneNumber(value: string): string {
  // Strip all non-numeric characters
  const digits = value.replace(/\D/g, '');

  // Format based on number of digits
  if (digits.length === 0) return '';
  if (digits.length <= 3) return `(${digits}`;
  if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
}

export default function ContactSection({
  dealerName,
  dealerNumber,
  subdomain,
  domainPrefix,
  domain,
  isEnabled = true,
  turnstileSiteKey,
  language = 'en',
}: ContactSectionProps) {
  const [state, setState] = useState<ContactFormState>(initialState);
  const [phone, setPhone] = useState('');
  const [formLoadTime] = useState(() => Date.now());
  const {
    containerRef: turnstileRef,
    getToken: getTurnstileToken,
    reset: resetTurnstile,
    isVerified: isTurnstileVerified,
  } = useTurnstile({
    siteKey: turnstileSiteKey || undefined,
  });

  // Don't render if form is disabled
  if (!isEnabled) {
    return null;
  }

  const handlePhoneChange = (event: ChangeEvent<HTMLInputElement>) => {
    const formatted = formatPhoneNumber(event.target.value);
    setPhone(formatted);
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (state.status === 'submitting') {
      return;
    }

    const form = event.currentTarget;
    const formData = new FormData(form);
    const name = String(formData.get('name') || '').trim();
    const email = String(formData.get('email') || '').trim();
    const phoneValue = phone.trim();
    const message = String(formData.get('message') || '').trim();
    const honeypot = String(formData.get('website') || '').trim();
    const timeElapsed = Date.now() - formLoadTime;
    const turnstileToken = getTurnstileToken();

    if (!name || !email || !message) {
      setState({ status: 'error', message: t(language, 'contact.requiredFields') });
      return;
    }

    if (!isTurnstileVerified) {
      setState({ status: 'error', message: t(language, 'contact.securityVerification') });
      return;
    }

    setState({ status: 'submitting' });

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name,
          email,
          phone: phoneValue || undefined,
          message,
          dealerNumber: dealerNumber || undefined,
          subdomain: subdomain || undefined,
          // Parent-domain tuple so the route can identify the correct sibling
          // on hosts where the proxy doesn't inject x-dealer-* headers (e.g.,
          // the dev server amsoil-dlp.acdev3.com serving /sites/{subdomain}/
          // {domainSlug}/...). Proxy headers still take precedence when present.
          domainPrefix: domainPrefix || undefined,
          domain: domain || undefined,
          // Spam protection fields
          _hp: honeypot || undefined, // Honeypot - should be empty
          _ts: timeElapsed, // Time elapsed since form load (ms)
          _turnstile: turnstileToken || undefined, // Cloudflare Turnstile token
        }),
      });

      if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        if (data.errors?.length) {
          throw new Error(data.errors[0]);
        }
        throw new Error('Failed to submit contact form.');
      }

      form.reset();
      setPhone('');
      resetTurnstile();
      setState({
        status: 'success',
        message: (
          <>
            {t(language, 'contact.thankYou')}{' '}
            {dealerName ? (
              <>
                {dealerName} {t(language, 'contact.willReachOut')}
              </>
            ) : (
              <>{t(language, 'contact.weWillReachOut')}</>
            )}
          </>
        ),
      });
    } catch (error) {
      setState({
        status: 'error',
        message: error instanceof Error ? error.message : t(language, 'contact.genericError'),
      });
    }
  };

  const isSubmitting = state.status === 'submitting';

  return (
    <section className="contact" aria-labelledby="contact-heading" id="contact-us">
      <div className="contact__inner">
        <div className="contact__intro">
          <span className="eyebrow">{t(language, 'contact.eyebrow')}</span>
          <h2 id="contact-heading">{t(language, 'contact.heading')}</h2>
          <p>{t(language, 'contact.description')}</p>
        </div>
        <form className="contact__form" onSubmit={handleSubmit} noValidate>
          <div className="contact__field">
            <label htmlFor="contact-name">{t(language, 'contact.nameLabel')}</label>
            <input
              type="text"
              id="contact-name"
              name="name"
              autoComplete="name"
              required
              disabled={isSubmitting}
            />
          </div>
          <div className="contact__field">
            <label htmlFor="contact-email">{t(language, 'contact.emailLabel')}</label>
            <input
              type="email"
              id="contact-email"
              name="email"
              autoComplete="email"
              required
              disabled={isSubmitting}
            />
          </div>
          <div className="contact__field">
            <label htmlFor="contact-phone">{t(language, 'contact.phoneLabel')}</label>
            <input
              type="tel"
              id="contact-phone"
              name="phone"
              autoComplete="tel"
              placeholder={t(language, 'contact.phonePlaceholder')}
              value={phone}
              onChange={handlePhoneChange}
              disabled={isSubmitting}
            />
          </div>
          {/* Honeypot field - hidden from humans, bots will fill it */}
          <div
            aria-hidden="true"
            style={{
              position: 'absolute',
              left: '-9999px',
              top: '-9999px',
              opacity: 0,
              pointerEvents: 'none',
            }}
          >
            <label htmlFor="contact-website">Website</label>
            <input
              type="text"
              id="contact-website"
              name="website"
              tabIndex={-1}
              autoComplete="off"
            />
          </div>
          <div className="contact__field contact__field--textarea">
            <label htmlFor="contact-message">{t(language, 'contact.messageLabel')}</label>
            <textarea
              id="contact-message"
              name="message"
              rows={4}
              required
              disabled={isSubmitting}
            />
          </div>
          {/* Cloudflare Turnstile widget */}
          <div className="contact__turnstile" ref={turnstileRef} />
          <button
            className="contact__submit"
            type="submit"
            disabled={isSubmitting || !isTurnstileVerified}
          >
            {isSubmitting ? t(language, 'contact.submitting') : t(language, 'contact.submitButton')}
          </button>
          <p
            className={`contact__feedback contact__feedback--${state.status}`}
            aria-live="polite"
            role="status"
          >
            {state.message}
          </p>
        </form>
      </div>
    </section>
  );
}
