import { useMutation, useQuery } from "@tanstack/react-query";
import { Menu, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { rolesApi } from "~/api/roles-api.service";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { roleClassMap } from "../../utils";
import { RoleExtendsModal } from "./role-extends-modal";
import RoleResourceModal from "./role-resource-modal";
import { ConfirmAlert } from "~/components/btn/confirm-alert";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "~/components/ui/tooltip";
import { APPROLE } from "~/types/enum";

export interface IRoleItemProps {
  data: IRole;
  onDeleted?: () => void;
}

export default function RoleItem({ data, onDeleted }: IRoleItemProps) {
  const [role, setRole] = useState(data);

  const query = useQuery({
    queryKey: ["roles", data.id],
    queryFn: () => rolesApi.get(data.id),
    enabled: false, // <- không fetch ngay từ đầu
  });

  const deleteMutation = useMutation({
    mutationFn: () => rolesApi.delete(data),
    onSuccess: onDeleted,
  });

  const isRoot = useMemo(() => {
    return APPROLE.ROOT.includes(data.role_key);
  }, [data]);

  useEffect(() => {
    if (query.isSuccess && query.data) {
      setRole(query.data?.data);
    }
  }, [query.isSuccess, query.data]);

  useEffect(() => {
    if (!data) return;

    setRole(data);
  }, [data]);

  return (
    <div className="flex items-center justify-between p-4 border rounded-lg">
      <div className="flex items-center space-x-3">
        <Badge
          className={roleClassMap[data.role_key] || "bg-zinc-100 text-zinc-800"}
        >
          {role.role_name}
        </Badge>
        <div>
          <p className="font-medium">Vai trò {role.role_name}</p>
          <p className="text-sm text-muted-foreground">
            Cấu hình quyền mặc định cho vai trò này
          </p>
          {role.inherits?.length > 0 && (
            <p className="text-xs text-blue-600">
              Kế thừa từ: {role.inherits.join(", ")}
            </p>
          )}
        </div>
      </div>
      <div className="flex items-center space-x-2">
        <Badge variant={"secondary"}>ID: {role.id}</Badge>

        {!isRoot && (
          <RoleExtendsModal onClose={query.refetch} init={role}>
            <Button variant="outline" size="sm">
              Kế thừa
            </Button>
          </RoleExtendsModal>
        )}

        {!isRoot && (
          <RoleResourceModal role={role} allResources={role.resources}>
            <Button variant="outline" size="sm">
              Thêm resource
            </Button>
          </RoleResourceModal>
        )}

        {!isRoot && (
          <ConfirmAlert onConfirm={() => deleteMutation.mutate()}>
            <Button
              disabled={deleteMutation.isPending}
              variant="outline"
              size="sm"
            >
              <Trash2 className="h-4 w-4 text-destructive" />
            </Button>
          </ConfirmAlert>
        )}
      </div>
    </div>
  );
}
