import React from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Users } from 'lucide-react';

/**
 * Componente de Formulário de Usuário para o GR.
 * Encapsula a lógica de cadastro/edição, incluindo visibilidade condicional de campos.
 */
export const GrUserForm = ({ 
  formData, 
  handleInputChange, 
  handleSaveUser, 
  groups = [], 
  bases = [], 
  responsibles = [],
  isEditing = false
}) => {

  // Lógica para verificar se o grupo selecionado é de Coordenadores
  // Ajuste conforme os nomes exatos retornados pela API/Banco
  const isCoordinatorGroup = (groupName) => {
    if (!groupName) return false;
    const lowerName = groupName.toLowerCase();
    return lowerName.includes('coordenador') || lowerName.includes('coordenação');
  };

  const showBaseField = !isCoordinatorGroup(formData.grupo);

  return (
    <form id="user-form" onSubmit={handleSaveUser} className="space-y-8 animate-in fade-in duration-500">
      
      {/* 1. Nome Completo */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Nome <span className="text-red-500">*</span></Label>
        <Input 
          value={formData.nome_completo}
          onChange={(e) => handleInputChange('nome_completo', e.target.value)}
          placeholder="Nome completo" 
          className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20" 
          required
        />
      </div>

      {/* 2. Email */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Email <span className="text-red-500">*</span></Label>
        <Input 
          type="email" 
          value={formData.email}
          onChange={(e) => handleInputChange('email', e.target.value)}
          placeholder="email@exemplo.com" 
          className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20" 
          required
        />
      </div>

      {/* 3. Senha */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Senha</Label>
        <Input 
          type="password" 
          value={formData.password}
          onChange={(e) => handleInputChange('password', e.target.value)}
          placeholder={isEditing ? "Deixe em branco para manter" : "Senha de acesso"} 
          className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20" 
          required={!isEditing}
        />
      </div>

      {/* 4. Setor (Fixo por enquanto) */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Setor</Label>
        <Select 
          value={formData.setor}
          onValueChange={(val) => handleInputChange('setor', val)}
          disabled 
        >
          <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm opacity-60">
            <SelectValue placeholder="Gestão de Risco" />
          </SelectTrigger>
          <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10">
            <SelectItem value="Gestão de Risco">Gestão de Risco</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 5. Grupo (Movido para baixo de Setor conforme solicitado) */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Grupo</Label>
        <Select 
          value={formData.grupo}
          onValueChange={(val) => handleInputChange('grupo', val)}
        >
          <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20">
            <SelectValue placeholder="Escolha uma opção..." />
          </SelectTrigger>
          <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 max-h-[200px]">
            {groups.map(g => (
              <SelectItem key={g.id || g.grupo} value={g.grupo || g.nome}>
                {g.grupo || g.nome}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 6. Base (Oculto se for Coordenador) */}
      {showBaseField && (
        <div className="space-y-2 animate-in slide-in-from-top-2 duration-300">
          <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Bases (Múltipla Seleção) <span className="text-red-500">*</span></Label>
          <div className="p-4 rounded-2xl bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 shadow-sm max-h-[200px] overflow-y-auto space-y-2 custom-scrollbar">
            {(() => {
              const masterBaseNames = new Set(bases.map(b => b.base || b.nome));
              const userBaseNames = Array.isArray(formData.base) ? formData.base : [];
              
              // Identifica bases legadas (não presentes na lista mestre)
              const legacyBases = userBaseNames
                .filter(name => name && !masterBaseNames.has(name))
                .map(name => ({ base: name, isLegacy: true }));
              
              const allDisplayBases = [...bases, ...legacyBases];

              return allDisplayBases.map((b, idx) => {
                const baseName = b.base || b.nome;
                const isSelected = userBaseNames.includes(baseName);
                const baseId = b.idbase || b.id || `base-${idx}-${baseName}`;
                
                return (
                  <div key={baseId} className="flex items-center gap-3 p-2 hover:bg-slate-50 dark:hover:bg-white/5 rounded-lg transition-colors cursor-pointer group select-none"
                       onClick={() => {
                         const newBases = isSelected
                           ? userBaseNames.filter(item => item !== baseName)
                           : [...userBaseNames, baseName];
                         handleInputChange('base', newBases);
                       }}
                  >
                    <div className={`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-all ${isSelected ? 'bg-[var(--gr-primary)] border-[var(--gr-primary)] scale-110' : 'border-slate-300 dark:border-white/20'}`}>
                      {isSelected && <Users size={12} className="text-white" />}
                    </div>
                    <div className="flex flex-col">
                      <span className={`text-sm font-semibold transition-colors ${isSelected ? 'text-[var(--gr-primary)]' : 'text-slate-600 dark:text-slate-300'}`}>
                        {baseName}
                      </span>
                      {b.isLegacy && (
                        <span className="text-[9px] text-orange-500 font-bold uppercase tracking-tighter leading-none">Registro Antigo (Remova se necessário)</span>
                      )}
                    </div>
                  </div>
                );
              });
            })()}
          </div>
          <p className="text-[10px] text-slate-400 italic ml-1">Selecione uma ou mais bases para este usuário.</p>
        </div>
      )}

      {/* 7. Responsável de Base (Pode ser dependente da escolha da base no futuro, mantendo simples por enquanto) */}
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Responsável de Base <span className="text-red-500">*</span></Label>
        <Select 
          value={formData.responsavel_base}
          onValueChange={(val) => handleInputChange('responsavel_base', val)}
          required
        >
          <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20">
            <SelectValue placeholder="Selecione o responsável..." />
          </SelectTrigger>
          <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 max-h-[200px]">
            {responsibles.map(r => (
              <SelectItem key={r.id || r.idresponsavel_base || r.responsavel} value={r.responsavel || r.nome}>
                {r.responsavel || r.nome}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 8. Modalidade - Comentado conforme solicitado por não ser usado aqui */}
      {/* 
      <div className="space-y-2">
        <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Modalidade <span className="text-red-500">*</span></Label>
        <Select 
          value={formData.modalidade}
          onValueChange={(val) => handleInputChange('modalidade', val)}
          required
        >
          <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm transition-all focus:ring-2 focus:ring-[var(--gr-primary)]/20">
            <SelectValue placeholder="Selecione a modalidade..." />
          </SelectTrigger>
          <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10">
            <SelectItem value="Agregado">Agregado</SelectItem>
            <SelectItem value="Rentals">Rentals</SelectItem>
            <SelectItem value="Frota Fixa Diarista">Frota Fixa Diarista</SelectItem>
            <SelectItem value="Frota Fixa Mensal">Frota Fixa Mensal</SelectItem>
          </SelectContent>
        </Select>
      </div>
      */}

    </form>
  );
};
