"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import {
  IconArrowRight,
  IconArrowsExchange2,
  IconBriefcase,
  IconBrowser,
  IconCheckbox,
  IconDots,
  IconGauge,
  IconInfoCircle,
  IconLoader2,
  IconShoppingCart,
  IconX,
} from "@tabler/icons-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm, useWatch } from "react-hook-form";
import {
  type ContactFormData,
  type ContactFormProps,
  type ContactFormResponse,
  createContactFormSchema,
} from "@/data/contact-form";
import { Link } from "@/i18n/navigation";

const PERSONAL_EMAIL_RE =
  /@(gmail|yahoo|hotmail|outlook|aol|icloud|live|me)\./i;

const projectTypeConfig = [
  {
    value: "headless-migration",
    labelKey: "projectTypeHeadless",
    descKey: "projectTypeHeadlessDesc",
    Icon: IconArrowsExchange2,
  },
  {
    value: "performance-audit",
    labelKey: "projectTypeAudit",
    descKey: "projectTypeAuditDesc",
    Icon: IconGauge,
  },
  {
    value: "ecommerce-shopify",
    labelKey: "projectTypeEcommerce",
    descKey: "projectTypeEcommerceDesc",
    Icon: IconShoppingCart,
  },
  {
    value: "marketing-site",
    labelKey: "projectTypeMarketing",
    descKey: "projectTypeMarketingDesc",
    Icon: IconBrowser,
  },
  {
    value: "technical-consulting",
    labelKey: "projectTypeConsulting",
    descKey: "projectTypeConsultingDesc",
    Icon: IconBriefcase,
  },
  {
    value: "other",
    labelKey: "projectTypeOther",
    descKey: "projectTypeOtherDesc",
    Icon: IconDots,
  },
] as const;

