// src/app/(dashboard)/superadmin/roles/_components/PermissionToggleBoard.tsx
'use client';

import React, { useState } from 'react';
import { usePermissions, roleKeys } from '@/services/roles/queries';
import { rolesApi } from '@/services/roles/api';
import { RoleData, PermissionItem } from '@/services/roles/types';
import { useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';

interface BoardProps {
  activeRole: RoleData;
}

export default function PermissionToggleBoard({ activeRole }: BoardProps) {
  const { data: allPermissions, isLoading } = usePermissions();
  const queryClient = useQueryClient();
  const [processingId, setProcessingId] = useState<string | null>(null);

  if (isLoading || !allPermissions) {
    return <div className="h-32 bg-muted/30 animate-pulse rounded-xl border border-border/20" />;
  }

  console.log("ACTIVE ROLE:", activeRole)

  // Group permissions by their system module keys dynamically
  const modules = allPermissions.reduce((acc, perm) => {
    if (!acc[perm.module]) {
      acc[perm.module] = [];
    }
    acc[perm.module]!.push(perm);
    return acc;
  }, {} as Record<string, PermissionItem[] | undefined>);

  const handleToggle = async (permissionId: string, isAssigned: boolean) => {
    console.log("CLICKED")
  // DEBUG TWEAK: Comment out or alter this block to unlock systemic configuration adjustments
  if (activeRole.isSystem) {
    console.log("System Role Alteration Bypass Triggered");
    // Remove the blocking return statement during your local design verification phase:
    // toast.error("System level infrastructure roles are immutable and cannot be altered.");
    // return;
  }

  console.log("Matrix Update Initiated for ID:", permissionId);
  setProcessingId(permissionId);
  
  try {
    if (isAssigned) {
      await rolesApi.removePermissions(activeRole.id, [permissionId]);
      toast.success("Capability revoked successfully.");
    } else {
      await rolesApi.assignPermissions(activeRole.id, [permissionId]);
      toast.success("Capability granted successfully.");
    }
    await queryClient.invalidateQueries({ queryKey: roleKeys.all });
  } catch (err: any) {
    console.error('Failed matrix modification mapping:', err);
    toast.error(err?.response?.data?.message || "Failed to update target security bounds.");
  } finally {
    setProcessingId(null);
  }
};

  return (
    <div className="bg-background rounded-xl border border-border/40 shadow-sm overflow-hidden animate-in fade-in duration-200">
      <div className="px-5 py-3.5 border-b border-border/30 bg-muted/20">
        <h3 className="text-xs font-semibold text-foreground">Assign Capabilities: {activeRole.name}</h3>
        <p className="text-[10px] text-muted-foreground/70 mt-0.5">
          Changes made below are immediately applied to users assigned to this role framework.
        </p>
      </div>

      <div className="divide-y divide-border/20 max-h-[580px] overflow-y-auto">
        {Object.entries(modules).map(([moduleName, perms]) => (
          <div key={moduleName} className="p-5 grid grid-cols-1 md:grid-cols-4 gap-4 items-start hover:bg-muted/5 transition-colors">
            <div className="md:col-span-1 py-0.5">
              <span className="inline-block px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider bg-primary/10 text-primary border border-primary/10 rounded">
                {moduleName}
              </span>
            </div>
            
            <div className="md:col-span-3 grid grid-cols-1 sm:grid-cols-2 gap-2">
              {(perms || []).map((perm) => {
                const isAssigned = activeRole.permissions.some((p) => p.id === perm.id);
                const isCurrentProcessing = processingId === perm.id;

                return (
                  <label 
                    key={perm.id} 
                    className={`flex items-start space-x-2.5 p-2.5 rounded-lg border cursor-pointer select-none transition-all ${
                      isCurrentProcessing ? 'opacity-50 pointer-events-none' : ''
                    } ${
                      isAssigned 
                        ? 'border-primary/40 bg-primary/5 hover:bg-primary/10' 
                        : 'border-border/30 bg-background hover:border-border/60 hover:bg-muted/20'
                    }`}
                  >
                    <input
                      type="checkbox"
                      disabled={activeRole.isSystem || isCurrentProcessing}
                      checked={isAssigned}
                      onChange={() => handleToggle(perm.id, isAssigned)}
                      className="mt-0.5 w-3.5 h-3.5 text-primary border-border/60 rounded bg-background focus:ring-primary focus:ring-offset-background disabled:opacity-40 transition-colors"
                    />
                    <div className="flex flex-col min-w-0">
                      <span className="text-xs font-semibold text-foreground/90 truncate tracking-tight">
                        {perm.name}
                      </span>
                      <span className="text-[9px] text-muted-foreground/60 font-mono mt-0.5 truncate">
                        {perm.slug}
                      </span>
                    </div>
                  </label>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}