"use client";

import * as React from "react";
import { useActionState } from "react";
import { Plus, TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Alert } from "@/components/ui/alert";
import { Field, Input, Select } from "@/components/ui/input";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { createUserAction, updateUserAction } from "@/actions/admin";
import { IDLE_ACTION } from "@/lib/action-state";
import { ROLE_LABELS } from "@/lib/roles";

const ROLES = (["ADMIN", "TEACHER", "STUDENT"] as const).map((role) => ({
  value: role,
  label: ROLE_LABELS[role],
}));

const STATUSES = [
  { value: "ACTIVE", label: "Aktif" },
  { value: "PENDING", label: "Menunggu" },
  { value: "SUSPENDED", label: "Ditangguhkan" },
];

export interface UserFormValues {
  id: string;
  username: string;
  fullName: string;
  email: string | null;
  role: string;
  status: string;
  school: string | null;
  gradeLevel: string | null;
}

/**
 * Create/edit dialog for a platform user.
 *
 * One component serves both modes because the field set is nearly identical;
 * only the action, the password field and the initial values differ.
 */
export function UserFormDialog({
  mode,
  user,
  trigger,
  open: controlledOpen,
  onOpenChange,
}: {
  mode: "create" | "edit";
  user?: UserFormValues;
  trigger?: React.ReactNode;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}) {
  const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false);
  const open = controlledOpen ?? uncontrolledOpen;
  const setOpen = onOpenChange ?? setUncontrolledOpen;

  const action = mode === "create" ? createUserAction : updateUserAction;
  const [state, formAction, pending] = useActionState(action, IDLE_ACTION);

  React.useEffect(() => {
    if (state.status === "success") setOpen(false);
  }, [state.status, setOpen]);

  const errors = state.status === "error" ? state.errors : undefined;

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}

      <DialogContent size="lg">
        <form action={formAction} className="flex min-h-0 flex-1 flex-col">
          {user ? <input type="hidden" name="userId" value={user.id} /> : null}

          <DialogHeader>
            <DialogTitle>{mode === "create" ? "Tambah Pengguna" : "Ubah Pengguna"}</DialogTitle>
            <DialogDescription>
              {mode === "create"
                ? "Akun baru langsung dapat digunakan sesuai status yang dipilih."
                : "Perbarui profil, peran, dan status akun ini."}
            </DialogDescription>
          </DialogHeader>

          <DialogBody className="space-y-4">
            {state.status === "error" && state.message ? (
              <Alert tone="danger" icon={<TriangleAlert className="size-4" />}>
                {state.message}
              </Alert>
            ) : null}

            <div className="grid gap-4 sm:grid-cols-2">
              <Field label="Nama Lengkap" htmlFor="fullName" required error={errors?.fullName}>
                <Input
                  id="fullName"
                  name="fullName"
                  defaultValue={user?.fullName}
                  placeholder="mis. Nadia Prameswari"
                  required
                  autoFocus
                />
              </Field>

              {mode === "create" ? (
                <Field
                  label="Username"
                  htmlFor="username"
                  required
                  hint="Huruf, angka, titik, garis bawah, dan tanda hubung."
                  error={errors?.username}
                >
                  <Input id="username" name="username" placeholder="mis. nadia.p" required />
                </Field>
              ) : (
                <Field label="Username" htmlFor="username-readonly" hint="Username tidak dapat diubah.">
                  <Input id="username-readonly" value={user?.username ?? ""} readOnly disabled />
                </Field>
              )}
            </div>

            <Field label="Email" htmlFor="email" error={errors?.email}>
              <Input
                id="email"
                name="email"
                type="email"
                defaultValue={user?.email ?? ""}
                placeholder="nama@sekolah.sch.id"
              />
            </Field>

            {mode === "create" ? (
              <Field
                label="Kata Sandi Awal"
                htmlFor="password"
                required
                hint="Minimal 8 karakter, mengandung huruf dan angka."
                error={errors?.password}
              >
                <Input id="password" name="password" type="password" required />
              </Field>
            ) : null}

            <div className="grid gap-4 sm:grid-cols-2">
              <Field label="Peran" htmlFor="role" error={errors?.role}>
                <Select id="role" name="role" defaultValue={user?.role ?? "STUDENT"}>
                  {ROLES.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>

              <Field label="Status" htmlFor="status" error={errors?.status}>
                <Select id="status" name="status" defaultValue={user?.status ?? "ACTIVE"}>
                  {STATUSES.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <Field label="Sekolah" htmlFor="school" error={errors?.school}>
                <Input
                  id="school"
                  name="school"
                  defaultValue={user?.school ?? ""}
                  placeholder="mis. SMP Negeri 1 Bandung"
                />
              </Field>

              <Field label="Tingkat Kelas" htmlFor="gradeLevel" error={errors?.gradeLevel}>
                <Input
                  id="gradeLevel"
                  name="gradeLevel"
                  defaultValue={user?.gradeLevel ?? ""}
                  placeholder="mis. 8"
                />
              </Field>
            </div>
          </DialogBody>

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => setOpen(false)}>
              Batal
            </Button>
            <Button type="submit" loading={pending}>
              {mode === "create" ? "Tambah Pengguna" : "Simpan Perubahan"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

/** Create-mode trigger used in the page header. */
export function CreateUserDialog() {
  return (
    <UserFormDialog
      mode="create"
      trigger={
        <Button>
          <Plus className="size-4" />
          Tambah Pengguna
        </Button>
      }
    />
  );
}
