import React, { useState, useMemo } from 'react';
import { 
  Receipt, 
  Search,
  Loader2,
  Clock
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';

/**
 * Componente compartilhado para criação e agendamento de boletos
 * Reutilizado na BoletosView e no Header Global
 */
export const BoletoCreationDialog = ({ 
    open, 
    onOpenChange, 
    creationMode = 'AVULSO', 
    empresas = [],
    isCreating = false,
    onCreateBoleto
}) => {
    const [searchTermEmpresa, setSearchTermEmpresa] = useState('');
    const [showsEmpresaSuggestions, setShowsEmpresaSuggestions] = useState(false);
    const [formData, setFormData] = useState({
        Solicitante: '',
        idempresa: '',
        nome: '',
        email: '',
        cpf_cnpj: '',
        endereco: '',
        telefone: '',
        cidade: '',
        uf: '',
        cep: '',
        tipo_pessoa: 'JURIDICA',
        data_vencimento: '',
        dia_vencimento: '',
        bairro: '',
        valor_servico: '',
        // Campos para agendamento global
        data_execucao: '',
        data_envio: ''
    });

    const filteredEmpresasSuggestions = useMemo(() => {
        if (!searchTermEmpresa) return [];
        return empresas.filter(e => 
            (e.nome_exibicao || e.nome || '').toLowerCase().includes(searchTermEmpresa.toLowerCase()) ||
            (e.cpf_cnpj || '').includes(searchTermEmpresa)
        ).slice(0, 10);
    }, [empresas, searchTermEmpresa]);

    const handleSelectEmpresa = (empresa) => {
        const idEmpresa = empresa.idempresa || empresa.id_empresa || empresa.idempresa_financeiro || empresa.id || '';
        
        setFormData({
            ...formData,
            Solicitante: empresa.nome_exibicao || empresa.nome || '',
            idempresa: idEmpresa,
            nome: empresa.nome || '',
            email: empresa.email || '',
            cpf_cnpj: empresa.cpf_cnpj || '',
            endereco: empresa.endereco || '',
            telefone: empresa.telefone || '',
            cidade: empresa.cidade || '',
            uf: empresa.uf || '',
            cep: empresa.cep || '',
            tipo_pessoa: empresa.tipo_pessoa || 'JURIDICA',
            data_vencimento: empresa.data_vencimento || '',
            dia_vencimento: '',
            bairro: empresa.bairro || '',
            valor_servico: empresa.valor_servico || ''
        });
        setSearchTermEmpresa(empresa.nome_exibicao || empresa.nome || '');
        setShowsEmpresaSuggestions(false);
    };

    const handleConfirm = () => {
        onCreateBoleto(formData, creationMode);
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl max-h-[95vh] h-fit md:h-auto overflow-hidden bg-white dark:bg-[#0f172a] border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white p-0 shadow-2xl z-[9999]">
                <DialogHeader className="p-6 pb-2">
                    <DialogTitle className="text-slate-900 dark:text-white font-bold text-xl flex items-center gap-2">
                        <Receipt className="w-6 h-6 text-blue-500" />
                        Gerar {creationMode === 'AVULSO' ? 'Boleto Avulso' : creationMode === 'MENSAL' ? 'Boleto Mensal' : 'Agendamento'}
                    </DialogTitle>
                    <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">
                        Preencha os dados ou selecione um cliente registrado
                    </p>
                </DialogHeader>
                
                <ScrollArea className="max-h-[calc(95vh-140px)] px-6">
                    {creationMode === 'AGENDAMENTO' ? (
                        <div className="py-8 space-y-4">
                            <div className="bg-blue-500/10 border border-blue-500/20 rounded-xl p-4 mb-4">
                                <p className="text-sm text-blue-200 flex items-center gap-2">
                                    <Clock className="w-5 h-5 text-blue-400" />
                                    Defina a nova data de vencimento para o agendamento.
                                </p>
                            </div>
                            <div className="space-y-2 max-w-sm mx-auto">
                                <Label className="text-slate-400 text-xs font-bold uppercase tracking-widest">Nova Data de Vencimento</Label>
                                <Input
                                    type="date"
                                    value={formData.data_vencimento}
                                    onChange={(e) => setFormData({...formData, data_vencimento: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-12 text-lg text-center"
                                />
                            </div>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-6 gap-x-4 gap-y-3 py-4">
                            {/* Solicitante (Searchable) */}
                            <div className="space-y-1.5 relative col-span-1 md:col-span-6">
                                <Label className="text-blue-400 text-[10px] font-bold uppercase tracking-widest">Solicitante (Pesquisar cliente)</Label>
                                <div className="relative group">
                                    <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
                                    <Input
                                        placeholder="Digite o nome do cliente..."
                                        value={searchTermEmpresa}
                                        onChange={(e) => {
                                            setSearchTermEmpresa(e.target.value);
                                            setShowsEmpresaSuggestions(true);
                                        }}
                                        onFocus={() => setShowsEmpresaSuggestions(true)}
                                        className="bg-white dark:bg-slate-800/50 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white pl-10 focus:border-blue-500 transition-all h-10 text-sm"
                                    />
                                    {showsEmpresaSuggestions && filteredEmpresasSuggestions.length > 0 && (
                                        <Card className="absolute z-[10000] w-full mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 shadow-2xl overflow-hidden animate-in fade-in slide-in-from-top-1">
                                            <ScrollArea className="h-48">
                                                {filteredEmpresasSuggestions.map((empresa, idx) => (
                                                    <div 
                                                        key={idx}
                                                        className="p-3 hover:bg-slate-50 dark:hover:bg-slate-700 cursor-pointer border-b border-slate-100 dark:border-slate-700/50 last:border-0 transition-colors"
                                                        onClick={() => handleSelectEmpresa(empresa)}
                                                    >
                                                        <p className="text-sm font-bold text-slate-900 dark:text-white">{empresa.nome_exibicao || empresa.nome}</p>
                                                        <p className="text-[10px] text-slate-400 uppercase font-medium">
                                                            {empresa.cpf_cnpj} • {empresa.email}
                                                        </p>
                                                    </div>
                                                ))}
                                            </ScrollArea>
                                        </Card>
                                    )}
                                </div>
                            </div>

                            {/* Campos de Nome e Email */}
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Nome Completo</Label>
                                <Input
                                    value={formData.nome}
                                    onChange={(e) => setFormData({...formData, nome: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">E-mail</Label>
                                <Input
                                    type="email"
                                    value={formData.email}
                                    onChange={(e) => setFormData({...formData, email: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>

                            {/* Documento e Telefone */}
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">CPF / CNPJ</Label>
                                <Input
                                    value={formData.cpf_cnpj}
                                    onChange={(e) => setFormData({...formData, cpf_cnpj: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Telefone</Label>
                                <Input
                                    value={formData.telefone}
                                    onChange={(e) => setFormData({...formData, telefone: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>

                            {/* Endereço e CEP */}
                            <div className="space-y-1 col-span-1 md:col-span-4">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Endereço</Label>
                                <Input
                                    value={formData.endereco}
                                    onChange={(e) => setFormData({...formData, endereco: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-2">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">CEP</Label>
                                <Input
                                    value={formData.cep}
                                    onChange={(e) => setFormData({...formData, cep: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            
                            <div className="space-y-1 col-span-1 md:col-span-2">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Bairro</Label>
                                <Input
                                    value={formData.bairro}
                                    onChange={(e) => setFormData({...formData, bairro: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Cidade</Label>
                                <Input
                                    value={formData.cidade}
                                    onChange={(e) => setFormData({...formData, city: e.target.value})}
                                    className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm"
                                />
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-1">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">UF</Label>
                                <Input
                                    value={formData.uf}
                                    maxLength={2}
                                    onChange={(e) => setFormData({...formData, uf: e.target.value.toUpperCase()})}
                                    className="bg-slate-800/30 border-slate-700 text-white h-9 text-sm"
                                />
                            </div>

                            {/* Tipo Pessoa e Vencimento */}
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                <Label className="text-slate-400 text-[10px] font-bold uppercase">Tipo de Pessoa</Label>
                                <Select 
                                    value={formData.tipo_pessoa} 
                                    onValueChange={(val) => setFormData({...formData, tipo_pessoa: val})}
                                >
                                    <SelectTrigger className="bg-slate-100 dark:bg-slate-800/30 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white h-9 text-sm">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent className="bg-white dark:bg-[#1e293b] border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white">
                                        <SelectItem value="JURIDICA">Pessoa Jurídica</SelectItem>
                                        <SelectItem value="FISICA">Pessoa Física</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="space-y-1 col-span-1 md:col-span-3">
                                {creationMode === 'MENSAL' ? (
                                    <>
                                        <Label className="text-slate-400 text-[10px] font-bold uppercase">Dia do Vencimento (1-31)</Label>
                                        <Input
                                            type="number"
                                            min="1"
                                            max="31"
                                            placeholder="Ex: 10"
                                            value={formData.dia_vencimento}
                                            onChange={(e) => setFormData({...formData, dia_vencimento: parseInt(e.target.value) || ''})}
                                            className="bg-slate-800/30 border-slate-700 text-white h-9 text-sm"
                                        />
                                    </>
                                ) : (
                                    <>
                                        <Label className="text-slate-400 text-[10px] font-bold uppercase">Data de Vencimento</Label>
                                        <Input
                                            type="date"
                                            value={formData.data_vencimento}
                                            onChange={(e) => setFormData({...formData, data_vencimento: e.target.value})}
                                            className="bg-slate-800/30 border-slate-700 text-white h-9 text-sm"
                                        />
                                    </>
                                )}
                            </div>

                            {/* Valor */}
                            <div className="space-y-1 col-span-1 md:col-span-6 pt-2">
                                <Label className="text-blue-400 text-[10px] font-bold uppercase tracking-widest">Valor da Cobrança (R$)</Label>
                                <div className="relative">
                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-blue-500 font-bold text-lg">R$</span>
                                    <Input
                                        type="number"
                                        step="0.01"
                                        placeholder="0,00"
                                        value={formData.valor_servico}
                                        onChange={(e) => setFormData({...formData, valor_servico: e.target.value})}
                                        className="bg-blue-50 dark:bg-blue-500/10 border-blue-200 dark:border-blue-500/30 text-blue-700 dark:text-white text-2xl font-bold h-14 pl-12 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/20"
                                    />
                                </div>
                            </div>
                        </div>
                    )}
                </ScrollArea>

                <DialogFooter className="p-6 pt-2 bg-slate-50 dark:bg-slate-900/50 border-t border-slate-100 dark:border-slate-800 gap-3">
                    <Button 
                        variant="ghost" 
                        onClick={() => onOpenChange(false)}
                        className="text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800 h-10"
                    >
                        Cancelar
                    </Button>
                    <Button 
                        onClick={handleConfirm}
                        disabled={isCreating}
                        className="bg-blue-600 hover:bg-blue-700 text-white font-bold px-8 h-12 shadow-lg shadow-blue-500/20 flex-1 md:flex-none"
                    >
                        {isCreating ? (
                            <>
                                <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                                {creationMode === 'AGENDAMENTO' ? 'Agendando...' : 'Gerando Cobrança...'}
                            </>
                        ) : (
                            <>
                                <Receipt className="w-5 h-5 mr-2" />
                                {creationMode === 'AGENDAMENTO' ? 'Agendar Agora' : 'Gerar Cobrança Agora'}
                            </>
                        )}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};
