import { useState, useEffect } from 'react';
import { submitLead } from '@/utils/lead-submit';
import { TurnstileBox } from '@shared/turnstile';
import { pushEnhancedConversions, trackFormSubmit } from '@/lib/analytics';
import SuburbPostcodeCombobox from '@/components/SuburbPostcodeCombobox';
import MultiSelect from '@/components/MultiSelect';

interface FormData {
  fullName: string;
  email: string;
  phone: string;
  suburbPostcode: string;
  suburb: string;
  state: string;
  postcode: string;
  servicesRequired: string[];
  additionalInfo: string;
  whoAreYou: "Participant" | "Family" | "Support Coordinator" | "Other";
  preferredContactMethod: "Call" | "SMS" | "Email";
  preferredContactTime: string;
  consent: boolean;
  utm_source: string;
  utm_medium: string;
  utm_campaign: string;
  utm_term: string;
  utm_content: string;
  gclid: string;
  msclkid: string;
  referrer_path: string;
  page_path: string;
}

const LeadForm = () => {
  const [formData, setFormData] = useState<FormData>({
    fullName: '',
    email: '',
    phone: '',
    suburbPostcode: '',
    suburb: '',
    state: '',
    postcode: '',
    servicesRequired: [],
    additionalInfo: '',
    whoAreYou: 'Participant',
    preferredContactMethod: 'Call',
    preferredContactTime: '',
    consent: false,
    utm_source: '',
    utm_medium: '',
    utm_campaign: '',
    utm_term: '',
    utm_content: '',
    gclid: '',
    msclkid: '',
    referrer_path: '',
    page_path: ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    // Capture URL parameters and referrer on component mount
    const urlParams = new URLSearchParams(window.location.search);
    setFormData(prev => ({
      ...prev,
      utm_source: urlParams.get('utm_source') || '',
      utm_medium: urlParams.get('utm_medium') || '',
      utm_campaign: urlParams.get('utm_campaign') || '',
      utm_term: urlParams.get('utm_term') || '',
      utm_content: urlParams.get('utm_content') || '',
      gclid: urlParams.get('gclid') || '',
      msclkid: urlParams.get('msclkid') || '',
      referrer_path: document.referrer || '',
      page_path: window.location.pathname
    }));
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
    }));
  };

  const handleServicesChange = (services: string[]) => {
    setFormData(prev => ({
      ...prev,
      servicesRequired: services
    }));
  };

  const validateForm = (): string | null => {
    if (!formData.fullName.trim()) return 'Full name is required';
    if (!formData.email.trim()) return 'Email is required';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) return 'Valid email is required';
    if (!formData.phone.trim()) return 'Phone number is required';
    // AU phone validation
    const cleanPhone = formData.phone.replace(/[^\d+]/g, "");
    const auPhoneRegex = /^(?:\+?61|0)(?:4\d{8}|[2378]\d{8})$/;
    if (!auPhoneRegex.test(cleanPhone)) return 'Please enter a valid Australian phone number';
    if (!formData.suburbPostcode.trim()) return 'Suburb/postcode is required';
    // Validate structured fields are captured
    if (!formData.suburb || !formData.postcode || !formData.state) {
      // Analytics for error
      if ((window as any).dataLayer) {
        (window as any).dataLayer.push({ event: 'suburb_select_error' });
      }
      return 'Please select a valid suburb from the list so we can capture your postcode and state.';
    }
    if (!formData.servicesRequired || formData.servicesRequired.length === 0) return 'Please select at least one service';
    if (!formData.consent) return 'You must agree to be contacted';
    return null;
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    
    const validationError = validateForm();
    if (validationError) {
      setErrorMessage(validationError);
      setSubmitStatus('error');
      return;
    }

    setIsSubmitting(true);
    setSubmitStatus('idle');
    setErrorMessage('');

    try {
      // Check if user has consented to analytics
      const consent = localStorage.getItem('consent');
      if (consent === 'accepted') {
        await pushEnhancedConversions(formData.email, formData.phone);
        trackFormSubmit();
      }

      console.log('Submitting form with data:', formData);
      await submitLead(formData);

      setSubmitStatus('success');
      // Redirect to thank you page
      window.location.href = '/thank-you?from=ndis-cleaning-melbourne';
    } catch (error) {
      console.error('Form submission error:', error);
      // Show the server's own message (e.g. the "I am human" check) when there is one.
      const serverMessage = error instanceof Error && /^Please /.test(error.message) ? error.message : '';
      setErrorMessage(serverMessage || 'Failed to submit form. Please try again or call us directly.');
      setSubmitStatus('error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const services = [
    'Garden Maintenance',
    'Green Waste',
    'Gutter Cleaning',
    'Pressure Wash',
    'Windows Cleaning',
    'Others (Specify in Additional Information)'
  ];

  return (
    <div className="usp-card max-w-2xl mx-auto">
      <h2 className="text-2xl font-bold mb-6 text-foreground">Please tell us a bit about yourself!</h2>
      
      <form onSubmit={handleSubmit} className="grid gap-4">
        {/* Honeypot field */}
        <input 
          type="text" 
          name="zx_hp" 
          style={{ display: 'none' }} 
          tabIndex={-1} 
          autoComplete="off" 
        />
        
        {/* Who are you? */}
        <fieldset className="mb-4">
          <legend className="block text-sm font-medium text-foreground mb-2">Who are you? *</legend>
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
            {(["Participant", "Family", "Support Coordinator", "Other"] as const).map((label) => (
              <label key={label} className="flex items-center gap-2 rounded-md border border-border p-2 cursor-pointer">
                <input 
                  type="radio" 
                  name="whoAreYou" 
                  value={label} 
                  checked={formData.whoAreYou === label}
                  onChange={handleInputChange}
                  required 
                />
                <span className="text-sm text-black">{label}</span>
              </label>
            ))}
          </div>
        </fieldset>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="fullName" className="block text-sm font-medium text-foreground mb-1">
              Full Name *
            </label>
            <input
              type="text"
              id="fullName"
              name="fullName"
              value={formData.fullName}
              onChange={handleInputChange}
              className="form-input"
              required
              placeholder="Your full name"
              aria-describedby="name-error"
            />
          </div>
          
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-foreground mb-1">
              Email Address *
            </label>
            <input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              onChange={handleInputChange}
              className="form-input"
              required
              placeholder="you@example.com"
              aria-describedby="email-error"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="phone" className="block text-sm font-medium text-foreground mb-1">
              Phone Number *
            </label>
            <input
              type="tel"
              id="phone"
              name="phone"
              value={formData.phone}
              onChange={handleInputChange}
              className="form-input"
              required
              inputMode="tel"
              placeholder="e.g. 04xxxxxxxx"
              pattern="^(?:\+?61|0)(?:4\d{8}|[2378]\d{8})$"
              title="Enter an Australian number (mobile 04xxxxxxxx or landline 0xxxxxxxxx)"
              aria-describedby="phone-error"
            />
          </div>
          
          <div>
            <SuburbPostcodeCombobox
              label="Suburb/Postcode"
              required
              onSelect={(loc) => {
                setFormData(prev => ({
                  ...prev,
                  suburbPostcode: `${loc.suburb}, ${loc.state} ${loc.postcode}`,
                  suburb: loc.suburb,
                  postcode: loc.postcode,
                  state: loc.state
                }));
                // analytics
                if ((window as any).dataLayer) {
                  (window as any).dataLayer.push({ 
                    event: 'suburb_selected', 
                    suburb: loc.suburb, 
                    postcode: loc.postcode, 
                    state: loc.state 
                  });
                }
              }}
              initialValue={formData.suburbPostcode}
            />
            {/* Hidden structured fields for backend */}
            <input type="hidden" name="suburb" value={formData.suburb} />
            <input type="hidden" name="postcode" value={formData.postcode} />
            <input type="hidden" name="state" value={formData.state} />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Service(s) Required *
            </label>
            <MultiSelect
              options={services}
              selectedValues={formData.servicesRequired}
              onChange={handleServicesChange}
              placeholder="Select one or more services"
              className="w-full"
            />
          </div>
          
          <div>
            <label htmlFor="preferredContactTime" className="block text-sm font-medium text-foreground mb-1">
              Preferred Contact Time
            </label>
            <input
              type="text"
              id="preferredContactTime"
              name="preferredContactTime"
              value={formData.preferredContactTime}
              onChange={handleInputChange}
              className="form-input"
              placeholder="e.g. Weekday mornings"
            />
          </div>
        </div>

        {/* Preferred Contact Method */}
        <fieldset className="mb-4">
          <legend className="block text-sm font-medium text-foreground mb-2">Preferred Contact Method</legend>
          <div className="grid grid-cols-3 gap-2">
            {(["Call", "SMS", "Email"] as const).map((method) => (
              <label key={method} className="flex items-center gap-2 rounded-md border border-border p-2 cursor-pointer">
                <input 
                  type="radio" 
                  name="preferredContactMethod" 
                  value={method} 
                  checked={formData.preferredContactMethod === method}
                  onChange={handleInputChange}
                />
                <span className="text-sm text-black">{method}</span>
              </label>
            ))}
          </div>
        </fieldset>

        <div>
          <label htmlFor="additionalInfo" className="block text-sm font-medium text-foreground mb-1">
            Additional Information
          </label>
          <textarea
            id="additionalInfo"
            name="additionalInfo"
            value={formData.additionalInfo}
            onChange={handleInputChange}
            rows={4}
            className="form-textarea"
            placeholder="Tell us about your specific needs, preferred schedule, or any questions..."
          />
        </div>

        <div className="flex items-start gap-2">
          <input
            type="checkbox"
            id="consent"
            name="consent"
            checked={formData.consent}
            onChange={handleInputChange}
            className="mt-1"
            required
            aria-describedby="consent-error"
          />
          <label htmlFor="consent" className="text-sm text-foreground">
            By submitting, you agree to our <a href="/privacy-policy" className="text-primary hover:underline">Privacy Policy</a> and to be contacted about your enquiry. *
          </label>
        </div>

        {submitStatus === 'error' && (
          <div 
            className="p-3 bg-destructive/10 border border-destructive/20 rounded-md text-destructive"
            role="alert"
            aria-live="assertive"
          >
            {errorMessage}
          </div>
        )}

        <TurnstileBox />

        <button
          type="submit"
          disabled={isSubmitting}
          className="btn-primary w-full"
          aria-describedby="submit-status"
        >
          {isSubmitting ? 'Submitting...' : 'Submit Enquiry'}
        </button>
      </form>

      <p className="text-xs text-muted-foreground mt-4 text-center">
        Your information is secure and will only be used to contact you about NDIS gardening services.
      </p>
    </div>
  );
};

export default LeadForm;