"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input, Select } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { cardClasses } from "@/components/ui/styles";
import { clientFetch } from "@/lib/api/client";

const ROLE_OPTIONS = [
  { value: "organizer", label: "Organizer" },
  { value: "petugas", label: "Staff" },
];

/** FR-085 extension: admin mints an Organizer/Petugas account directly, no apply/approve step. */
export function CreateStaffAccountForm() {
  const router = useRouter();
  const [isOpen, setIsOpen] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("organizer");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string[]> | null>(null);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  function reset() {
    setName("");
    setEmail("");
    setPassword("");
    setRole("organizer");
    setErrors(null);
    setError(null);
  }

  async function handleSubmit(formEvent: FormEvent<HTMLFormElement>) {
    formEvent.preventDefault();
    setError(null);
    setErrors(null);
    setIsSubmitting(true);

    const res = await clientFetch("/api/admin/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, email, password, role }),
    });

    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      setErrors(body?.errors ?? null);
      const message = body?.errors ? null : (body?.message ?? "Failed to create account.");
      setError(message);
      toast(message ?? "Please check the entered data.", "error");
      return;
    }

    setIsOpen(false);
    reset();
    toast("Account created successfully.", "success");
    router.refresh();
  }

  if (!isOpen) {
    return (
      <Button type="button" size="sm" onClick={() => setIsOpen(true)}>
        + Create Staff / Organizer Account
      </Button>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className={cardClasses("flex flex-col gap-3 p-4")}
    >
      <p className="text-sm font-medium">Create Staff / Organizer Account</p>

      <label className="flex flex-col gap-1 text-xs font-medium">
        Name
        <Input required size="sm" value={name} onChange={(e) => setName(e.target.value)} />
        {errors?.name && <span className="text-xs font-normal text-red-600">{errors.name[0]}</span>}
      </label>

      <label className="flex flex-col gap-1 text-xs font-medium">
        Email
        <Input required type="email" size="sm" value={email} onChange={(e) => setEmail(e.target.value)} />
        {errors?.email && <span className="text-xs font-normal text-red-600">{errors.email[0]}</span>}
      </label>

      <label className="flex flex-col gap-1 text-xs font-medium">
        Password
        <Input
          required
          type="password"
          size="sm"
          minLength={8}
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        {errors?.password && <span className="text-xs font-normal text-red-600">{errors.password[0]}</span>}
      </label>

      <label className="flex flex-col gap-1 text-xs font-medium">
        Role
        <Select size="sm" value={role} onChange={(e) => setRole(e.target.value)}>
          {ROLE_OPTIONS.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
        {errors?.role && <span className="text-xs font-normal text-red-600">{errors.role[0]}</span>}
      </label>

      {error && <p className="text-xs text-red-600">{error}</p>}

      <div className="flex gap-2">
        <Button type="submit" size="sm" loading={isSubmitting}>
          Create Account
        </Button>
        <Button
          type="button"
          variant="secondary"
          size="sm"
          disabled={isSubmitting}
          onClick={() => {
            setIsOpen(false);
            reset();
          }}
        >
          Cancel
        </Button>
      </div>
    </form>
  );
}
