import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { RoleWithPermissions } from "@/features/roles/types"
import { formatPermissionBadge } from "@/lib/shared/constants/modules"

export default function RoleList({ roles }: { roles: RoleWithPermissions[] }) {
  return (
    <Card className="w-full overflow-hidden">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-[200px]">Name</TableHead>
            <TableHead>Permissions</TableHead>
            <TableHead className="w-[100px] text-right">Action</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {roles.map((role) => (
            <TableRow key={role.id}>
              <TableCell className="font-medium align-top">{role.name}</TableCell>
              <TableCell className="align-top">
                <div className="flex flex-wrap gap-1.5 max-w-[600px]">
                  {role.permissions && role.permissions.length > 0 ? (
                    role.permissions.flatMap((perm) =>
                      perm.actions.map((action) => (
                        <Badge
                          key={`${role.id}-${perm.module}-${action}`}
                          variant="secondary"
                          className="text-xs bg-primary/10 text-primary hover:bg-primary/20 border-primary/20"
                        >
                          {formatPermissionBadge(perm.module, action)}
                        </Badge>
                      ))
                    )
                  ) : (
                    <span className="text-sm text-muted-foreground">No permissions</span>
                  )}
                </div>
              </TableCell>
              <TableCell className="text-right align-top">
                <Button asChild variant="ghost" size="sm" className="h-8 w-8 p-0">
                  <a href={`/roles/edit/${role.id}`}>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="text-primary"
                    >
                      <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
                    </svg>
                    <span className="sr-only">Edit</span>
                  </a>
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Card>
  )
}
