"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Snackbar from "@mui/material/Snackbar";

import { AppButton } from "@/components/ui/button";
import { Heading } from "@/components/ui/heading";
import { RoleViewDialog } from "@/features/role/components/role-view-dialog";
import { RoleTable } from "@/features/role/components/table/role-table";
import { useRoles } from "@/features/role/hook/use-roles";
import type { Role, RoleDetail } from "@/features/role/role-data";

type Notice = { severity: "success" | "error"; message: string };

export function RoleScreen() {
  const router = useRouter();
  const { roles, isLoading, error, getRoleDetail, deleteRole } = useRoles();
  const [notice, setNotice] = useState<Notice | null>(null);
  const [viewOpen, setViewOpen] = useState(false);
  const [viewLoading, setViewLoading] = useState(false);
  const [viewError, setViewError] = useState<string | null>(null);
  const [viewRole, setViewRole] = useState<RoleDetail | null>(null);

  function openCreate() {
    router.push("/admin/role/create");
  }

  function openEdit(role: Role) {
    router.push(`/admin/role/${role.id}`);
  }

  async function openView(role: Role) {
    setViewOpen(true);
    setViewLoading(true);
    setViewError(null);
    setViewRole(null);

    try {
      const detail = await getRoleDetail(role.id);
      setViewRole(detail);
    } catch (requestError) {
      setViewError(
        requestError instanceof Error
          ? requestError.message
          : "Could not load role detail.",
      );
    } finally {
      setViewLoading(false);
    }
  }

  function closeView() {
    setViewOpen(false);
    setViewRole(null);
    setViewError(null);
  }

  async function handleDelete(role: Role) {
    if (!window.confirm(`Delete role "${role.role}"?`)) {
      return;
    }

    try {
      await deleteRole(role.id);
      setNotice({ severity: "success", message: "Role deleted successfully." });
    } catch (requestError) {
      setNotice({
        severity: "error",
        message:
          requestError instanceof Error
            ? requestError.message
            : "Could not delete the role.",
      });
    }
  }

  return (
    <Box
      sx={{
        width: "100%",
        minHeight: "calc(100dvh - 64px)",
        display: "flex",
        flexDirection: "column",
        px: { xs: 2, sm: 3, lg: 2.5 },
        pt: { xs: 3, md: 3 },
        pb: { xs: 2, lg: 2 },
      }}
    >
      <Heading
        title="Role and Permission"
        description="Manage role and permission of user"
        action={<AppButton onClick={openCreate}>Create Role</AppButton>}
        sx={{ mb: 2 }}
      />

      <RoleTable
        roles={roles}
        isLoading={isLoading}
        error={error}
        onView={openView}
        onEdit={openEdit}
        onDelete={handleDelete}
      />

      <RoleViewDialog
        open={viewOpen}
        role={viewRole}
        loading={viewLoading}
        error={viewError}
        onClose={closeView}
      />

      <Snackbar
        open={Boolean(notice)}
        autoHideDuration={3000}
        onClose={() => setNotice(null)}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
      >
        {notice ? (
          <Alert
            severity={notice.severity}
            variant="filled"
            onClose={() => setNotice(null)}
            sx={{ fontWeight: 700 }}
          >
            {notice.message}
          </Alert>
        ) : undefined}
      </Snackbar>
    </Box>
  );
}
