import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Info } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";

interface Permission {
  id: number;
  name: string;
  code: string;
  description?: string;
}

interface PermissionCategory {
  category: string;
  permissions: Permission[];
}

interface PermissionSelectorProps {
  permissionsByCategory: PermissionCategory[];
  selectedPermissions: number[];
  onChange: (selectedPermissions: number[]) => void;
  disabled?: boolean;
  isAdmin?: boolean;
}

export function PermissionSelector({
  permissionsByCategory,
  selectedPermissions,
  onChange,
  disabled = false,
  isAdmin = false
}: PermissionSelectorProps) {
  // Handle permission checkbox change
  const handlePermissionChange = (permissionId: number) => {
    const newSelectedPermissions = selectedPermissions.includes(permissionId)
      ? selectedPermissions.filter(id => id !== permissionId)
      : [...selectedPermissions, permissionId];
    
    onChange(newSelectedPermissions);
  };

  // Handle selecting/deselecting all permissions in a category
  const handleSelectCategory = (category: string) => {
    const categoryData = permissionsByCategory.find(c => c.category === category);
    if (!categoryData) return;
    
    const categoryPermIds = categoryData.permissions.map(p => p.id);
    
    // Check if all permissions in category are already selected
    const allSelected = categoryPermIds.every(id => selectedPermissions.includes(id));
    
    // If all selected, deselect all; otherwise select all
    const newSelectedPermissions = allSelected
      ? selectedPermissions.filter(id => !categoryPermIds.includes(id))
      : [...new Set([...selectedPermissions, ...categoryPermIds])];
    
    onChange(newSelectedPermissions);
  };

  // Check if there are no permission categories
  if (!permissionsByCategory || permissionsByCategory.length === 0) {
    return (
      <div className="text-center py-4">
        <p className="text-muted-foreground">No permissions available</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <h3 className="text-lg font-medium">Permissions</h3>
      {isAdmin && (
        <Alert variant="destructive">
          <AlertDescription>
            Administrators have access to all permissions by default. Individual permissions cannot be edited for admin users.
          </AlertDescription>
        </Alert>
      )}
      
      {permissionsByCategory.map(category => (
        <Card key={category.category} className="mb-4">
          <CardHeader className="pb-2 flex flex-row items-center justify-between pt-2">
            <CardTitle className="text-md">{category.category}</CardTitle>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => handleSelectCategory(category.category)}
              disabled={disabled}
            >
              {category.permissions.every(p => selectedPermissions.includes(p.id))
                ? 'Deselect All'
                : 'Select All'}
            </Button>
          </CardHeader>
          
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {category.permissions.map(permission => (
                <div key={permission.id} className="flex items-center space-x-2 py-1">
                  <Checkbox
                    id={`permission-${permission.id}`}
                    checked={selectedPermissions.includes(permission.id)}
                    onCheckedChange={() => handlePermissionChange(permission.id)}
                    disabled={disabled}
                  />
                  <label
                    htmlFor={`permission-${permission.id}`}
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 flex items-center"
                  >
                    {permission.name}
                    
                    {permission.description && (
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Info className="h-3.5 w-3.5 ml-1 text-muted-foreground" />
                          </TooltipTrigger>
                          <TooltipContent>
                            <p>{permission.description}</p>
                            <p className="text-xs text-muted-foreground mt-1">Code: {permission.code}</p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    )}
                  </label>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
} 