/* eslint-disable @next/next/no-img-element */
"use client";

import { Mail, MapPin, Phone, Send } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useTransition, useState } from "react";
import { toast } from "react-toastify";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PhoneInput } from "@/components/ui/inputs/phone-input";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { countries } from "@/lib/countries";
import { SectionUnderline } from "../ui/section-underline";
import { socialLinks } from "../footer";
import { submitContact } from "@/app/actions/contact";

type ContactInfo = {
  label: string;
  value: string;
  icon: "phone" | "email" | "location";
};

type ContactUsProps = {
  title?: string;
  contactInfo?: ContactInfo[];
  className?: string;
};

export default function ContactUs({
  title,
  contactInfo,
  className,
}: ContactUsProps) {
  const t = useTranslations("contact");
  const locale = useLocale();
  const isEnglish = locale === "en";

  const defaultContactInfo: ContactInfo[] = [
    { label: t("phoneLabel"), value: "0551443666", icon: "phone" },
    { label: t("emailLabel"), value: "example@maaal.com", icon: "email" },
    { label: t("locationLabel"), value: t("defaultLocation"), icon: "location" },
  ];

  const displayTitle = title || t("title");
  const displayContactInfo = contactInfo || defaultContactInfo;

  const [isPending, startTransition] = useTransition();
  const [selectedCountry, setSelectedCountry] = useState(countries[0]);
  const [formState, setFormState] = useState({
    name: "", email: "", code: countries[0].dialCode, phone: "", message: "",
  });

  const handleChange =
    (field: keyof typeof formState) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setFormState((prev) => ({ ...prev, [field]: e.target.value }));

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    startTransition(async () => {
      const res = await submitContact(formState);
      toast[res.ok ? "success" : "error"](res.message);
      if (res.ok) {
        setSelectedCountry(countries[0]);
        setFormState({ name: "", email: "", code: countries[0].dialCode, phone: "", message: "" });
      }
    });
  };

  return (
    <section
      className={cn(
        "relative w-full overflow-hidden bg-white px-4 sm:px-6 md:px-8 lg:px-12 xl:px-[120px] py-14 sm:py-16 md:py-20",
        className
      )}
    >

      <div
        aria-hidden
        className="pointer-events-none absolute inset-0 [background-attachment:fixed] [background-image:repeating-linear-gradient(to_right,rgba(16,24,40,0.06)_0_1px,transparent_1px_310px)]"
      />

      <div className="relative mx-auto flex max-w-[1280px] flex-col gap-10">
        <div className="flex flex-col items-center gap-2 text-center">
          <h2 className="text-3xl sm:text-[32px] md:text-[36px] lg:text-[40px] font-bold text-foreground">
            {displayTitle}
          </h2>
          <SectionUnderline className="w-[220px]" />
        </div>

        <div className="grid grid-cols-1 lg:[&>*]:col-start-1 lg:[&>*]:row-start-1" dir="ltr">

          <div
            aria-hidden
            className={cn(
              "pointer-events-none relative hidden aspect-[1179/602] w-full self-end overflow-hidden bg-[#1C75BC] lg:block",
              "[background-attachment:fixed] [background-image:repeating-linear-gradient(to_right,rgba(255,255,255,0.16)_0_1px,transparent_1px_310px)]",
              "[mask-size:100%_100%] [mask-repeat:no-repeat]",
              isEnglish
                ? "[mask-image:url('/images/contact-us/rectangle-339-flipped.svg')]"
                : "[mask-image:url('/images/contact-us/Rectangle%20339.svg')]"
            )}
          >
            <img
              src="/images/contact-us/Vector.svg"
              alt=""
              className={cn(
                "absolute bottom-0 w-[63%] opacity-[0.35]",
                isEnglish ? "left-0" : "right-0"
              )}
            />
          </div>

          <div
            className={cn(
              "grid grid-cols-1 gap-8 lg:grid-cols-[53%_1fr] lg:gap-x-[8%] lg:gap-y-0 lg:pb-[52px]",
              isEnglish ? "lg:pl-[6%] lg:pr-[8%]" : "lg:pl-[8%] lg:pr-[6%]"
            )}
          >

            <div
              className={cn(
                "relative z-10 self-start rounded-[24px] bg-white border border-[#b9d4ea] p-6 sm:p-8 shadow-[0px_12px_16px_-4px_rgba(16,24,40,0.08),0px_4px_6px_-2px_rgba(16,24,40,0.03)]",
                isEnglish && "lg:order-2"
              )}
              dir="auto"
            >
            <form className="space-y-6" onSubmit={handleSubmit}>
              <FormField label={t("yourName")}>
                <Input
                  placeholder={t("namePlaceholder")}
                  className="text-start rounded-[12px] border border-border h-[56px]"
                  value={formState.name}
                  onChange={handleChange("name")}
                  required
                />
              </FormField>

              <FormField label={t("yourEmail")}>
                <Input
                  type="email"
                  placeholder={t("emailPlaceholder")}
                  className="text-start rounded-[12px] border border-border h-[56px]"
                  value={formState.email}
                  onChange={handleChange("email")}
                  required
                />
              </FormField>

              <FormField label={t("phoneNumber")}>
                <PhoneInput
                  value={formState.phone}
                  onChange={(value) =>
                    setFormState((prev) => ({ ...prev, phone: value }))
                  }
                  country={selectedCountry}
                  onCountryChange={(country) => {
                    setSelectedCountry(country);
                    setFormState((prev) => ({ ...prev, code: country.dialCode }));
                  }}
                  placeholder={t("phonePlaceholder")}
                  className="h-[56px] rounded-[12px] border-[#e7e7e7] bg-muted"
                />
              </FormField>

              <FormField label={t("message")}>
                <Textarea
                  placeholder={t("messagePlaceholder")}
                  className="min-h-[120px] text-start rounded-[12px] border border-border"
                  value={formState.message}
                  onChange={handleChange("message")}
                  required
                />
              </FormField>

              <Button
                type="submit"
                disabled={isPending}
                className="w-full h-12 rounded-[12px] bg-[#1c75bc] text-white gap-2 hover:bg-[#1c75bc]/90 flex-row disabled:opacity-60"
              >
                <span>{isPending ? t("sending") : t("send")}</span>
                <Send className="h-4 w-4" />
              </Button>
              </form>
            </div>

            <div
              className={cn(
                "relative z-10 self-center overflow-hidden rounded-[24px] bg-gradient-to-br from-[#1c75bc] to-[#0f4067] p-6 text-white shadow-lg sm:p-8",
                "lg:rounded-none lg:bg-none lg:p-0 lg:shadow-none",
                isEnglish && "lg:order-1"
              )}
              dir="auto"
            >
              <img
                src="/images/contact-us/Vector.svg"
                alt=""
                className="pointer-events-none absolute -bottom-6 hidden w-[420px] opacity-[0.08] sm:block lg:hidden end-[10%]"
              />
              <p className="relative max-w-[460px] text-[26px] font-bold leading-[1.35] text-start sm:text-[30px] lg:text-[32px]">
                {t("helpYouNow")}
              </p>
              <div className="space-y-4 relative mt-8">
                {displayContactInfo.map((item) => (
                  <div
                    key={item.label}
                    className="flex flex-row items-center gap-3 justify-start"
                  >
                    <div className="flex size-10 shrink-0 items-center justify-center rounded-full border border-white/25 bg-white/15">
                      {item.icon === "phone" && <Phone className="h-5 w-5" />}
                      {item.icon === "email" && <Mail className="h-5 w-5" />}
                      {item.icon === "location" && <MapPin className="h-5 w-5" />}
                    </div>
                    <div className="text-white text-base font-medium">
                      {item.value}
                    </div>
                  </div>
                ))}
              </div>
              <div className="space-y-4 relative mt-10">
                <p className="text-2xl font-bold text-start">{t("followUs")}</p>
                <div className="flex flex-wrap items-center gap-3 justify-start">
                  {socialLinks.map((social) => (
                    <a
                      key={social.name}
                      href={social.href}
                      aria-label={social.name}
                      className="relative flex size-8 items-center justify-center rounded-full transition-opacity hover:opacity-80"
                    >
                      <img src={social.iconPath} alt="" className="size-8" />
                      {social.overlayIconPath && (
                        <img
                          src={social.overlayIconPath}
                          alt=""
                          className="absolute left-1/2 top-1/2 size-5 -translate-x-1/2 -translate-y-1/2"
                        />
                      )}
                    </a>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function FormField({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-2">
      <label className="text-foreground text-[16px] text-start block">{label}</label>
      {children}
    </div>
  );
}
