"use client"

import { useState } from "react"
import { ChevronDown, Calendar, Clock } from "lucide-react"
import type { WeddingInquiryData } from "@/lib/strapi/types"
import { submitForm } from "@/lib/forms/submitForm"

const FIELD_STYLE: React.CSSProperties = {}

function FormField({ children, className = "" }: { children: React.ReactNode; className?: string }) {
  return (
    <label className={`border-b border-[rgba(16,36,67,0.2)] flex items-start pt-[12px] pb-[32px] pr-[20px] cursor-pointer ${className}`}>
      {children}
    </label>
  )
}

export default function WeddingInquiry({ data }: { data: WeddingInquiryData }) {
  const today = new Date().toISOString().split("T")[0]

  const [form, setForm] = useState({
    fullName: "",
    email: "",
    mobile: "",
    eventType: "",
    eventBudget: "",
    eventDate: "",
    eventTime: "",
    requirements: "",
    company: "",
  })
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitStatus, setSubmitStatus] = useState<"idle" | "success" | "error">("idle")
  const [submitMessage, setSubmitMessage] = useState("")

  const update =
    (field: string) =>
      (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
        setForm((prev) => ({ ...prev, [field]: e.target.value }))

  const updateMobile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value.replace(/[^0-9+]/g, "")
    setForm((prev) => ({ ...prev, mobile: val }))
  }

  const [focusedFields, setFocusedFields] = useState<Record<string, boolean>>({})
  const handleFocus = (field: string) => () => setFocusedFields((prev) => ({ ...prev, [field]: true }))
  const handleBlur = (field: string) => () => setFocusedFields((prev) => ({ ...prev, [field]: false }))

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setSubmitStatus("idle")
    setSubmitMessage("")
    setIsSubmitting(true)
    try {
      const res = await submitForm("/api/wedding-inquiry", form)
      if (res.ok) {
        setSubmitStatus("success")
        setForm({
          fullName: "",
          email: "",
          mobile: "",
          eventType: "",
          eventBudget: "",
          eventDate: "",
          eventTime: "",
          requirements: "",
          company: "",
        })
      } else {
        setSubmitMessage(res.message ?? "Something went wrong. Please try again later.")
        setSubmitStatus("error")
      }
    } catch {
      setSubmitMessage("Something went wrong. Please try again later.")
      setSubmitStatus("error")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <section className="wi-section w-full bg-white px-[16px] md:px-[72px] py-[40px] md:py-[60px]">
      <div className="max-w-[1296px] mx-auto flex flex-col md:flex-row gap-[20px] md:gap-[30px] md:items-center">
        <div className="w-full md:flex-1 h-[338px] md:h-auto md:self-stretch rounded-[12px] overflow-hidden">
          <img
            src={data.image}
            alt="Wedding couple under floral mandap"
            className="w-full h-full object-cover"
          />
        </div>

        <div className="wi-form w-full md:w-[659px] md:shrink-0 bg-[#f9f9f9] rounded-[16px] px-[16px] py-[20px] md:p-[32px] relative overflow-hidden">
          <div className="relative flex flex-col gap-[24px]">
            <h2 className="font-heading text-[#2a3036] text-[32px] md:text-[40px] leading-[36px] md:leading-normal tracking-[-1.08px]">
              {data.heading}
            </h2>

            <form onSubmit={handleSubmit} className="flex flex-col gap-[40px] items-end w-full">
              <input
                type="text"
                name="company"
                value={form.company}
                onChange={update("company")}
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                className="absolute -left-[9999px] w-px h-px opacity-0"
              />
              <div className="flex flex-col gap-[37px] w-full">
                <FormField>
                  <input
                    type="text"
                    placeholder={`${data.fullNamePlaceholder} *`}
                    value={form.fullName}
                    onChange={update("fullName")}
                    className="w-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                    style={FIELD_STYLE}
                  />
                </FormField>

                <FormField className="md:hidden">
                  <input
                    type="tel"
                    placeholder={`${data.mobilePlaceholder} *`}
                    value={form.mobile}
                    onChange={updateMobile}
                    minLength={10}
                    pattern="^[0-9+]{10,}$"
                    title="Please enter a valid mobile number"
                    className="w-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                    style={FIELD_STYLE}
                  />
                </FormField>

                <FormField className="md:hidden">
                  <input
                    type="email"
                    placeholder={`${data.emailPlaceholder} *`}
                    value={form.email}
                    onChange={update("email")}
                    className="w-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                    style={FIELD_STYLE}
                  />
                </FormField>

                <div className="hidden md:flex gap-[24px]">
                  <FormField className="flex-1 min-w-0">
                    <input
                      type="email"
                      placeholder={`${data.emailPlaceholder} *`}
                      value={form.email}
                      onChange={update("email")}
                      className="w-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                      style={FIELD_STYLE}
                    />
                  </FormField>
                  <FormField className="flex-1 min-w-0">
                    <input
                      type="tel"
                      placeholder={`${data.mobilePlaceholder} *`}
                      value={form.mobile}
                      onChange={updateMobile}
                      minLength={10}
                      pattern="^[0-9+]{10,}$"
                      title="Please enter a valid mobile number"
                      className="w-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                      style={FIELD_STYLE}
                    />
                  </FormField>
                </div>

                <FormField className="md:hidden justify-between">
                  <select
                    value={form.eventType}
                    onChange={update("eventType")}
                    className="flex-1 bg-transparent text-[16px] text-black/60 outline-none appearance-none"
                    style={FIELD_STYLE}
                  >
                    <option value="" disabled>{`${data.eventTypePlaceholder} *`}</option>
                    {data.eventTypes.map((t, i) => (
                      <option key={i} value={t}>
                        {t}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="w-[24px] h-[24px] text-black/40 shrink-0" />
                </FormField>

                <FormField className="md:hidden justify-between">
                  <select
                    value={form.eventBudget}
                    onChange={update("eventBudget")}
                    className="flex-1 bg-transparent text-[16px] text-black/60 outline-none appearance-none"
                    style={FIELD_STYLE}
                  >
                    <option value="" disabled>{`${data.eventBudgetPlaceholder} *`}</option>
                    {data.eventBudgets.map((b, i) => (
                      <option key={i} value={b}>
                        {b}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="w-[24px] h-[24px] text-black/40 shrink-0" />
                </FormField>

                <div className="hidden md:flex gap-[24px]">
                  <FormField className="flex-1 min-w-0 justify-between">
                    <select
                      value={form.eventType}
                      onChange={update("eventType")}
                      className="flex-1 bg-transparent text-[16px] text-black/60 outline-none appearance-none"
                      style={FIELD_STYLE}
                    >
                      <option value="" disabled>{`${data.eventTypePlaceholder} *`}</option>
                      {data.eventTypes.map((t, i) => (
                        <option key={i} value={t}>
                          {t}
                        </option>
                      ))}
                    </select>
                    <ChevronDown className="w-[24px] h-[24px] text-black/40 shrink-0" />
                  </FormField>
                  <FormField className="flex-1 min-w-0 justify-between">
                    <select
                      value={form.eventBudget}
                      onChange={update("eventBudget")}
                      className="flex-1 bg-transparent text-[16px] text-black/60 outline-none appearance-none"
                      style={FIELD_STYLE}
                    >
                      <option value="" disabled>{`${data.eventBudgetPlaceholder} *`}</option>
                      {data.eventBudgets.map((b, i) => (
                        <option key={i} value={b}>
                          {b}
                        </option>
                      ))}
                    </select>
                    <ChevronDown className="w-[24px] h-[24px] text-black/40 shrink-0" />
                  </FormField>
                </div>

                <FormField className="md:hidden justify-between">
                  <input
                    type={focusedFields.time || form.eventTime ? "time" : "text"}
                    placeholder={`${data.eventTimePlaceholder} *`}
                    value={form.eventTime}
                    onChange={update("eventTime")}
                    onFocus={handleFocus("time")}
                    onBlur={handleBlur("time")}
                    className="flex-1 bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                    style={FIELD_STYLE}
                  />
                  {!(focusedFields.time || form.eventTime) && (
                    <Clock className="w-[24px] h-[24px] text-black/40 shrink-0" />
                  )}
                </FormField>

                <FormField className="md:hidden justify-between">
                  <input
                    type={focusedFields.date || form.eventDate ? "date" : "text"}
                    placeholder={`${data.eventDatePlaceholder} *`}
                    value={form.eventDate}
                    min={today}
                    onChange={update("eventDate")}
                    onFocus={handleFocus("date")}
                    onBlur={handleBlur("date")}
                    className="flex-1 bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                    style={FIELD_STYLE}
                  />
                  {!(focusedFields.date || form.eventDate) && (
                    <Calendar className="w-[24px] h-[24px] text-black/40 shrink-0" />
                  )}
                </FormField>

                <div className="hidden md:flex gap-[24px]">
                  <FormField className="flex-1 min-w-0 justify-between">
                    <input
                      type={focusedFields.date || form.eventDate ? "date" : "text"}
                      placeholder={`${data.eventDatePlaceholder} *`}
                      value={form.eventDate}
                      min={today}
                      onChange={update("eventDate")}
                      onFocus={handleFocus("date")}
                      onBlur={handleBlur("date")}
                      className="flex-1 bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                      style={FIELD_STYLE}
                    />
                    {!(focusedFields.date || form.eventDate) && (
                      <Calendar className="w-[24px] h-[24px] text-black/40 shrink-0" />
                    )}
                  </FormField>
                  <FormField className="flex-1 min-w-0 justify-between">
                    <input
                      type={focusedFields.time || form.eventTime ? "time" : "text"}
                      placeholder={`${data.eventTimePlaceholder} *`}
                      value={form.eventTime}
                      onChange={update("eventTime")}
                      onFocus={handleFocus("time")}
                      onBlur={handleBlur("time")}
                      className="flex-1 bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none"
                      style={FIELD_STYLE}
                    />
                    {!(focusedFields.time || form.eventTime) && (
                      <Clock className="w-[24px] h-[24px] text-black/40 shrink-0" />
                    )}
                  </FormField>
                </div>

                <label className="border-b border-[rgba(16,36,67,0.2)] flex items-start pt-[12px] pb-[32px] pr-[20px] h-[113px] cursor-pointer w-full">
                  <textarea
                    placeholder={`${data.requirementsPlaceholder} *`}
                    value={form.requirements}
                    onChange={update("requirements")}
                    className="w-full h-full bg-transparent text-[16px] text-black placeholder:text-black/60 outline-none resize-none"
                    style={FIELD_STYLE}
                  />
                </label>
              </div>

              <div className="self-start md:self-end">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="bg-[#d20010] rounded-[66px] flex items-center pl-[2px] py-[2px] hover:bg-[#b8000e] transition-colors disabled:opacity-70"
                >
                  <span
                    className="bg-white rounded-[44px] px-[24px] py-[7px] md:py-[12px] text-[14px] md:text-[16px] font-medium uppercase tracking-[0.32px] text-[#1c2023] whitespace-nowrap"
                    style={FIELD_STYLE}
                  >
                    {isSubmitting ? "Sending..." : data.ctaLabel}
                  </span>
                  <span className="flex items-center justify-center w-[24px] h-[24px] mx-[6px] md:mx-[8px] shrink-0">
                    <svg width="8" height="14" viewBox="0 0 7.5 13.5" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M0.75 0.75C0.75 0.75 6.75 5.169 6.75 6.75C6.75 8.331 0.75 12.75 0.75 12.75"
                        stroke="#FAFAFA"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </span>
                </button>
              </div>
              {submitStatus === "success" ? (
                <p className="text-green-600 text-sm w-full">
                  Thank you! Your inquiry has been received.
                </p>
              ) : null}
              {submitStatus === "error" ? (
                <p className="text-red-600 text-sm w-full">
                  {submitMessage || "Something went wrong. Please try again later."}
                </p>
              ) : null}
            </form>
          </div>
        </div>
      </div>
    </section>
  )
}
