"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Send, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { EnquiryType } from "@/lib/api/website/contact-types";

const DIAL_CODES = [
  { code: "+966", emoji: "🇸🇦" },
  { code: "+971", emoji: "🇦🇪" },
  { code: "+965", emoji: "🇰🇼" },
  { code: "+974", emoji: "🇶🇦" },
  { code: "+973", emoji: "🇧🇭" },
  { code: "+968", emoji: "🇴🇲" },
  { code: "+962", emoji: "🇯🇴" },
  { code: "+20",  emoji: "🇪🇬" },
  { code: "+1",   emoji: "🇺🇸" },
  { code: "+44",  emoji: "🇬🇧" },
];

const MAX_MESSAGE = 500;
const getOrigin = () =>
  (process.env.NEXT_PUBLIC_API_URL || "https://maaal-h.maaal.site").replace(/\/+$/, "");

type FormState = {
  name: string;
  email: string;
  dialCode: string;
  phone: string;
  enquiryTypeId: string;
  subject: string;
  message: string;
};

const EMPTY: FormState = {
  name: "", email: "", dialCode: "+966", phone: "",
  enquiryTypeId: "", subject: "", message: "",
};

type Status = "idle" | "loading" | "success" | "error";

export default function ContactForm({ enquiryTypes }: { enquiryTypes: EnquiryType[] }) {
  const t = useTranslations("contactUsPage");
  const [form, setForm] = useState<FormState>(EMPTY);
  const [status, setStatus] = useState<Status>("idle");
  const [errorMsg, setErrorMsg] = useState("");

  const set = (key: keyof FormState) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
      setForm((f) => ({ ...f, [key]: e.target.value }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (status === "loading") return;
    setStatus("loading");
    setErrorMsg("");
    try {
      const res = await fetch(`${getOrigin()}/api/contact`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          country_dial_code: form.dialCode,
          phone: form.phone,
          enquiry_type_id: Number(form.enquiryTypeId),
          subject: form.subject,
          message: form.message,
        }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({})) as { message?: string };
        throw new Error(err.message || t("form.errorMessage"));
      }
      setStatus("success");
      setForm(EMPTY);
    } catch (err) {
      setStatus("error");
      setErrorMsg(err instanceof Error ? err.message : t("form.errorMessage"));
    }
  };

  if (status === "success") {
    return (
      <div className="flex flex-col items-center justify-center gap-6 rounded-2xl bg-primary-50 px-8 py-16 text-center">
        <div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10">
          <CheckCircle2 className="h-10 w-10 text-primary" />
        </div>
        <div className="flex flex-col gap-2">
          <h3 className="text-2xl font-bold text-primary">{t("form.successTitle")}</h3>
          <p className="text-sm text-muted-foreground">{t("form.successMessage")}</p>
        </div>
        <Button variant="outline" onClick={() => setStatus("idle")}>
          {t("form.sendAnother")}
        </Button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-5">
      <p className="text-xl font-bold leading-relaxed text-foreground sm:text-2xl lg:text-[26px]">
        {t("form.sectionTitle")}
      </p>

      {/* Name */}
      <Field label={t("form.nameLabel")}>
        <Input
          type="text"
          required
          placeholder={t("form.namePlaceholder")}
          value={form.name}
          onChange={set("name")}
          className="h-12"
        />
      </Field>

      {/* Email */}
      <Field label={t("form.emailLabel")}>
        <Input
          type="email"
          required
          placeholder={t("form.emailPlaceholder")}
          value={form.email}
          onChange={set("email")}
          className="h-12"
        />
      </Field>

      {/* Phone with dial code */}
      <Field label={t("form.phoneLabel")}>
        <div className="flex h-12 overflow-hidden rounded-xl border border-border bg-card transition-[border-color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/30">
          {/* Dial code — native select keeps it inline */}
          <select
            value={form.dialCode}
            onChange={set("dialCode")}
            aria-label="Country dial code"
            className="shrink-0 cursor-pointer appearance-none border-e border-border bg-transparent py-0 pe-2 ps-3 text-sm font-medium text-font-primary focus:outline-none"
          >
            {DIAL_CODES.map((d) => (
              <option key={d.code} value={d.code}>
                {d.emoji} {d.code}
              </option>
            ))}
          </select>
          <input
            type="tel"
            required
            placeholder={t("form.phonePlaceholder")}
            value={form.phone}
            onChange={set("phone")}
            className="min-w-0 flex-1 bg-transparent px-3 text-sm text-font-primary placeholder:text-muted-foreground focus:outline-none"
          />
        </div>
      </Field>

      {/* Inquiry Type */}
      <Field label={t("form.enquiryTypeLabel")}>
        <Select
          value={form.enquiryTypeId}
          onValueChange={(v) => setForm((f) => ({ ...f, enquiryTypeId: v }))}
          required
        >
          <SelectTrigger className="h-12 rounded-xl">
            <SelectValue placeholder={t("form.enquiryTypePlaceholder")} />
          </SelectTrigger>
          <SelectContent>
            {enquiryTypes.map((et) => (
              <SelectItem key={et.id} value={String(et.id)}>
                {et.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </Field>

      {/* Subject */}
      <Field label={t("form.subjectLabel")}>
        <Input
          type="text"
          required
          placeholder={t("form.subjectPlaceholder")}
          value={form.subject}
          onChange={set("subject")}
          className="h-12"
        />
      </Field>

      {/* Message */}
      <Field label={t("form.messageLabel")}>
        <div className="relative">
          <Textarea
            required
            rows={5}
            placeholder={t("form.messagePlaceholder")}
            value={form.message}
            onChange={(e) => setForm((f) => ({ ...f, message: e.target.value.slice(0, MAX_MESSAGE) }))}
            maxLength={MAX_MESSAGE}
            className="resize-none pb-7"
          />
          <span className="pointer-events-none absolute bottom-2 start-3 text-xs text-muted-foreground">
            {form.message.length}/{MAX_MESSAGE}
          </span>
        </div>
      </Field>

      {/* Error */}
      {status === "error" && (
        <p role="alert" className="rounded-lg bg-destructive/10 px-4 py-2.5 text-sm text-destructive">
          {errorMsg || t("form.errorMessage")}
        </p>
      )}

      {/* Submit */}
      <Button type="submit" size="xl" className="w-full" disabled={status === "loading"}>
        <Send className="h-4 w-4" />
        {status === "loading" ? t("form.sending") : t("form.submitButton")}
      </Button>
    </form>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex flex-col gap-2">
      <Label className="text-font-primary">{label}</Label>
      {children}
    </div>
  );
}
