import React from 'react';
import { User, CreditCard, Car, Calendar, Building2, Briefcase, Info, FileText, CheckCircle, Clock, MapPin } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
} from '@/components/ui/dropdown-menu';

/**
 * Gr Kanban Card
 * Customized for GR environment to match specific visual requirements.
 */
export const GrKanbanCard = ({ 
  item, // Accept the full item object
  title, 
  subtitle, 
  details = [], 
  date,
  base,
  statusColor = "emerald", 
  onClick,
  className,
  isPendencia,
  observation: obsText,
  isBlocked = false, // Novo prop para indicar se o card está bloqueado
  dragDisabled = false // Novo prop para desabilitar o arraste (ex: para Despachantes)
}) => {
  const handleDragStart = (e) => {
    if (isBlocked || dragDisabled) {
      e.preventDefault();
      return;
    }
    e.dataTransfer.setData("application/json", JSON.stringify(item));
    e.dataTransfer.effectAllowed = "move";
  };

  // Debug: verificar se os valores estão chegando
  if (isPendencia) {
    console.log('🔍 GrKanbanCard Debug:', {
      title,
      isPendencia,
      obsText,
      hasObservation: !!obsText,
      item
    });
  }


  const handleClick = (e) => {
    // Se não estiver bloqueado, executar o onClick normalmente
    onClick?.(e);
  };

  return (
    <div 
      onClick={handleClick}
      draggable={!isBlocked && !dragDisabled}
      onDragStart={handleDragStart}
      className={cn(
        "group relative bg-white dark:bg-[#1a1a1a] border border-slate-200 dark:border-white/5 rounded-[24px] p-6 shadow-sm hover:shadow-xl hover:shadow-slate-200/50 dark:hover:shadow-black/40 transition-all duration-300 block select-none",
        isBlocked 
          ? "cursor-pointer opacity-80 border-amber-300 dark:border-amber-500/30 hover:-translate-y-1" 
          : "cursor-pointer hover:-translate-y-1",
        className
      )}
      title={isBlocked ? "Este cadastro está travado. É necessário ter um contrato assinado ou não assinado para movê-lo." : undefined}
    >
      {/* Status Dot Indicator */}
      <div className={cn(
        "absolute top-4 right-4 w-2 h-2 rounded-full",
        statusColor === 'blue' && "bg-blue-500",
        statusColor === 'emerald' && "bg-emerald-500",
        statusColor === 'orange' && "bg-orange-500",
        statusColor === 'red' && "bg-red-500",
        statusColor === 'slate' && "bg-slate-400"
      )} />

      <div className="flex gap-4">
        {/* Avatar Area */}
        <div className="shrink-0 pt-1">
          <div className="w-10 h-10 bg-slate-100 dark:bg-white/5 rounded-full flex items-center justify-center text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-white/10">
            <User size={20} strokeWidth={2.5} />
          </div>
        </div>

        {/* Content Area */}
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2 mb-2">
            <h3 className="text-[11px] font-medium text-slate-800 dark:text-slate-100 uppercase tracking-tight leading-4 pr-4">
              {title}
            </h3>
            
            {isPendencia && obsText && (
              <div className="shrink-0" onClick={(e) => e.stopPropagation()}>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <button className="p-1 bg-amber-500/10 rounded-md text-amber-600 hover:bg-amber-500/20 transition-colors">
                      <Info size={14} />
                    </button>
                  </DropdownMenuTrigger>
                  
                  <DropdownMenuContent 
                    side="bottom" 
                    align="end" 
                    sideOffset={8}
                    className="w-[240px] p-0 bg-transparent border-none shadow-none"
                    style={{ zIndex: 99999 }}
                  >
                    <div className="bg-white/98 dark:bg-[#1a1a1a]/98 backdrop-blur-xl border border-amber-500/30 rounded-[20px] p-4 text-center shadow-[0_20px_50px_rgba(0,0,0,0.2)] dark:shadow-[0_20px_50px_rgba(0,0,0,0.5)] max-h-[180px] flex flex-col items-center">
                        <div className="w-8 h-8 bg-amber-500/10 rounded-lg flex items-center justify-center mb-2 text-amber-600 shrink-0">
                            <Info size={16} />
                        </div>
                        <h4 className="text-[9px] font-medium uppercase tracking-[0.2em] text-amber-600/70 mb-2 shrink-0">Obs. de Retorno</h4>
                        <div className="overflow-y-auto custom-scrollbar pr-1 w-full text-left">
                            <p className="text-[11px] font-normal text-slate-700 dark:text-slate-200 leading-relaxed">
                                "{obsText}"
                            </p>
                        </div>
                    </div>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            )}
          </div>

          {/* Details List */}
          <div className="space-y-1.5 mb-4">
            {/* CPF */}
             <div className="flex items-center gap-2 text-slate-500 dark:text-slate-400">
               <CreditCard size={12} className="shrink-0" />
               <span className="text-[10px] font-normal leading-none">
                  CPF: <span className={cn(
                    "font-medium",
                    isPendencia && item.status_doc_motorista === 'Aprovado' ? "text-emerald-600 dark:text-emerald-400" :
                    isPendencia && item.status_doc_motorista === 'Reprovado' ? "text-red-500" :
                    "text-slate-600 dark:text-slate-300"
                  )}>{subtitle}</span>
               </span>
             </div>

             {/* Custom Details Mapping */}
             {(Array.isArray(details) ? details : []).map((detail, idx) => {
               const isPlaca = detail.label === 'Placa';
               const highlightPlaca = isPendencia && isPlaca;
               
               // Ícones para diferentes tipos de detalhes
               const getIcon = (label) => {
                 switch (label) {
                   case 'Placa': return <Car size={12} className="shrink-0" />;
                   case 'Modalidade': return <Briefcase size={12} className="shrink-0" />;
                   case 'Base': return <Building2 size={12} className="shrink-0" />;
                   case 'Tipo Contrato': return <FileText size={12} className="shrink-0" />;
                   case 'Status Assinatura': return <CheckCircle size={12} className="shrink-0" />;
                   case 'Admissão': return <Calendar size={12} className="shrink-0" />;
                   case 'Contrato': return <FileText size={12} className="shrink-0" />;
                   case 'Assinatura': return <Clock size={12} className="shrink-0" />;
                   case 'Rota': return <MapPin size={12} className="shrink-0" />;
                   default: return null;
                 }
               };
               
               return (
                 <div key={idx} className="flex items-center gap-2 text-slate-500 dark:text-slate-400">
                   {getIcon(detail.label)}
                   
                   <span className="text-[10px] font-normal leading-none">
                     {detail.label}: <span className={cn(
                        "font-medium",
                        isPendencia && detail.label === 'Placa' && item.status_doc_carro === 'Aprovado' ? "text-emerald-600 dark:text-emerald-400" :
                        isPendencia && detail.label === 'Placa' && item.status_doc_carro === 'Reprovado' ? "text-red-500" :
                        detail.label === 'Status Assinatura' && detail.value === 'Assinado' ? "text-emerald-600 dark:text-emerald-400" :
                        detail.label === 'Status Assinatura' && detail.value === 'Não Assinado' ? "text-red-500" :
                        detail.label === 'Status Assinatura' && detail.value === 'Em andamento' ? "text-orange-500" :
                        "text-slate-600 dark:text-slate-300"
                     )}>{detail.value}</span>
                   </span>
                 </div>
               );
             })}
          </div>

          <div className="h-px w-full bg-slate-100 dark:bg-white/5 mb-3"></div>

          {/* Footer */}
          <div className="flex items-center justify-between text-[0.6vw] font-medium text-slate-400 dark:text-slate-500 uppercase tracking-wider min-w-0 gap-2">
            <div className="flex items-center gap-1.5 shrink-0">
               <Calendar size={10} className="mb-0.5" />
               <span className="whitespace-nowrap">
                 {typeof date === 'string' && date.includes('00:00:00') ? date.split(' ')[0] : date}
               </span>
            </div>
            
            {base && (
              <div className="flex items-center gap-1.5 min-w-0">
                <Building2 size={10} className="mb-0.5 shrink-0" />
                <span className="truncate">{base}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

