"use client";

import Button from "@/components/atoms/buttons/Button";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { FormEvent, useState } from "react";

export default function CreateStaffPage() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [form, setForm] = useState({ name: "", phone: "", password: "" });
  const [errors, setErrors] = useState({
    name: "",
    phone: "",
    password: "",
    submit: "",
  });

  const validatePhone = (phone: string) =>
    /^(0[3|5|7|8|9])[0-9]{8}$/.test(phone);

  const handleChange =
    (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => {
      setForm({ ...form, [field]: e.target.value });
      setErrors({ ...errors, [field]: "", submit: "" });
    };

  const validate = () => {
    const next = { name: "", phone: "", password: "", submit: "" };
    if (!form.name.trim()) next.name = "Please enter full name";
    if (!form.phone.trim()) next.phone = "Please enter phone number";
    else if (!validatePhone(form.phone))
      next.phone = "Invalid phone number (e.g. 0987654321)";
    if (!form.password.trim()) next.password = "Please enter password";
    else if (form.password.length < 6)
      next.password = "Password must be at least 6 characters";
    setErrors(next);
    return !next.name && !next.phone && !next.password;
  };

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!validate()) return;

    setIsLoading(true);
    try {
      const res = await fetch("/api/Staff/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });

      if (res.ok || res.status === 201) {
        router.push("/manager");
      } else {
        const errorCode = (await res.text().catch(() => "")).trim();
        const errorMap: Record<string, string> = {
          ExistedUser: "Phone number already registered",
          InvalidPhoneNumber: "Invalid phone number",
          InvalidManager: "Manager account not found",
        };
        setErrors({
          ...errors,
          submit: errorMap[errorCode] ?? "An error occurred, please try again",
        });
      }
    } catch {
      setErrors({ ...errors, submit: "Unable to connect, please try again" });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="bg-background flex min-h-screen items-center justify-center px-4 py-8">
      <div className="w-full max-w-md rounded-2xl bg-white p-8 shadow-lg">
        <div className="mb-8 flex flex-col items-center">
          <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-(--color-accent-light)">
            <i className="fa-solid fa-user-plus text-2xl text-(--color-primary)"></i>
          </div>
          <h1 className="mb-1 text-2xl font-bold text-(--color-primary-dark)">
            Create Staff Account
          </h1>
          <p className="text-sm text-(--color-text-muted)">
            Add a new staff member to the restaurant
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {[
            {
              id: "name",
              label: "Full name",
              icon: "fa-user",
              placeholder: "John Doe",
              field: "name" as const,
              type: "text",
            },
            {
              id: "phone",
              label: "Phone number",
              icon: "fa-phone",
              placeholder: "0987654321",
              field: "phone" as const,
              type: "tel",
            },
            {
              id: "password",
              label: "Password",
              icon: "fa-lock",
              placeholder: "At least 6 characters",
              field: "password" as const,
              type: "password",
            },
          ].map(({ id, label, icon, placeholder, field, type }) => (
            <div key={id}>
              <label
                htmlFor={id}
                className="mb-2 block text-sm font-medium text-(--color-text-secondary)"
              >
                {label}
              </label>
              <div className="relative">
                <i
                  className={`fa-solid ${icon} absolute top-1/2 left-4 hidden -translate-y-1/2 text-(--color-text-muted) lg:block`}
                ></i>
                <input
                  id={id}
                  type={type}
                  value={form[field]}
                  onChange={handleChange(field)}
                  placeholder={placeholder}
                  disabled={isLoading}
                  className={`text-foreground focus:ring-opacity-20 w-full rounded-xl border bg-white px-4 pl-10 py-3 transition-all duration-150 outline-none placeholder:text-(--color-text-muted) focus:border-(--color-primary) focus:ring-2 focus:ring-(--color-primary) disabled:opacity-60 lg:pl-11 ${errors[field] ? "border-red-400" : "border-(--color-border)"}`}
                />
              </div>
              {errors[field] && (
                <p className="mt-1.5 flex items-center gap-1 text-xs text-red-500">
                  <i className="fa-solid fa-circle-exclamation"></i>
                  {errors[field]}
                </p>
              )}
            </div>
          ))}

          {errors.submit && (
            <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
              <i className="fa-solid fa-circle-exclamation mr-2"></i>
              {errors.submit}
            </div>
          )}

          <div className="space-y-3 pt-2">
            <Button
              variant="primaryNoBorder"
              type="submit"
              style="login"
              size="lg"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>Processing...
                </>
              ) : (
                "Create account"
              )}
            </Button>
            <Link
              href="/manager"
              className="flex w-full items-center justify-center rounded-xl border-2 border-(--color-primary) bg-white py-3 font-semibold text-(--color-primary) no-underline transition-all duration-150 hover:bg-(--color-primary) hover:text-white"
            >
              Back to Dashboard
            </Link>
          </div>
        </form>
      </div>
    </div>
  );
}
