"use client"

import * as React from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { Plus, Shield, ShieldCheck, ShieldAlert, MoreHorizontal, Pencil, Trash2, Power } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableCaption,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { useActionMutation } from "@/shared/hooks/use-action-mutation"
import { formatDate } from "@/shared/lib/utils"
import { useTranslations } from "next-intl"

import { deleteRoleAction, toggleRoleEnabledAction } from "../actions"
import type { RoleWithStats } from "../types"

interface RoleListProps {
  roles: RoleWithStats[]
}

/**
 * Admin role management list view.
 *
 * Renders a table of roles with their type (system/custom), status, permission
 * and user counts, and a row menu with edit / toggle / delete actions.
 */
export function RoleList({ roles }: RoleListProps) {
  const router = useRouter()
  const t = useTranslations("rbac")
  const [deleteTarget, setDeleteTarget] = React.useState<RoleWithStats | null>(null)

  const toggleMutation = useActionMutation({
    successMessage: t("messages.roleStatusUpdated"),
    onSuccess: () => router.refresh(),
  })

  const deleteMutation = useActionMutation({
    successMessage: t("messages.deleted"),
    onSuccess: () => {
      setDeleteTarget(null)
      router.refresh()
    },
  })

  const handleToggle = (role: RoleWithStats): void => {
    void toggleMutation.mutate(() => toggleRoleEnabledAction(role.id, !role.isEnabled))
  }

  const handleDelete = (): void => {
    if (!deleteTarget) return
    void deleteMutation.mutate(() => deleteRoleAction(deleteTarget.id))
  }

  if (roles.length === 0) {
    return (
      <EmptyState
        icon={Shield}
        title={t("roles.emptyTitle")}
        description={t("roles.emptyDescription")}
        action={{
          label: t("roles.create"),
          href: "/admin/roles?new=1",
          variant: "default",
        }}
      />
    )
  }

  return (
    <>
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">{t("roles.listTitle", { count: roles.length })}</CardTitle>
          <Button asChild size="sm">
            <Link href="/admin/roles?new=1">
              <Plus className="mr-2 h-4 w-4" />
              {t("roles.create")}
            </Link>
          </Button>
        </CardHeader>
        <CardContent>
          <Table aria-label={t("roles.tableAriaLabel")}>
            <TableCaption className="sr-only">
              {t("roles.tableCaption", { count: roles.length })}
            </TableCaption>
            <TableHeader>
              <TableRow>
                <TableHead>{t("roles.name")}</TableHead>
                <TableHead>{t("roles.description")}</TableHead>
                <TableHead>{t("roles.type")}</TableHead>
                <TableHead>{t("roles.status")}</TableHead>
                <TableHead className="text-center">{t("roles.permissions")}</TableHead>
                <TableHead className="text-center">{t("roles.users")}</TableHead>
                <TableHead>{t("roles.updated")}</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {roles.map((role) => {
                const isAdmin = role.name === "admin"
                return (
                  <TableRow key={role.id}>
                    <TableCell className="font-medium">
                      <Link
                        href={`/admin/roles/${role.id}`}
                        className="text-primary hover:underline"
                      >
                        {role.name}
                      </Link>
                    </TableCell>
                    <TableCell className="max-w-48 truncate text-muted-foreground">
                      {role.description ?? "—"}
                    </TableCell>
                    <TableCell>
                      {role.isSystem ? (
                        <Badge variant="secondary">
                          <ShieldCheck className="mr-1 h-3 w-3" />
                          {t("roles.system")}
                        </Badge>
                      ) : (
                        <Badge variant="outline">
                          <Shield className="mr-1 h-3 w-3" />
                          {t("roles.custom")}
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      {role.isEnabled ? (
                        <Badge variant="default">{t("roles.enabled")}</Badge>
                      ) : (
                        <Badge variant="destructive">{t("roles.disabled")}</Badge>
                      )}
                    </TableCell>
                    <TableCell className="text-center">{role.permissionCount}</TableCell>
                    <TableCell className="text-center">{role.userCount}</TableCell>
                    <TableCell className="text-muted-foreground">
                      {formatDate(role.updatedAt)}
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreHorizontal className="h-4 w-4" />
                            <span className="sr-only">{t("roles.openMenu")}</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem asChild>
                            <Link href={`/admin/roles/${role.id}`}>
                              <Pencil className="mr-2 h-4 w-4" />
                              {t("actions.edit")}
                            </Link>
                          </DropdownMenuItem>
                          {!isAdmin && (
                            <DropdownMenuItem onClick={() => handleToggle(role)}>
                              <Power className="mr-2 h-4 w-4" />
                              {role.isEnabled ? t("actions.disable") : t("actions.enable")}
                            </DropdownMenuItem>
                          )}
                          {!role.isSystem && (
                            <>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                className="text-destructive focus:text-destructive"
                                onClick={() => setDeleteTarget(role)}
                              >
                                <Trash2 className="mr-2 h-4 w-4" />
                                {t("actions.delete")}
                              </DropdownMenuItem>
                            </>
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <AlertDialog
        open={Boolean(deleteTarget)}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <ShieldAlert className="h-5 w-5 text-destructive" />
              {t("roles.deleteConfirmTitle", { name: deleteTarget?.name ?? "" })}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("roles.deleteConfirmDescription", { count: deleteTarget?.userCount ?? 0 })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleteMutation.isWorking}>{t("actions.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleteMutation.isWorking}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteMutation.isWorking ? t("actions.deleting") : t("actions.delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