export function ContactForm({
  title,
  subtitle,
  variant = "default",
  className = "",
}: ContactFormProps) {
  const t = useTranslations("contact");

  const displayTitle = title ?? t("title");
  const displaySubtitle = subtitle ?? t("subtitle");

  const schema = createContactFormSchema({
    fullNameRequired: t("validationFullNameRequired"),
    fullNameTooLong: t("validationFullNameTooLong"),
    emailRequired: t("validationEmailRequired"),
    emailInvalid: t("validationEmailInvalid"),
    websiteRequired: t("validationWebsiteRequired"),
    websiteInvalid: t("validationWebsiteInvalid"),
    websiteTooLong: t("validationWebsiteTooLong"),
    projectTypeRequired: t("validationProjectTypeRequired"),
    projectTypeInvalid: t("validationProjectTypeInvalid"),
    messageTooLong: t("validationMessageTooLong"),
  });

  const {
    register,
    handleSubmit,
    control,
    formState: { errors },
    reset,
  } = useForm<ContactFormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      email: "",
      website: "",
      fullName: "",
      projectType: "",
      message: "",
    },
  });

  const watchedEmail = useWatch({ control, name: "email" });
  const showPersonalEmailHint =
    typeof watchedEmail === "string" &&
    watchedEmail.length > 0 &&
    PERSONAL_EMAIL_RE.test(watchedEmail);

  const [isLoading, setIsLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const onSubmit = async (data: ContactFormData) => {
    setIsLoading(true);
    setSuccessMessage(null);
    setErrorMessage(null);

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      const result: ContactFormResponse = await response.json();

      if (!(response.ok && result.success)) {
        setErrorMessage(result.message || t("errorSending"));
        return;
      }

      setSuccessMessage(result.message);
      reset();
    } catch (error) {
      console.error("Network error:", error);
      setErrorMessage(t("errorGeneric"));
    } finally {
      setIsLoading(false);
    }
  };

  const containerPadding =
    variant === "compact" ? "p-4 sm:p-6 lg:p-8" : "p-4 sm:p-6 lg:p-12";

  return (
    <section
      className={`bg-gradient-to-br from-[#000] to-[#1A2428] py-12 sm:py-24 md:py-32 ${className}`}
    >
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        <div className="mx-auto max-w-4xl">
          <div className="mb-8 text-center md:mb-12">
            <h2 className="mb-4 font-bold text-2xl text-white sm:text-3xl md:mb-6 md:text-4xl lg:text-5xl">
              {displayTitle}
            </h2>
            <p className="mx-auto max-w-3xl text-base text-neutral-300 leading-relaxed md:text-lg">
              {displaySubtitle}
            </p>
          </div>

          <div
            className={`rounded-2xl border border-white/10 bg-white/5 shadow-sm backdrop-blur-sm ${containerPadding}`}
          >
            {successMessage && (
              <div className="mb-8 rounded-xl border border-green-200/20 bg-green-50/10 p-6">
                <div className="flex items-start">
                  <IconCheckbox
                    className="mt-0.5 mr-3 h-6 w-6 shrink-0 text-green-400"
                    strokeWidth={1.5}
                  />
                  <div>
                    <h3 className="mb-1 font-semibold text-green-300">
                      {t("successTitle")}
                    </h3>
                    <p className="text-green-400 text-sm">
                      {t("successMessage")}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {errorMessage && (
              <div className="mb-8 rounded-xl border border-red-200/20 bg-red-50/10 p-6">
                <div className="flex items-start">
                  <IconX
                    className="mt-0.5 mr-3 h-6 w-6 shrink-0 text-red-400"
                    strokeWidth={1.5}
                  />
                  <div>
                    <h3 className="mb-1 font-semibold text-red-300">
                      {t("errorTitle")}
                    </h3>
                    <p className="text-red-400 text-sm">{errorMessage}</p>
                  </div>
                </div>
              </div>
            )}

            <form className="space-y-8" onSubmit={handleSubmit(onSubmit)}>
              {/* 1. Email */}
              <div className="space-y-2">
                <label
                  className="block font-medium text-sm text-white"
                  htmlFor="email"
                >
                  {t("email")} <span className="text-[#FD105E]">*</span>
                </label>
                <input
                  autoComplete="email"
                  id="email"
                  type="email"
                  {...register("email")}
                  className="w-full rounded-xl border border-white/20 bg-white/5 px-4 py-3 text-white placeholder-neutral-400 transition-all duration-300 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-[#FD105E]"
                  disabled={isLoading}
                  placeholder={t("emailPlaceholder")}
                />
                {showPersonalEmailHint && !errors.email && (
                  <p className="flex items-center gap-1.5 text-neutral-300 text-xs">
                    <IconInfoCircle
                      className="h-4 w-4 shrink-0 text-[#FD105E]"
                      strokeWidth={1.5}
                    />
                    {t("emailPersonalWarning")}
                  </p>
                )}
                {errors.email && (
                  <p className="text-red-400 text-sm">{errors.email.message}</p>
                )}
              </div>

              {/* 2. Website */}
              <div className="space-y-2">
                <label
                  className="block font-medium text-sm text-white"
                  htmlFor="website"
                >
                  {t("website")} <span className="text-[#FD105E]">*</span>
                </label>
                <input
                  autoCapitalize="off"
                  autoComplete="url"
                  id="website"
                  inputMode="url"
                  spellCheck={false}
                  type="text"
                  {...register("website")}
                  className="w-full rounded-xl border border-white/20 bg-white/5 px-4 py-3 text-white placeholder-neutral-400 transition-all duration-300 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-[#FD105E]"
                  disabled={isLoading}
                  placeholder={t("websitePlaceholder")}
                />
                {errors.website && (
                  <p className="text-red-400 text-sm">
                    {errors.website.message}
                  </p>
                )}
              </div>

              {/* 3. Full Name */}
              <div className="space-y-2">
                <label
                  className="block font-medium text-sm text-white"
                  htmlFor="fullName"
                >
                  {t("fullName")} <span className="text-[#FD105E]">*</span>
                </label>
                <input
                  autoComplete="name"
                  id="fullName"
                  type="text"
                  {...register("fullName")}
                  className="w-full rounded-xl border border-white/20 bg-white/5 px-4 py-3 text-white placeholder-neutral-400 transition-all duration-300 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-[#FD105E]"
                  disabled={isLoading}
                  placeholder={t("fullNamePlaceholder")}
                />
                {errors.fullName && (
                  <p className="text-red-400 text-sm">
                    {errors.fullName.message}
                  </p>
                )}
              </div>

              {/* 4. Project Type — radio cards */}
              <div className="space-y-3">
                <span
                  className="block font-medium text-sm text-white"
                  id="projectTypeLabel"
                >
                  {t("projectType")} <span className="text-[#FD105E]">*</span>
                </span>
                <div
                  aria-labelledby="projectTypeLabel"
                  className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3"
                  role="radiogroup"
                >
                  {projectTypeConfig.map(
                    ({ value, labelKey, descKey, Icon }) => (
                      <label
                        className="group relative cursor-pointer"
                        key={value}
                      >
                        <input
                          type="radio"
                          value={value}
                          {...register("projectType")}
                          className="peer sr-only"
                          disabled={isLoading}
                        />
                        <div className="h-full rounded-xl border border-white/15 bg-white/5 p-4 transition-all duration-200 hover:border-[#FD105E]/40 peer-checked:border-[#FD105E] peer-checked:bg-[#FD105E]/10 peer-focus-visible:ring-2 peer-focus-visible:ring-[#FD105E]">
                          <Icon
                            className="mb-2 h-6 w-6 text-white/70 group-hover:text-white peer-checked:group-[]:text-[#FD105E]"
                            strokeWidth={1.5}
                          />
                          <div className="font-semibold text-sm text-white">
                            {t(labelKey)}
                          </div>
                          <div className="mt-1 text-neutral-400 text-xs leading-snug">
                            {t(descKey)}
                          </div>
                        </div>
                      </label>
                    )
                  )}
                </div>
                {errors.projectType && (
                  <p className="text-red-400 text-sm">
                    {errors.projectType.message}
                  </p>
                )}
              </div>

              {/* 5. Message (optional) */}
              <div className="space-y-2">
                <label
                  className="block font-medium text-sm text-white"
                  htmlFor="message"
                >
                  {t("message")}{" "}
                  <span className="font-normal text-neutral-400 text-xs">
                    ({t("messageOptional")})
                  </span>
                </label>
                <textarea
                  id="message"
                  {...register("message")}
                  className="w-full resize-none rounded-xl border border-white/20 bg-white/5 px-4 py-3 text-white placeholder-neutral-400 transition-all duration-300 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-[#FD105E]"
                  disabled={isLoading}
                  placeholder={t("messagePlaceholder")}
                  rows={4}
                />
                {errors.message && (
                  <p className="text-red-400 text-sm">
                    {errors.message.message}
                  </p>
                )}
                <p className="text-neutral-400 text-xs">{t("messageHelper")}</p>
              </div>

              {/* Submit + implicit consent (GDPR-compliant: submission = consent, links exposed) */}
              <div className="flex flex-col items-center gap-3 pt-4">
                <button
                  className="inline-flex w-full min-w-[200px] items-center justify-center gap-2 rounded-xl bg-[#E00D54] px-8 py-4 font-medium text-white transition-all duration-300 hover:bg-[#E00D54]/90 focus:outline-none focus:ring-2 focus:ring-[#FD105E] focus:ring-offset-2 focus:ring-offset-transparent disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
                  disabled={isLoading}
                  type="submit"
                >
                  {isLoading ? (
                    <>
                      <IconLoader2 className="h-5 w-5 animate-spin" />
                      <span>{t("submitting")}</span>
                    </>
                  ) : (
                    <>
                      <span>{t("submit")}</span>
                      <IconArrowRight className="h-5 w-5" />
                    </>
                  )}
                </button>
                <p className="max-w-md text-center text-neutral-400 text-xs">
                  {t.rich("implicitConsent", {
                    privacyPolicy: (chunks) => (
                      <Link
                        className="text-[#FD105E] hover:underline"
                        href="/privacy-policy"
                      >
                        {chunks}
                      </Link>
                    ),
                    terms: (chunks) => (
                      <Link
                        className="text-[#FD105E] hover:underline"
                        href="/terms"
                      >
                        {chunks}
                      </Link>
                    ),
                  })}
                </p>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}
