"use client";

import React, { useState } from "react";
import { useTranslations } from "next-intl";
import { Mail, MessageCircle, PackageCheck, UserRound } from "lucide-react";

type ContactAudience = "customer" | "supplier";

export default function ContactForm() {
  const t = useTranslations();
  const [status, setStatus] = useState<"idle" | "handoff">("idle");
  const [audience, setAudience] = useState<ContactAudience>("customer");

  const selectAudience = (nextAudience: ContactAudience) => {
    setAudience(nextAudience);
    setStatus("idle");
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.currentTarget as HTMLFormElement;
    if (!form.reportValidity()) return;
    const data = new FormData(form);
    const audienceLabel = t(`contact.${audience}`);
    const subject = String(data.get("subject") || "").trim();
    const body = [
      `${t("contact.audience_label")}: ${audienceLabel}`,
      `${t("contact.name")}: ${String(data.get("name") || "")}`,
      `${t("contact.email")}: ${String(data.get("email") || "")}`,
      `${t("contact.phone_field")}: ${String(data.get("phone") || "-")}`,
      "",
      `${t("contact.message")}:`,
      String(data.get("message") || ""),
    ].join("\n");
    setStatus("handoff");
    window.location.href = `mailto:info@norden-haus.com?subject=${encodeURIComponent(`[Norden · ${audienceLabel}] ${subject}`)}&body=${encodeURIComponent(body)}`;
  };

  const whatsappText = audience === "supplier"
    ? t("contact.supplier_whatsapp_message")
    : t("catalog.whatsapp_general");
  const whatsappUrl = `https://wa.me/905394671328?text=${encodeURIComponent(whatsappText)}`;

  const inputStyle: React.CSSProperties = {
    background: "rgba(128,128,160,0.06)",
    border: "1px solid var(--border)",
    color: "var(--fg-primary)",
    transition: "all 200ms ease",
  };

  const labelStyle: React.CSSProperties = {
    fontFamily: "var(--font-ibm-plex-mono)",
    fontSize: "10px",
    textTransform: "uppercase" as const,
    letterSpacing: "0.14em",
    color: "var(--fg-muted)",
  };

  return (
    <form className="space-y-5 w-full" onSubmit={handleSubmit}>
      <input type="hidden" name="audience" value={audience} />

      <fieldset aria-describedby="contact-audience-description">
        <legend className="sr-only">{t("contact.audience_label")}</legend>
        <div className="grid grid-cols-2 gap-2 rounded-2xl p-1.5" style={{ background: "rgba(128,128,160,0.06)", border: "1px solid var(--border)" }}>
          {([
            { value: "customer" as const, Icon: UserRound },
            { value: "supplier" as const, Icon: PackageCheck },
          ]).map(({ value, Icon }) => {
            const isActive = audience === value;
            return (
              <button
                key={value}
                type="button"
                aria-pressed={isActive}
                onClick={() => selectAudience(value)}
                className="flex min-h-11 items-center justify-center gap-2 rounded-xl px-3 py-3 text-xs font-semibold uppercase tracking-wider transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember"
                style={{
                  color: isActive ? "var(--surface-0)" : "var(--fg-secondary)",
                  background: isActive ? "var(--ember)" : "transparent",
                }}
              >
                <Icon size={15} aria-hidden="true" />
                {t(`contact.${value}`)}
              </button>
            );
          })}
        </div>
        <p id="contact-audience-description" className="mt-3 text-xs leading-relaxed" style={{ color: "var(--fg-secondary)" }}>
          {t(`contact.${audience}_description`)}
        </p>
      </fieldset>

      {/* Name + Email row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <div className="flex flex-col gap-2">
          <label htmlFor="contact-name" style={labelStyle}>{t("contact.name")}</label>
          <input
            id="contact-name"
            type="text"
            name="name"
            autoComplete="name"
            required
            maxLength={100}
            placeholder={t("contact.name_placeholder")}
            className="w-full rounded-full px-5 py-3.5 text-sm focus:outline-none transition-all"
            style={inputStyle}
            onFocus={(e) => { e.target.style.borderColor = "var(--ember)"; e.target.style.background = "rgba(128,128,160,0.10)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.background = "rgba(128,128,160,0.06)"; }}
          />
        </div>
        <div className="flex flex-col gap-2">
          <label htmlFor="contact-email" style={labelStyle}>{t("contact.email")}</label>
          <input
            id="contact-email"
            type="email"
            name="email"
            autoComplete="email"
            required
            maxLength={160}
            placeholder={t("contact.email_placeholder")}
            className="w-full rounded-full px-5 py-3.5 text-sm focus:outline-none transition-all"
            style={inputStyle}
            onFocus={(e) => { e.target.style.borderColor = "var(--ember)"; e.target.style.background = "rgba(128,128,160,0.10)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.background = "rgba(128,128,160,0.06)"; }}
          />
        </div>
      </div>

      {/* Phone + Subject row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <div className="flex flex-col gap-2">
          <label htmlFor="contact-phone" style={labelStyle}>{t("contact.phone_field")}</label>
          <input
            id="contact-phone"
            type="tel"
            name="phone"
            autoComplete="tel"
            inputMode="tel"
            maxLength={40}
            placeholder={t("contact.phone_placeholder")}
            className="w-full rounded-full px-5 py-3.5 text-sm focus:outline-none transition-all"
            style={inputStyle}
            onFocus={(e) => { e.target.style.borderColor = "var(--ember)"; e.target.style.background = "rgba(128,128,160,0.10)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.background = "rgba(128,128,160,0.06)"; }}
          />
        </div>
        <div className="flex flex-col gap-2">
          <label htmlFor="contact-subject" style={labelStyle}>{t("contact.subject")}</label>
          <input
            id="contact-subject"
            type="text"
            name="subject"
            required
            maxLength={160}
            placeholder={t(`contact.${audience}_subject_placeholder`)}
            className="w-full rounded-full px-5 py-3.5 text-sm focus:outline-none transition-all"
            style={inputStyle}
            onFocus={(e) => { e.target.style.borderColor = "var(--ember)"; e.target.style.background = "rgba(128,128,160,0.10)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.background = "rgba(128,128,160,0.06)"; }}
          />
        </div>
      </div>

      {/* Message */}
      <div className="flex flex-col gap-2">
        <label htmlFor="contact-message" style={labelStyle}>{t("contact.message")}</label>
        <textarea
          id="contact-message"
          name="message"
          required
          maxLength={2000}
          rows={4}
          placeholder={t(`contact.${audience}_message_placeholder`)}
          className="w-full rounded-2xl px-5 py-3.5 text-sm focus:outline-none transition-all resize-none"
          style={inputStyle}
          onFocus={(e) => { e.target.style.borderColor = "var(--ember)"; e.target.style.background = "rgba(128,128,160,0.10)"; }}
          onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.background = "rgba(128,128,160,0.06)"; }}
        />
      </div>

      <p className="text-[11px] leading-5" style={{ color: "var(--fg-muted)" }}>{t("contact.delivery_note")}</p>

      <div className="grid gap-3 sm:grid-cols-2">
        <button
          type="submit"
          className="flex min-h-12 w-full items-center justify-center gap-2 rounded-full px-5 font-sans text-xs font-semibold uppercase tracking-widest transition-all duration-300 hover:opacity-90 active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember focus-visible:ring-offset-2 focus-visible:ring-offset-surface-1"
          style={{ background: "var(--ember)", color: "var(--surface-0)", cursor: "pointer" }}
        >
          <Mail size={15} aria-hidden="true" /> {t("contact.prepare_email")}
        </button>
        <a href={whatsappUrl} target="_blank" rel="noopener noreferrer" className="flex min-h-12 items-center justify-center gap-2 rounded-full border px-5 text-center text-xs font-semibold uppercase tracking-widest transition-colors hover:border-ember hover:text-ember focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ember" style={{ borderColor: "var(--border)", color: "var(--fg-secondary)" }}>
          <MessageCircle size={15} aria-hidden="true" /> {t("contact.whatsapp_alternative")}
        </a>
      </div>

      <p role="status" aria-live="polite" className="min-h-5 text-xs leading-5" style={{ color: "var(--ember-bright)" }}>
        {status === "handoff" ? t("contact.email_handoff") : ""}
      </p>
    </form>
  );
}
