import { Badge, Button, DescriptionCard } from "@tailor-platform/app-shell";
import { useMutation } from "urql";
import { X } from "lucide-react";
import { graphql, type FragmentOf, readFragment } from "@/graphql";
import { useToast } from "@/hooks/use-toast";

const RevokeRoleFromUserMutation = graphql(`
  mutation RevokeRoleFromUserDetail($userId: String!, $roleId: String!) {
    revokeRoleFromUser(userId: $userId, roleId: $roleId) {
      userId
      roleId
    }
  }
`);

export const UserDetailFragment = graphql(`
  fragment UserDetail on User {
    id
    name
    email
    status
    createdAt
    updatedAt
    userRoles {
      edges {
        node {
          id
          role {
            id
            name
          }
        }
      }
    }
  }
`);

interface UserDetailProps {
  user: FragmentOf<typeof UserDetailFragment>;
}

export const UserDetail = ({ user: userFragment }: UserDetailProps) => {
  const user = readFragment(UserDetailFragment, userFragment);
  const roles = user.userRoles.edges.map((edge) => edge.node);
  const toast = useToast();
  const [{ fetching: revoking }, revokeRole] = useMutation(RevokeRoleFromUserMutation);

  const handleRemoveRole = (roleId: string, roleName: string) => {
    void revokeRole(
      { userId: user.id, roleId },
      { additionalTypenames: ["User", "UserRole"] },
    ).then((result) => {
      if (result.error) {
        toast.error(result.error);
        return;
      }
      toast.success(`Role "${roleName}" removed`);
    });
  };

  return (
    <div className="space-y-4">
      <DescriptionCard
        data={user}
        title="User Information"
        columns={3}
        fields={[
          { key: "name", label: "Name" },
          { key: "email", label: "Email", meta: { copyable: true } },
          {
            key: "status",
            label: "Status",
            type: "badge",
            meta: {
              badgeVariantMap: {
                ACTIVE: "success",
                PENDING: "warning",
                INACTIVE: "neutral",
              },
            },
          },
          { type: "divider" },
          {
            key: "createdAt",
            label: "Created At",
            type: "date",
            meta: { dateFormat: "medium" },
          },
          {
            key: "updatedAt",
            label: "Updated At",
            type: "date",
            meta: { dateFormat: "relative" },
          },
        ]}
      />
      <div className="rounded-lg border p-4">
        <h3 className="mb-3 text-sm font-medium">Assigned Roles</h3>
        {roles.length > 0 ? (
          <div className="flex flex-wrap gap-2">
            {roles.map((userRole) => (
              <Badge key={userRole.id} className="flex items-center gap-1">
                {userRole.role?.name ?? "-"}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-4 w-4 p-0"
                  disabled={revoking}
                  onClick={() => handleRemoveRole(userRole.role!.id, userRole.role!.name)}
                >
                  <X className="h-3 w-3" />
                </Button>
              </Badge>
            ))}
          </div>
        ) : (
          <p className="text-muted-foreground text-sm">No roles assigned</p>
        )}
      </div>
    </div>
  );
};
