"use client";

import React, { useState } from "react";
import { toast } from "react-toastify";
import { Playfair_Display } from "next/font/google";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import { IoCloseOutline } from "react-icons/io5";

const playfair = Playfair_Display({ subsets: ["latin"] });

type CmsFormField = {
  id: string;
  name: string;
  label: string;
  blockType: "text" | "email" | "textarea" | "number" | "select" | "checkbox" | "phone";
  required?: boolean | null;
  defaultValue?: string | null;
  width?: number | string | null;
};

export type CmsNewsletterForm = {
  id: number;
  title?: string;
  fields: CmsFormField[];
  submitButtonLabel?: string;
  submitButtonId?: string | null;
  confirmationType?: string;
  successMessage?: string;
  redirect?: {
    redirectType?: string;
    url?: string | null;
    slug?: string | null;
  };
};

interface Props {
  form: CmsNewsletterForm;
}

function getInitialValues(fields: CmsFormField[]): Record<string, string> {
  return Object.fromEntries(
    fields.map((f) => [
      f.name,
      f.blockType === "checkbox" ? "false" : (f.defaultValue ?? ""),
    ]),
  );
}

export default function ScillyNewsletterForm({ form }: Props) {
  const [values, setValues] = useState<Record<string, string>>(() =>
    getInitialValues(form.fields),
  );
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle");
  const [successMsg, setSuccessMsg] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [bgTooltipPos, setBgTooltipPos] = useState<{ x: number; y: number } | null>(null);
  const [textTooltipPos, setTextTooltipPos] = useState<{ x: number; y: number } | null>(null);
  const bgTimerRef = React.useRef<NodeJS.Timeout | null>(null);
  const textTimerRef = React.useRef<NodeJS.Timeout | null>(null);

  const validate = () => {
    const newErrors: Record<string, string> = {};
    for (const field of form.fields) {
      if (!field.required) continue;
      const val = values[field.name] ?? "";
      if (field.blockType === "checkbox") {
        if (val !== "true") newErrors[field.name] = `${field.label} is required`;
      } else if (!val.trim()) {
        newErrors[field.name] = `${field.label} is required`;
      } else if (field.blockType === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val.trim())) {
        newErrors[field.name] = "Please enter a valid email";
      }
    }
    return newErrors;
  };

  const handleChange = (name: string, value: string) => {
    setValues((prev) => ({ ...prev, [name]: value }));
    setErrors((prev) => ({ ...prev, [name]: "" }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const validationErrors = validate();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }

    setStatus("submitting");

    const payload = {
      form: String(form.id),
      submissionData: form.fields.map((f) => ({
        field: f.name,
        value: values[f.name] ?? "",
      })),
    };

    try {
      const res = await fetch("/api/scilly/newsletter", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        setStatus("error");
        toast.error("Failed to submit. Please try again.");
        return;
      }

      const data = await res.json();
      const msg = data.message || form.successMessage || "Successfully submitted!";
      setSuccessMsg(msg);
      setStatus("success");
      setShowModal(true);
      setValues(getInitialValues(form.fields));

      if (form.confirmationType === "redirect" && form.redirect) {
        const { slug, url } = form.redirect;
        if (slug) {
          window.history.pushState({}, "", `/${slug}`);
        } else if (url) {
          window.location.href = url;
        }
      }
    } catch {
      setStatus("error");
    }
  };

  return (
    <>
      <form
        onSubmit={handleSubmit}
        noValidate
        className="grid w-full gap-6 sm:grid-cols-2 lg:grid-cols-[minmax(160px,1fr)_minmax(160px,1fr)_minmax(180px,1fr)_minmax(180px,1fr)] lg:items-end xl:gap-10"
      >
        {form.fields.map((field) => {
          if (field.blockType === "checkbox") {
            return (
              <div key={field.id} className="col-span-full mt-2 flex items-start gap-4">
                <div className="relative flex h-8 w-8 shrink-0 items-center justify-center">
                  <input
                    type="checkbox"
                    id={`form-${field.name}`}
                    checked={values[field.name] === "true"}
                    onChange={(e) =>
                      handleChange(field.name, e.target.checked ? "true" : "false")
                    }
                    className="peer h-8 w-8 cursor-pointer appearance-none rounded border-2 border-white/40 bg-transparent transition-all checked:bg-white checked:border-white"
                  />
                  <svg
                    className="pointer-events-none absolute h-5 w-5 text-black opacity-0 peer-checked:opacity-100"
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="4"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                </div>
                <label
                  htmlFor={`form-${field.name}`}
                  className="mt-1 cursor-pointer text-[13px] leading-tight text-white/70 transition hover:text-white"
                >
                  {field.label}
                </label>
                {errors[field.name] && (
                  <p className="mt-1 text-[11px] text-red-400">{errors[field.name]}</p>
                )}
              </div>
            );
          }

          const inputType =
            field.blockType === "email"
              ? "email"
              : field.blockType === "phone"
                ? "tel"
                : field.blockType === "number"
                  ? "number"
                  : "text";

          const colSpan =
            field.blockType === "email" || field.blockType === "phone"
              ? "sm:col-span-2 lg:col-span-1"
              : "";

          return (
            <div key={field.id} className={`min-w-0 ${colSpan}`}>
              <input
                id={`form-${field.name}`}
                type={inputType}
                placeholder={field.label}
                value={values[field.name] ?? ""}
                onChange={(e) => handleChange(field.name, e.target.value)}
                className="w-full border-b border-white/20 bg-transparent pb-[10px] text-[13px] text-white outline-none placeholder:text-white/80"
              />
              {errors[field.name] && (
                <p className="mt-1 text-[11px] text-red-400">{errors[field.name]}</p>
              )}
            </div>
          );
        })}

        <div className="col-span-full flex justify-center lg:justify-start">
          <button
            type="submit"
            id={form.submitButtonId ?? undefined}
            disabled={status === "submitting"}
            className="h-[40px] min-w-[140px] rounded-full bg-[#85714D] px-10 text-[14px] font-medium text-white transition hover:bg-[#85714D] active:scale-95 disabled:opacity-50"
          >
            {status === "submitting" ? "Sending..." : (form.submitButtonLabel || "Submit")}
          </button>
        </div>

        {status === "error" && (
          <p className="col-span-full text-[11px] text-red-400">
            Something went wrong. Please try again.
          </p>
        )}
      </form>

      <AnimatePresence>
        {showModal && (
          <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setShowModal(false)}
              className="absolute inset-0 bg-black/70 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-[700px] overflow-hidden rounded-[24px] bg-[#1E1E1E] shadow-2xl shadow-black/50"
            >
              <div
                className="absolute inset-0 z-0"
                onMouseMove={(e) => { 
                  const r = e.currentTarget.getBoundingClientRect(); 
                  const x = e.clientX - r.left;
                  const y = e.clientY - r.top;
                  if (bgTimerRef.current) clearTimeout(bgTimerRef.current);
                  setBgTooltipPos((prev) => (prev !== null ? null : prev));
                  bgTimerRef.current = setTimeout(() => setBgTooltipPos({ x, y }), 1000);
                }}
                onMouseLeave={() => {
                  if (bgTimerRef.current) clearTimeout(bgTimerRef.current);
                  setBgTooltipPos(null);
                }}
              >
                <Image
                  src="/scilly/Thank you Page.png"
                  alt="Thank you background"
                  fill
                  className="object-cover opacity-60 brightness-75"
                  priority
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
                <AnimatePresence>
                  {bgTooltipPos && (
                    <motion.div
                      initial={{ opacity: 0, scale: 0.95 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                      transition={{ duration: 0.12 }}
                      style={{
                        position: "absolute",
                        left: bgTooltipPos.x,
                        top: bgTooltipPos.y,
                        transform: "translate(-50%, calc(-100% - 8px))",
                        pointerEvents: "none",
                        zIndex: 200,
                        whiteSpace: "nowrap",
                      }}
                      className="rounded border border-black bg-white px-3 py-1.5 text-sm font-semibold text-black shadow-sm"
                    >
                      Thank you background
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              <div className="relative z-10 flex flex-col items-center px-6 py-20 text-center text-white sm:px-12 sm:py-24">
                <button
                  onClick={() => setShowModal(false)}
                  className="absolute right-6 top-6 flex h-10 w-10 items-center justify-center rounded-full border border-white/20 bg-black/20 text-white backdrop-blur-md transition hover:bg-white hover:text-black"
                >
                  <IoCloseOutline size={28} />
                </button>

                <div
                  className="relative flex flex-col items-center"
                  onMouseMove={(e) => { 
                    const r = e.currentTarget.getBoundingClientRect(); 
                    const x = e.clientX - r.left;
                    const y = e.clientY - r.top;
                    if (textTimerRef.current) clearTimeout(textTimerRef.current);
                    setTextTooltipPos((prev) => (prev !== null ? null : prev));
                    textTimerRef.current = setTimeout(() => setTextTooltipPos({ x, y }), 1000);
                  }}
                  onMouseLeave={() => {
                    if (textTimerRef.current) clearTimeout(textTimerRef.current);
                    setTextTooltipPos(null);
                  }}
                >
                  <Image
                    src="/scilly/text-1-thank-you.png"
                    alt="Thank You"
                    width={320}
                    height={120}
                    className="h-auto w-[240px] sm:w-[320px] object-contain"
                  />
                  <AnimatePresence>
                    {textTooltipPos && (
                      <motion.div
                        initial={{ opacity: 0, scale: 0.95 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.95 }}
                        transition={{ duration: 0.12 }}
                        style={{
                          position: "absolute",
                          left: textTooltipPos.x,
                          top: textTooltipPos.y,
                          transform: "translate(-50%, calc(-100% - 8px))",
                          pointerEvents: "none",
                          zIndex: 200,
                          whiteSpace: "nowrap",
                        }}
                        className="rounded border border-black bg-white px-3 py-1.5 text-sm font-semibold text-black shadow-sm"
                      >
                        Thank You
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>

                <div className={`${playfair.className} mt-8 whitespace-pre-line flex flex-col gap-2`}>
                  <p className="text-[18px] font-medium tracking-[0.02em] text-white sm:text-[22px]">
                    {successMsg}
                  </p>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </>
  );
}