'use client';

import { EmptyState } from '@/components/entity-list';
import { Card, CardContent } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Role } from '@hed-hog/api-types';
import { useApp, useQuery } from '@hed-hog/next-app-provider';
import { Loader2, ShieldCheck } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { toast } from 'sonner';

type CustomRole = Role & {
  isAssigned: boolean;
};

type PermissionsSectionProps = {
  userId: number;
  onRoleChange?: () => void;
};

export function PermissionsSection({
  userId,
  onRoleChange,
}: PermissionsSectionProps) {
  const t = useTranslations('core.UserPage');
  const { request, currentLocaleCode } = useApp();
  const [togglingRoleId, setTogglingRoleId] = useState<number | null>(null);

  const {
    data: userRoles = [],
    isLoading: isLoadingUserRoles,
    refetch: refetchUserRoles,
  } = useQuery<CustomRole[]>({
    queryKey: ['user-roles', userId, currentLocaleCode],
    queryFn: async () => {
      const response = await request<CustomRole[]>({
        url: `/user/${userId}/role`,
        method: 'GET',
      });
      return response.data || [];
    },
    enabled: !!userId,
  });

  const handleToggleRole = async (roleId: number, isAssigned: boolean) => {
    setTogglingRoleId(roleId);
    try {
      if (isAssigned) {
        await request({
          url: `/user/${userId}/role/${roleId}`,
          method: 'DELETE',
        });
        toast.success(t('roleRemoved'));
      } else {
        await request({
          url: `/user/${userId}/role/${roleId}`,
          method: 'POST',
        });
        toast.success(t('roleAssigned'));
      }
      await refetchUserRoles();
      onRoleChange?.();
    } catch {
      toast.error(
        isAssigned ? t('errorRemovingRole') : t('errorAssigningRole')
      );
    } finally {
      setTogglingRoleId(null);
    }
  };

  if (isLoadingUserRoles) {
    return (
      <div className="flex items-center justify-center py-8">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        <span className="ml-2 text-sm text-muted-foreground">
          {t('loadingRoles')}
        </span>
      </div>
    );
  }

  if (!userRoles || userRoles.length === 0) {
    return (
      <EmptyState
        className="min-h-60 py-10"
        icon={<ShieldCheck className="h-12 w-12" />}
        title={t('noRolesAvailable')}
      />
    );
  }

  return (
    <div className="space-y-2">
      {userRoles.map((role, index) => {
        const isToggling = togglingRoleId === role.id;

        return (
          <Card
            key={role.id ?? `role-${index}`}
            className={`transition-all py-4 ${
              role.isAssigned
                ? 'border-primary bg-primary/5'
                : 'border-border hover:border-primary/50'
            }`}
          >
            <CardContent className="flex items-center justify-between px-4">
              <div className="flex items-center gap-2 flex-1">
                <div
                  className={`rounded-md p-2 ${
                    role.isAssigned ? 'bg-primary/10' : 'bg-muted'
                  }`}
                >
                  <ShieldCheck
                    className={`h-5 w-5 ${
                      role.isAssigned ? 'text-primary' : 'text-muted-foreground'
                    }`}
                  />
                </div>
                <div className="flex-1">
                  <Label
                    htmlFor={`role-${role.id}`}
                    className={`text-sm font-medium cursor-pointer ${
                      role.isAssigned ? 'text-foreground' : 'text-foreground'
                    }`}
                  >
                    {role.name} ({role.slug})
                  </Label>
                  {role.description && (
                    <p className="text-xs text-muted-foreground">
                      {role.description}
                    </p>
                  )}
                </div>
              </div>
              <Switch
                id={`role-${role.id}`}
                checked={role.isAssigned}
                disabled={isToggling}
                onCheckedChange={() =>
                  handleToggleRole(role.id!, role.isAssigned)
                }
                className="ml-4"
              />
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}
