import React, { useState } from 'react';
import { User, CreditCard, Car, Calendar, Building2, X, FileText } from 'lucide-react';
import { cn } from '@/lib/utils';
import { GrKanbanCard } from './GrKanbanCard';
import { GrFormSidebar } from './GrFormSidebar';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

/**
 * Coluna de Cadastros Abertos
 * Mostra cards de cadastros sem contrato criado
 * Cada card abre um painel de detalhes com formulário de criar contrato
 */
export const CadastrosAbertosColumn = ({ 
  registrations = [], 
  onContractCreate,
  searchTerm = '',
  columnTitle = 'Cadastros Abertos',
  contractMode = 'agregado' // Nova prop para identificar o modo
}) => {
  const [selectedRegistration, setSelectedRegistration] = useState(null);
  const [isDetailsOpen, setIsDetailsOpen] = useState(false);
  const [formData, setFormData] = useState({
    iddrivers: '',
    tipo_contract: '',
    base_driver: '',
    status: 'Ativo',
    status_assinatura_form: contractMode === 'agregado' ? 'Não Assinado' : '',
    data_admissao: '',
    data_demissao: ''
  });

  // Filtrar por termo de busca
  const filteredRegistrations = registrations.filter(reg => {
    const searchLower = searchTerm.toLowerCase();
    return (
      (reg.nome_completo || '').toLowerCase().includes(searchLower) ||
      (reg.cpf || '').includes(searchTerm) ||
      (reg.coordenador || '').toLowerCase().includes(searchLower)
    );
  });

  const handleCardClick = (registration) => {
    setSelectedRegistration(registration);
    setFormData({
      iddrivers: registration.iddrivers || '',
      idcontrato_drivers: '',
      tipo_contract: registration.modalidade || '',
      base_driver: registration.base || '',
      status: 'Ativo',
      status_assinatura_form: contractMode === 'agregado' ? 'Não Assinado' : '',
      data_admissao: '',
      data_demissao: ''
    });
    setIsDetailsOpen(true);
  };

  const handleInputChange = (field, value) => {
    setFormData(prev => {
      const newData = { ...prev, [field]: value };
      // Limpeza de data de admissão se "Não Assinado"
      // COMENTADO POR SOLICITAÇÃO: Manter data de admissão fixa
      /*
      if (field === 'status_assinatura_form' && value === 'Não Assinado') {
        newData.data_admissao = '';
      }
      */
      return newData;
    });
  };

  const handleSaveContract = async (e) => {
    e.preventDefault();
    try {
      await onContractCreate({
        ...formData,
        iddrivers: selectedRegistration.iddrivers,
        // O ContractsView já lidará com o global_status baseado no contractMode e status_assinatura_form
      });
      setIsDetailsOpen(false);
      setSelectedRegistration(null);
    } catch (error) {
      throw error; // Re-throw para o componente pai tratar
    }
  };

  // Converter registrations para formato de cards
  const cards = filteredRegistrations.map(reg => ({
    id: reg.iddrivers,
    title: reg.nome_completo || `ID: ${reg.iddrivers}`,
    subtitle: reg.cpf || 'N/A',
    date: reg.data_cadastro || 'N/A',
    base: reg.base || 'N/A',
    details: [
      { label: 'Placa', value: reg.placa_veiculo || 'N/A' },
      { label: 'Modalidade', value: reg.modalidade || 'N/A' },
      { label: 'Tipo', value: reg.tipo_veiculo || 'N/A' }
    ],
    registration: reg // Manter referência ao objeto original
  }));

  return (
    <>
      <div className="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 border-slate-200/60 dark:border-white/5 h-full max-h-[calc(100vh-240px)] overflow-visible">
        {/* 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="w-2.5 h-2.5 rounded-full bg-purple-500 shadow-purple-500/20 shadow-[0_0_10px_rgba(0,0,0,0.1)]" />
            <h2 className="text-[12px] font-bold uppercase text-slate-800 dark:text-slate-200 tracking-[0.05em]">
              {columnTitle}
            </h2>
            <span className="ml-2 px-2.5 py-0.5 rounded-full bg-slate-200/50 dark:bg-white/10 text-[10px] font-bold text-slate-600 dark:text-slate-400">
              {cards.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">
            {cards.map((card) => (
              <div key={card.id} className="group relative">
                <div onClick={() => handleCardClick(card.registration)}>
                  <GrKanbanCard 
                    item={card}
                    title={card.title}
                    subtitle={card.subtitle}
                    date={card.date}
                    base={card.base}
                    details={card.details}
                    statusColor="purple"
                    dragDisabled={true}
                  />
                </div>
              </div>
            ))}
            
            {cards.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-bold uppercase tracking-widest text-slate-500">Sem Itens</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Details Panel with Contract Form */}
      <GrFormSidebar 
        isOpen={isDetailsOpen} 
        onClose={() => {
          setIsDetailsOpen(false);
          setSelectedRegistration(null);
        }}
        title="Cadastro - Criar Contrato"
        footer={
          <button 
            type="submit"
            form="contract-create-form"
            className="w-full py-4 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-2xl font-bold uppercase text-xs tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 active:scale-95"
          >
            Criar Contrato
          </button>
        }
      >
        {selectedRegistration && (
          <div className="space-y-8">
            {/* Registration Details Section */}
            <div className="space-y-4">
              <h3 className="text-[10px] font-bold uppercase tracking-widest text-[var(--gr-primary)] border-b border-slate-200 dark:border-white/10 pb-2">
                Informações do Cadastro
              </h3>
              
              <div className="flex flex-col gap-5 p-5 bg-slate-50 dark:bg-white/5 rounded-2xl border border-slate-200 dark:border-white/10">
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">Nome Completo</Label>
                  <p className="text-sm font-bold text-slate-700 dark:text-white">{selectedRegistration.nome_completo || 'N/A'}</p>
                </div>
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">CPF</Label>
                  <p className="text-sm font-medium text-slate-600 dark:text-slate-300">{selectedRegistration.cpf || 'N/A'}</p>
                </div>
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">Placa</Label>
                  <p className="text-sm font-medium text-slate-600 dark:text-slate-300 uppercase">{selectedRegistration.placa_veiculo || 'N/A'}</p>
                </div>
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">Modalidade</Label>
                  <p className="text-sm font-medium text-slate-600 dark:text-slate-300">{selectedRegistration.modalidade || 'N/A'}</p>
                </div>
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">Email</Label>
                  <p className="text-sm font-medium text-slate-600 dark:text-slate-300 break-all">{selectedRegistration.email || 'N/A'}</p>
                </div>
                <div className="space-y-1">
                  <Label className="text-[9px] font-bold text-slate-400 uppercase">Base</Label>
                  <p className="text-sm font-medium text-slate-600 dark:text-slate-300 leading-relaxed">{selectedRegistration.base || 'N/A'}</p>
                </div>
              </div>
            </div>

            {/* Contract Form Section */}
            <form id="contract-create-form" onSubmit={handleSaveContract} className="space-y-6">
              <h3 className="text-[10px] font-bold uppercase tracking-widest text-[var(--gr-primary)] border-b border-slate-200 dark:border-white/10 pb-2">
                Dados do Contrato
              </h3>

              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Tipo de Contrato</Label>
                <Input 
                  value={formData.tipo_contract}
                  onChange={(e) => handleInputChange('tipo_contract', e.target.value)}
                  placeholder="Ex: Frota Fixa Mensal, Frota Fixa Diarista, Agregado, Rentals" 
                  className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm" 
                  required
                />
              </div>

              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Base do Driver</Label>
                <Input 
                  value={formData.base_driver}
                  onChange={(e) => handleInputChange('base_driver', e.target.value)}
                  placeholder="Ex: SRJ03 - Volta Redonda" 
                  className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm" 
                />
              </div>

              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Status</Label>
                <Select 
                  value={formData.status}
                  onValueChange={(val) => handleInputChange('status', val)}
                >
                  <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm">
                    <SelectValue placeholder="-- Escolha uma opção --" />
                  </SelectTrigger>
                  <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10">
                    <SelectItem value="Ativo">Ativo</SelectItem>
                    <SelectItem value="Inativo">Inativo</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Novo campo: Status de Assinatura (Exclusivo para Agregados/Rentals) */}
              {contractMode === 'agregado' && (
                <div className="space-y-2">
                  <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Status de Assinatura</Label>
                  <Select 
                    value={formData.status_assinatura_form}
                    onValueChange={(val) => handleInputChange('status_assinatura_form', val)}
                  >
                      <SelectTrigger className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm">
                          <SelectValue placeholder="-- Escolha uma opção --" />
                      </SelectTrigger>
                      <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10">
                          <SelectItem value="Assinado">Assinado</SelectItem>
                          <SelectItem value="Não Assinado">Não Assinado</SelectItem>
                      </SelectContent>
                  </Select>
                </div>
              )}


              {/* Data de Admissão - Visível em Frota Fixa OU se status de assinatura for "Assinado" */}
              {(contractMode === 'frota-fixa' || formData.status_assinatura_form === 'Assinado') && (
              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Data de Admissão</Label>
                <Input 
                  type="date" 
                  value={formData.data_admissao}
                  onChange={(e) => handleInputChange('data_admissao', e.target.value)}
                  className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 px-4 shadow-sm" 
                  required
                />
              </div>
              )}
            </form>
          </div>
        )}
      </GrFormSidebar>
    </>
  );
};
