import React from 'react';
import { cn } from '@/lib/utils';
import { Info } from 'lucide-react';
import { toast } from 'sonner';
import { GrKanbanCard } from './GrKanbanCard';

/**
 * Gr Kanban Board
 * Production version - Clean and functional.
 * Adapted for GR environment.
 */
export const GrKanbanBoard = ({ 
  columns = [], 
  onCardClick,
  onCardMove,
  userRole,
  className,
  allowRoleMovement = false // Nova prop para permitir movimento independente do cargo
}) => {
  const [draggedOverCol, setDraggedOverCol] = React.useState(null);

  const handleDragOver = (e, colId) => {
    e.preventDefault();
    setDraggedOverCol(colId);
  };

  const handleDragLeave = () => {
    setDraggedOverCol(null);
  };

  const handleDrop = (e, targetStatus) => {
    e.preventDefault();
    setDraggedOverCol(null);
    try {
      const cardData = JSON.parse(e.dataTransfer.getData("application/json"));
      // Verificar se o card está bloqueado antes de permitir movimento
      if (cardData.isBlocked) {
        // Cards bloqueados (Agregado/Rentals sem contrato assinado) só podem ficar em "Aguardando Análise"
        if (targetStatus !== 'aguardando') {
          toast.error("Cadastros com modalidade Agregado ou Rentals não podem sair de 'Aguardando Análise' até terem contrato ASSINADO.");
          return; // Impede movimento para outras colunas
        }
      }

      // Impedir que Despachantes e Coordenadores movam cards, A MENOS que allowRoleMovement seja true
      if (!allowRoleMovement && (userRole === 'Despachante' || userRole === 'Coordenador')) {
        toast.error("Acesso restrito", {
          description: `${userRole}s não possuem permissão para mover cards entre colunas.`
        });
        return;
      }

      if (cardData.status !== targetStatus) {
        onCardMove?.(cardData.id, targetStatus);
      }
    } catch (err) {
      console.error("Error parsing drop data:", err);
    }
  };

  // Ensure columns is an array
  const safeColumns = Array.isArray(columns) ? columns : [];

  return (
    <div className={cn("flex gap-4 h-full w-full overflow-x-auto pb-4 custom-scrollbar min-h-0", className)}>
      {safeColumns.map((column) => {
        // Ensure cards is an array
        const safeCards = Array.isArray(column.cards) ? column.cards : [];
        
        return (
        <div 
          key={column.id} 
          onDragOver={(e) => handleDragOver(e, column.title)}
          onDragLeave={handleDragLeave}
          onDrop={(e) => handleDrop(e, column.id)}
          className={cn(
            "flex-shrink-0 flex-1 min-w-[280px] max-w-[320px] flex flex-col bg-slate-50/80 dark:bg-black/40 rounded-[32px] border transition-all duration-300 backdrop-blur-md h-full max-h-[calc(100vh-240px)] overflow-visible",
            draggedOverCol === column.title 
              ? "border-[var(--gr-primary)] bg-[var(--gr-primary)]/10 scale-[1.01] ring-4 ring-[var(--gr-primary)]/10 shadow-lg" 
              : "border-slate-200/60 dark:border-white/5"
          )}
        >
          {/* Column Header */}
          <div className="p-5 flex items-center justify-between bg-white/40 dark:bg-white/5 rounded-t-[32px] border-b border-slate-100 dark:border-white/5">
            <div className="flex items-center gap-2">
              <div className={cn(
                "w-2.5 h-2.5 rounded-full shadow-[0_0_10px_rgba(0,0,0,0.1)]",
                column.color === 'blue' && "bg-blue-500 shadow-blue-500/20",
                column.color === 'emerald' && "bg-[var(--gr-primary)] shadow-emerald-500/20",
                column.color === 'orange' && "bg-orange-500 shadow-orange-500/20",
                column.color === 'red' && "bg-red-500 shadow-red-500/20",
                column.color === 'slate' && "bg-slate-400 shadow-slate-400/20"
              )} />
              <h2 className="text-[12px] font-medium uppercase text-slate-800 dark:text-slate-200 tracking-[0.05em]">
                {column.title}
              </h2>
              <span className="ml-2 px-2.5 py-0.5 rounded-full bg-slate-200/50 dark:bg-white/10 text-[10px] font-medium text-slate-600 dark:text-slate-400">
                {safeCards.length}
              </span>
            </div>
          </div>

          {/* Cards Area */}
          <div className="flex-1 px-3 py-4 overflow-y-auto custom-scrollbar min-h-0">
            <div className="flex flex-col gap-4 pb-2">
              {safeCards.map((card, idx) => (
                <div key={`${card.id}-${idx}`} className="group relative">
                  <GrKanbanCard 
                    item={card} 
                    title={card.title}
                    subtitle={card.subtitle}
                    date={card.date}
                    base={card.base}
                    details={card.details}
                    statusColor={column.color}
                    isPendencia={column.id === 'pendencias'}
                    observation={column.id === 'pendencias' ? card.obs_retorno : null}
                    onClick={() => onCardClick?.(card)}
                    isBlocked={card.isBlocked}
                    dragDisabled={!allowRoleMovement && (userRole === 'Despachante' || userRole === 'Coordenador')}
                  />
                </div>
              ))}
              
              {safeCards.length === 0 && (
                <div className="mt-8 flex flex-col items-center justify-center opacity-20 italic">
                   <div className="w-12 h-12 border-2 border-dashed border-slate-400 rounded-xl mb-2" />
                   <span className="text-[10px] font-medium uppercase tracking-widest text-slate-500">Sem Itens</span>
                </div>
              )}
            </div>
          </div>
        </div>
      );
      })}
    </div>
  );
};
