'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

interface FormData {
  firstName: string
  lastName: string
  email: string
  postcode: string
  consent: boolean
  updates: boolean
}

const INITIAL: FormData = {
  firstName: '',
  lastName: '',
  email: '',
  postcode: '',
  consent: false,
  updates: false,
}

// Set NEXT_PUBLIC_POWER_AUTOMATE_URL in .env.local (see README.md for setup guide)
const POWER_AUTOMATE_URL =
  process.env.NEXT_PUBLIC_POWER_AUTOMATE_URL ?? 'YOUR_POWER_AUTOMATE_HTTP_TRIGGER_URL'

export default function LeadCaptureForm() {
  const router = useRouter()
  const [form, setForm]       = useState<FormData>(INITIAL)
  const [errors, setErrors]   = useState<Partial<FormData>>({})
  const [loading, setLoading] = useState(false)
  const [submitErr, setSubmitErr] = useState('')

  const validate = (): boolean => {
    const e: Record<string, string> = {}
    if (!form.firstName.trim()) e.firstName = 'Please enter your first name.'
    if (!form.lastName.trim())  e.lastName  = 'Please enter your last name.'
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      e.email = 'Please enter a valid email address.'
    if (!form.postcode.trim()) e.postcode = 'Please enter your postcode.'
    if (!form.consent) e.consent = 'You must agree to continue.'
    setErrors(e as Partial<FormData>)
    return Object.keys(e).length === 0
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    setForm(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }))
    if (errors[name as keyof FormData]) {
      setErrors(prev => ({ ...prev, [name]: undefined }))
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validate()) return
    setLoading(true)
    setSubmitErr('')

    try {
      const payload = {
        firstName:  form.firstName.trim(),
        lastName:   form.lastName.trim(),
        email:      form.email.trim().toLowerCase(),
        postcode:   form.postcode.trim().toUpperCase(),
        consent:    form.consent,
        updates:    form.updates,
        source:     'Plymouth Metro Website',
        submittedAt: new Date().toISOString(),
      }

      // Submit to Power Automate / SharePoint
      await fetch(POWER_AUTOMATE_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
    } catch {
      // If endpoint not yet configured, we still proceed to thank-you
      // Remove this catch block and show an error once the endpoint is live
    }

    router.push('/thank-you')
  }

  return (
    <form
      onSubmit={handleSubmit}
      noValidate
      className="space-y-5"
      aria-label="Petition sign-up form"
    >
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label htmlFor="firstName" className="block text-sm font-medium text-metro-navy mb-1.5">
            First name <span className="text-red-500" aria-hidden="true">*</span>
          </label>
          <input
            id="firstName"
            name="firstName"
            type="text"
            autoComplete="given-name"
            value={form.firstName}
            onChange={handleChange}
            className={`input-field ${errors.firstName ? 'border-red-400 ring-red-200' : ''}`}
            aria-required="true"
            aria-describedby={errors.firstName ? 'firstName-err' : undefined}
          />
          {errors.firstName && (
            <p id="firstName-err" role="alert" className="mt-1 text-xs text-red-600">
              {errors.firstName}
            </p>
          )}
        </div>

        <div>
          <label htmlFor="lastName" className="block text-sm font-medium text-metro-navy mb-1.5">
            Last name <span className="text-red-500" aria-hidden="true">*</span>
          </label>
          <input
            id="lastName"
            name="lastName"
            type="text"
            autoComplete="family-name"
            value={form.lastName}
            onChange={handleChange}
            className={`input-field ${errors.lastName ? 'border-red-400' : ''}`}
            aria-required="true"
            aria-describedby={errors.lastName ? 'lastName-err' : undefined}
          />
          {errors.lastName && (
            <p id="lastName-err" role="alert" className="mt-1 text-xs text-red-600">
              {errors.lastName}
            </p>
          )}
        </div>
      </div>

      <div>
        <label htmlFor="email" className="block text-sm font-medium text-metro-navy mb-1.5">
          Email address <span className="text-red-500" aria-hidden="true">*</span>
        </label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="email"
          value={form.email}
          onChange={handleChange}
          className={`input-field ${errors.email ? 'border-red-400' : ''}`}
          aria-required="true"
          aria-describedby={errors.email ? 'email-err' : undefined}
        />
        {errors.email && (
          <p id="email-err" role="alert" className="mt-1 text-xs text-red-600">
            {errors.email}
          </p>
        )}
      </div>

      <div>
        <label htmlFor="postcode" className="block text-sm font-medium text-metro-navy mb-1.5">
          Postcode <span className="text-red-500" aria-hidden="true">*</span>
        </label>
        <input
          id="postcode"
          name="postcode"
          type="text"
          autoComplete="postal-code"
          value={form.postcode}
          onChange={handleChange}
          className={`input-field max-w-[200px] ${errors.postcode ? 'border-red-400' : ''}`}
          aria-required="true"
          aria-describedby={errors.postcode ? 'postcode-err' : undefined}
          placeholder="e.g. PL1 1AA"
        />
        {errors.postcode && (
          <p id="postcode-err" role="alert" className="mt-1 text-xs text-red-600">
            {errors.postcode}
          </p>
        )}
      </div>

      <div className="space-y-3 pt-1">
        <label className="flex items-start gap-3 cursor-pointer group">
          <input
            name="consent"
            type="checkbox"
            checked={form.consent}
            onChange={handleChange}
            className="mt-0.5 w-4 h-4 rounded border-metro-border text-metro-sky
                       focus:ring-metro-sky flex-shrink-0"
            aria-required="true"
          />
          <span className="text-sm text-metro-muted group-hover:text-metro-navy transition-colors">
            I agree that my details will be stored securely and used solely for this campaign.
            I have read the{' '}
            <a href="/privacy" className="text-metro-sky underline hover:no-underline">
              Privacy Policy
            </a>
            . <span className="text-red-500" aria-hidden="true">*</span>
          </span>
        </label>
        {(errors as Record<string, string>).consent && (
          <p role="alert" className="text-xs text-red-600 pl-7">
            {(errors as Record<string, string>).consent}
          </p>
        )}

        <label className="flex items-start gap-3 cursor-pointer group">
          <input
            name="updates"
            type="checkbox"
            checked={form.updates}
            onChange={handleChange}
            className="mt-0.5 w-4 h-4 rounded border-metro-border text-metro-sky
                       focus:ring-metro-sky flex-shrink-0"
          />
          <span className="text-sm text-metro-muted group-hover:text-metro-navy transition-colors">
            Yes, I'd like to receive campaign updates and news about Plymouth Metro by email.
            You can unsubscribe at any time.
          </span>
        </label>
      </div>

      {submitErr && (
        <p role="alert" className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-4 py-3">
          {submitErr}
        </p>
      )}

      <button
        type="submit"
        disabled={loading}
        className="w-full btn-primary py-4 text-base disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {loading ? (
          <>
            <svg className="animate-spin w-5 h-5" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
            Submitting…
          </>
        ) : (
          <>
            <svg viewBox="0 0 20 20" fill="currentColor" className="w-5 h-5" aria-hidden="true">
              <path fillRule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clipRule="evenodd" />
            </svg>
            Add My Name to the Petition
          </>
        )}
      </button>

      <p className="text-xs text-metro-muted text-center">
        Your details are held securely and never sold to third parties.
      </p>
    </form>
  )
}
