"use client"

import { useState } from 'react'
import type { NewsletterSubscribeData } from '@/lib/strapi/types'
import { submitForm } from '@/lib/forms/submitForm'

const ArrowIcon = () => (
  <svg width="6" height="12" viewBox="0 0 6 12" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M1 1L5 6L1 11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
)

export default function NewsletterSubscribeSection({ data }: { data?: NewsletterSubscribeData } = {}) {
  const heading = data?.heading ?? 'Subscribe to Our Newsletter'
  const description = data?.description ?? 'Receive the latest updates delivered straight to your inbox every month.'
  const emailPlaceholder = data?.emailPlaceholder ?? 'Email ID '
  const ctaLabel = data?.ctaLabel ?? 'Subscribe'
  const [email, setEmail] = useState('')
  const [company, setCompany] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle')
  const [message, setMessage] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setStatus('idle')
    setMessage('')
    setIsSubmitting(true)
    try {
      const res = await submitForm('/api/newsletter', { email, company })
      if (res.ok) {
        setStatus('success')
        setMessage(res.alreadySubscribed ? "You're already subscribed!" : 'Thank you for subscribing!')
        setEmail('')
      } else {
        setMessage(res.message ?? 'Something went wrong. Please try again.')
        setStatus('error')
      }
    } catch {
      setMessage('Something went wrong. Please try again.')
      setStatus('error')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <section className="bg-white">
      <div className="max-w-[1440px] mx-auto px-5 lg:px-[72px] pb-10 lg:pb-16">
        <div
          className="nl-box relative overflow-hidden rounded-[16px] p-5 lg:p-16 flex flex-col lg:flex-row lg:items-end lg:justify-between gap-7 lg:gap-10"
          style={{ background: 'radial-gradient(ellipse at bottom center, rgba(255,232,233,1), rgba(255,232,233,0) 70%), linear-gradient(90deg, #fff 0%, #fff 100%)',
          }}
        >
          {/* Left: Text content */}
          <div className="relative z-10 flex flex-col gap-2 shrink-0">
            <h2
              className="nl-heading text-[#2a3036] text-[32px] lg:text-[54px] leading-[41px] lg:leading-[62px] tracking-[-0.64px] lg:tracking-[-1.08px] w-full lg:w-[377px]"
            >
              {heading}
            </h2>
            <p
              className="nl-desc text-[#4a5565] lg:text-[rgba(42,48,54,0.6)] text-[14px] lg:text-[16px] leading-[24px] lg:leading-[1.5] w-full lg:w-[350px] lg:font-medium"
            >
              {description}
            </p>
          </div>

          {/* Right: Email form */}
          <form
            onSubmit={handleSubmit}
            className="nl-form relative z-10 flex flex-col gap-[25px] lg:gap-6 lg:items-center w-full lg:w-[527px]"
          >
            <input
              type="text"
              name="company"
              value={company}
              onChange={(e) => setCompany(e.target.value)}
              tabIndex={-1}
              autoComplete="off"
              aria-hidden="true"
              className="absolute -left-[9999px] w-px h-px opacity-0"
            />
            <div className="flex flex-col lg:flex-row gap-[25px] lg:gap-6 lg:items-center w-full lg:flex-1">
              <div className="flex-1 border-b border-[rgba(42,48,54,0.2)] pt-3 pb-8 pr-5">
                <input
                  type="email"
                  placeholder={`${emailPlaceholder} *`}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full bg-transparent text-[16px] text-black placeholder:text-[rgba(0,0,0,0.6)] outline-none"
                  required
                />
              </div>
              <button
                type="submit"
                disabled={isSubmitting}
                className="flex items-center bg-[#d20010] rounded-full pl-0.5 py-0.5 shrink-0 w-fit hover:bg-[#b8000e] transition-colors disabled:opacity-70"
              >
                <span
                  className="bg-white rounded-full px-6 py-[7px] lg:py-3 text-[14px] lg:text-[16px] uppercase tracking-[0.28px] lg:tracking-[0.32px] text-[#1c2023]"
                >
                  {isSubmitting ? 'Subscribing...' : ctaLabel}
                </span>
                <span className="flex items-center justify-center w-6 h-6 text-white">
                  <ArrowIcon />
                </span>
              </button>
            </div>
            {status === 'success' ? (
              <p className="text-green-600 text-sm">{message}</p>
            ) : null}
            {status === 'error' ? (
              <p className="text-red-600 text-sm">{message}</p>
            ) : null}
          </form>
        </div>
      </div>
    </section>
  )
}
