"use client";

import { useState } from "react";
import type { FormEvent } from "react";

type FieldErrors = Partial<Record<"name" | "email" | "message", string>>;

function validateEmail(raw: string): boolean {
  const s = raw.trim();
  if (!s) return false;
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
}

export function ContactForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [demoAcknowledged, setDemoAcknowledged] = useState(false);

  function validate(): boolean {
    const next: FieldErrors = {};
    const n = name.trim();
    const em = email.trim();
    const msg = message.trim();

    if (!n) {
      next.name = "Vui lòng nhập tên hoặc biệt danh — chỉ để thử khung, không gửi đi.";
    }
    if (!em) {
      next.email = "Vui lòng nhập email — hiện chỉ dùng để kiểm tra ô nhập, chưa có chỗ nhận.";
    } else if (!validateEmail(em)) {
      next.email = "Email chưa đúng dạng thường thấy (ví dụ: ten@email.com).";
    }
    if (!msg) {
      next.message = "Ô nội dung đang trống — hãy thử gõ vài dòng để xem khung hoạt động.";
    } else if (msg.length < 8) {
      next.message = "Nội dung hơi ngắn — thêm vài chữ để mô phỏng một tin nhắn thật.";
    }

    setFieldErrors(next);
    return Object.keys(next).length === 0;
  }

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setDemoAcknowledged(false);
    if (!validate()) return;
    setDemoAcknowledged(true);
  }

  function handleReset() {
    setName("");
    setEmail("");
    setMessage("");
    setFieldErrors({});
    setDemoAcknowledged(false);
  }

  return (
    <section
      className="mt-12 rounded-xl border border-dashed border-stone-700/50 bg-[#0c0b0a]/55 px-5 py-7 sm:px-7 sm:py-8"
      aria-labelledby="contact-form-heading"
    >
      <p className="ctkp-eyebrow text-center text-[10px] tracking-[0.28em]">Bản thử — chưa gửi thật</p>
      <h2
        id="contact-form-heading"
        className="font-ctkp-display mt-3 text-center text-lg font-semibold text-stone-100 sm:text-xl"
      >
        Biểu mẫu liên hệ (mô phỏng)
      </h2>
      <p className="mx-auto mt-3 max-w-md text-center text-sm leading-relaxed text-stone-500">
        Khung dưới đây chỉ chạy trên trình duyệt của bạn. Chúng tôi{" "}
        <span className="font-medium text-stone-400">chưa</span> mở kênh nhận thư từ trang này — bấm nút chỉ để xem
        thông báo minh họa, không có dữ liệu nào tới máy chủ.
      </p>

      {demoAcknowledged ? (
        <div
          className="mt-6 rounded-xl border border-stone-700/45 bg-[#12100e]/80 px-4 py-3.5 text-sm leading-relaxed text-stone-300/95"
          role="status"
          aria-live="polite"
        >
          <p className="font-medium text-stone-100">Đã xác nhận trên trình duyệt này.</p>
          <p className="mt-2 text-stone-300/95">
            Tin nhắn của bạn <span className="font-medium text-amber-200/90">không</span> được gửi tới Cổ Thư Kỳ Phổ và
            không được lưu ở phía chúng tôi. Khi có email hoặc biểu mẫu chính thức, trang sẽ được cập nhật để bạn liên
            hệ thật.
          </p>
        </div>
      ) : null}

      <form className="mt-6 space-y-5" onSubmit={handleSubmit} noValidate>
        {Object.keys(fieldErrors).length > 0 ? (
          <p className="sr-only" role="status" aria-live="polite">
            Biểu mẫu còn thiếu hoặc chưa hợp lệ — đã hiển thị gợi ý dưới từng ô.
          </p>
        ) : null}
        <div>
          <label htmlFor="contact-name" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
            Tên hoặc biệt danh <span className="text-amber-700/80">*</span>
          </label>
          <input
            id="contact-name"
            name="name"
            type="text"
            autoComplete="name"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              if (fieldErrors.name) setFieldErrors((f) => ({ ...f, name: undefined }));
            }}
            className="mt-2 w-full rounded-xl border border-amber-950/30 bg-black/30 px-4 py-2.5 text-sm text-stone-200 placeholder:text-stone-600 outline-none transition-[border-color,box-shadow] duration-200 focus:border-amber-800/40 focus:ring-2 focus:ring-amber-900/25"
            placeholder="Ví dụ: Minh"
            aria-invalid={Boolean(fieldErrors.name)}
            aria-describedby={fieldErrors.name ? "contact-name-err" : undefined}
          />
          {fieldErrors.name ? (
            <p id="contact-name-err" className="mt-1.5 text-xs text-amber-200/70">
              {fieldErrors.name}
            </p>
          ) : null}
        </div>
        <div>
          <label htmlFor="contact-email" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
            Email <span className="text-amber-700/80">*</span>
          </label>
          <input
            id="contact-email"
            name="email"
            type="email"
            autoComplete="email"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              if (fieldErrors.email) setFieldErrors((f) => ({ ...f, email: undefined }));
            }}
            className="mt-2 w-full rounded-xl border border-amber-950/30 bg-black/30 px-4 py-2.5 text-sm text-stone-200 placeholder:text-stone-600 outline-none transition-[border-color,box-shadow] duration-200 focus:border-amber-800/40 focus:ring-2 focus:ring-amber-900/25"
            placeholder="ban@email.com"
            aria-invalid={Boolean(fieldErrors.email)}
            aria-describedby={fieldErrors.email ? "contact-email-err" : undefined}
          />
          {fieldErrors.email ? (
            <p id="contact-email-err" className="mt-1.5 text-xs text-amber-200/70">
              {fieldErrors.email}
            </p>
          ) : null}
        </div>
        <div>
          <label htmlFor="contact-message" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
            Nội dung <span className="text-amber-700/80">*</span>
          </label>
          <textarea
            id="contact-message"
            name="message"
            rows={5}
            value={message}
            onChange={(e) => {
              setMessage(e.target.value);
              if (fieldErrors.message) setFieldErrors((f) => ({ ...f, message: undefined }));
            }}
            className="mt-2 w-full resize-y rounded-xl border border-amber-950/30 bg-black/30 px-4 py-2.5 text-sm text-stone-200 placeholder:text-stone-600 outline-none transition-[border-color,box-shadow] duration-200 focus:border-amber-800/40 focus:ring-2 focus:ring-amber-900/25"
            placeholder="Bạn muốn chia sẻ điều gì? (chỉ hiển thị trên máy bạn)"
            aria-invalid={Boolean(fieldErrors.message)}
            aria-describedby={fieldErrors.message ? "contact-message-err" : undefined}
          />
          {fieldErrors.message ? (
            <p id="contact-message-err" className="mt-1.5 text-xs text-amber-200/70">
              {fieldErrors.message}
            </p>
          ) : null}
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
          <button
            type="submit"
            className="ctkp-btn-primary px-8"
          >
            Xác nhận trên trang (không gửi đi)
          </button>
          {demoAcknowledged || name || email || message ? (
            <button
              type="button"
              onClick={handleReset}
              className="inline-flex min-h-[2.75rem] items-center justify-center rounded-lg border border-stone-600/40 bg-stone-950/35 px-6 py-2.5 text-sm font-medium text-stone-400 transition-colors duration-200 hover:border-stone-500/45 hover:text-stone-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-600/25 focus-visible:ring-offset-2 focus-visible:ring-offset-[#0e0c0b]"
            >
              Xóa và nhập lại
            </button>
          ) : null}
        </div>
      </form>
    </section>
  );
}
