import React, { useState } from 'react';
import { api } from '../../../services/api';
import { Button } from '../../../components/ui/button';
import { Upload, X, AlertCircle, CheckCircle } from 'lucide-react';

interface ImportAgentsModalProps {
    onClose: () => void;
    onSuccess: () => void;
}

interface ImportResult {
    totalProcessed: number;
    successCount: number;
    failureCount: number;
    errors: string[];
}

export function ImportAgentsModal({ onClose, onSuccess }: ImportAgentsModalProps) {
    const [file, setFile] = useState<File | null>(null);
    const [uploading, setUploading] = useState(false);
    const [result, setResult] = useState<ImportResult | null>(null);
    const [error, setError] = useState<string | null>(null);

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            setFile(e.target.files[0]);
            setError(null);
            setResult(null);
        }
    };

    const handleUpload = async () => {
        if (!file) return;

        setUploading(true);
        setError(null);
        setResult(null);

        const formData = new FormData();
        formData.append('file', file);

        try {
            // api.post() retorna response.data diretamente, não o objeto response completo
            const result = await api.post<ImportResult>('/rh/agents/imports/excel', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            setResult(result);  // result já é o data, não precisa de result.data
            if (result.successCount > 0) {
                onSuccess(); // Refresh list if some succeeded
            }
        } catch (err: any) {
            console.error('Import error:', err);  // Log for debugging
            if (!err.response) {
                setError('Erro de Conexão: O servidor backend parece estar offline ou inacessível.');
            } else {
                setError(err.response?.data?.message || `Erro ao enviar arquivo (${err.response.status}).`);
            }
        } finally {
            setUploading(false);
        }
    };

    const handleDownloadTemplate = async () => {
        try {
            const blobData = await api.get<Blob>('/rh/agents/imports/template', {
                responseType: 'blob',
            });
            const url = window.URL.createObjectURL(new Blob([blobData]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'template_agentes.xlsx');
            document.body.appendChild(link);
            link.click();
            link.remove();
        } catch (err) {
            console.error(err);
            setError('Erro ao baixar modelo.');
        }
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
            <div className="bg-white dark:bg-slate-900 rounded-lg p-6 w-full max-w-2xl shadow-xl">
                <div className="flex justify-between items-center mb-4">
                    <h2 className="text-xl font-bold text-slate-800 dark:text-slate-100">
                        Importar Agentes (Excel)
                    </h2>
                    <button onClick={onClose} className="text-slate-500 hover:text-slate-700">
                        <X size={24} />
                    </button>
                </div>

                <div className="space-y-4">
                    {!result && (
                        <div className="border-2 border-dashed border-slate-300 dark:border-slate-700 p-8 text-center rounded-lg hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                            <input
                                type="file"
                                accept=".xlsx, .xls"
                                onChange={handleFileChange}
                                className="hidden"
                                id="file-upload"
                                disabled={uploading}
                            />
                            <label htmlFor="file-upload" className="cursor-pointer flex flex-col items-center">
                                <Upload size={48} className="text-blue-500 mb-2" />
                                <span className="text-lg font-medium text-slate-700 dark:text-slate-200">
                                    {file ? file.name : 'Clique para selecionar o arquivo Excel'}
                                </span>
                                <span className="text-sm text-slate-500 mt-1">
                                    Formatos aceitos: .xlsx, .xls
                                </span>
                            </label>
                            <div className="mt-4">
                                <Button variant="link" onClick={handleDownloadTemplate} className="text-blue-600">
                                    Baixar Modelo de Exemplo
                                </Button>
                            </div>
                        </div>
                    )}

                    {error && (
                        <div className="bg-red-50 text-red-700 p-4 rounded-md flex items-center gap-2">
                            <AlertCircle size={20} />
                            {error}
                        </div>
                    )}

                    {result && (
                        <div className="space-y-4">
                            <div className="grid grid-cols-3 gap-4 text-center">
                                <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                                    <div className="text-2xl font-bold text-blue-600">{result.totalProcessed}</div>
                                    <div className="text-sm text-blue-800 dark:text-blue-200">Processados</div>
                                </div>
                                <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                                    <div className="text-2xl font-bold text-green-600">{result.successCount}</div>
                                    <div className="text-sm text-green-800 dark:text-green-200">Sucessos</div>
                                </div>
                                <div className="bg-red-50 dark:bg-red-900/20 p-4 rounded-lg">
                                    <div className="text-2xl font-bold text-red-600">{result.failureCount}</div>
                                    <div className="text-sm text-red-800 dark:text-red-200">Falhas</div>
                                </div>
                            </div>

                            {result.errors.length > 0 && (
                                <div className="bg-slate-50 dark:bg-slate-800 p-4 rounded-lg max-h-60 overflow-y-auto">
                                    <h3 className="font-semibold mb-2 text-red-600 flex items-center gap-2">
                                        <AlertCircle size={16} /> Erros ({result.errors.length})
                                    </h3>
                                    <ul className="list-disc list-inside text-sm text-slate-600 dark:text-slate-300 space-y-1">
                                        {result.errors.map((err, idx) => (
                                            <li key={idx} className="break-all">{err}</li>
                                        ))}
                                    </ul>
                                </div>
                            )}

                            {result.failureCount === 0 && (
                                <div className="bg-green-50 text-green-700 p-4 rounded-md flex items-center gap-2">
                                    <CheckCircle size={20} />
                                    Importação concluída com sucesso!
                                </div>
                            )}
                        </div>
                    )}
                </div>

                <div className="mt-6 flex justify-end gap-3">
                    <Button variant="outline" onClick={onClose} disabled={uploading}>
                        Fechar
                    </Button>
                    {!result && (
                        <Button
                            onClick={handleUpload}
                            disabled={!file || uploading}
                            className="bg-blue-600 hover:bg-blue-700 text-white"
                        >
                            {uploading ? 'Importando...' : 'Importar'}
                        </Button>
                    )}
                    {result && (
                        <Button onClick={() => { setResult(null); setFile(null); }} variant="outline">
                            Nova Importação
                        </Button>
                    )}
                </div>
            </div>
        </div>
    );
}
