"use client";

import Link from "next/link";
import { FormEvent, useState } from "react";

import { AppLogo } from "@/components/branding/app-logo";
import { LanguageSwitcher } from "@/components/layout/language-switcher";
import { useLocale } from "@/components/providers/locale-provider";

type ContactAdminClientProps = {
  captchaQuestion: string;
  captchaToken: string;
};

export function ContactAdminClient({
  captchaQuestion,
  captchaToken
}: ContactAdminClientProps) {
  const { locale, dict } = useLocale();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [captchaAnswer, setCaptchaAnswer] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError(null);
    setSuccess(null);

    try {
      const response = await fetch("/api/v1/public/contact-admin", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          name,
          email,
          message,
          captcha_token: captchaToken,
          captcha_answer: captchaAnswer,
          website: ""
        })
      });

      const payload = (await response.json()) as {
        message?: string;
        errors?: Record<string, string[]>;
      };

      if (!response.ok) {
        const firstError = payload.errors ? Object.values(payload.errors)[0]?.[0] : undefined;
        throw new Error(firstError ?? payload.message ?? "Gagal mengirim pesan.");
      }

      setSuccess(payload.message ?? "Pesan berhasil dikirim.");
      setName("");
      setEmail("");
      setMessage("");
      setCaptchaAnswer("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal mengirim pesan.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-screen bg-canvas px-6 py-10 lg:px-0">
      <div className="mx-auto w-full max-w-3xl">
        <div className="rounded-2xl border border-line/70 bg-white shadow-panel">
          <header className="border-b border-line/70 px-8 py-8 sm:px-10">
            <div className="flex items-start justify-between gap-4">
              <div className="flex items-center gap-4">
                <AppLogo size={64} className="h-16 w-16 rounded-2xl object-contain" priority />
                <div>
                  <p className="text-sm font-semibold uppercase tracking-[0.12em] text-slate-500">
                    AbelBirdnest Stock
                  </p>
                  <h1 className="mt-1 text-3xl font-semibold tracking-tight text-ink">
                    {locale === "id" ? "Hubungi Admin" : "Contact Admin"}
                  </h1>
                </div>
              </div>
              <LanguageSwitcher />
            </div>
            <p className="mt-5 max-w-2xl text-[15px] leading-7 text-slate-600">
              {locale === "id"
                ? "Gunakan form ini untuk permintaan akun operasional, bantuan akses, atau kendala login. Form ini dilindungi CAPTCHA untuk mengurangi spam."
                : "Use this form for operational account requests, access assistance, or login issues. This form is protected by CAPTCHA to reduce spam."}
            </p>
          </header>

          <form onSubmit={handleSubmit} className="space-y-6 px-8 py-8 sm:px-10">
            <label className="block">
              <span className="ops-label">{locale === "id" ? "Nama" : "Name"}</span>
              <input value={name} onChange={(event) => setName(event.target.value)} className="ops-input" />
            </label>

            <label className="block">
              <span className="ops-label">Email</span>
              <input
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                className="ops-input"
                placeholder="name@company.com"
              />
            </label>

            <label className="block">
              <span className="ops-label">{locale === "id" ? "Pesan" : "Message"}</span>
              <textarea
                value={message}
                onChange={(event) => setMessage(event.target.value)}
                className="ops-input min-h-32"
                placeholder={
                  locale === "id"
                    ? "Jelaskan kebutuhan akun atau kendala yang Anda alami."
                    : "Describe your account request or issue."
                }
              />
            </label>

            <div className="rounded-lg border border-line/70 bg-slate-50 p-4">
              <p className="ops-label mb-2">{locale === "id" ? "Verifikasi CAPTCHA" : "CAPTCHA Verification"}</p>
              <p className="text-sm text-slate-600">
                {locale === "id" ? "Berapa hasil dari" : "What is"} <span className="font-semibold text-ink">{captchaQuestion}</span>?
              </p>
              <input
                value={captchaAnswer}
                onChange={(event) => setCaptchaAnswer(event.target.value)}
                className="ops-input mt-3 max-w-40"
                inputMode="numeric"
              />
            </div>

            {error ? (
              <div className="rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">
                {error}
              </div>
            ) : null}

            {success ? (
              <div className="rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">
                {success}
              </div>
            ) : null}

            <div className="flex flex-col gap-3 sm:flex-row">
              <button type="submit" disabled={submitting} className="ops-btn-primary">
                {submitting
                  ? locale === "id"
                    ? "Mengirim..."
                    : "Sending..."
                  : locale === "id"
                    ? "Kirim ke Admin"
                    : "Send to Admin"}
              </button>
              <Link href="/login" className="ops-btn-secondary">
                {dict.common.backToLogin}
              </Link>
            </div>
          </form>
        </div>
      </div>
    </main>
  );
}
