import React, { useState, useEffect, useRef } from 'react';
import { clsx } from 'clsx';
import {
    Users,
    Building2,
    Image as ImageIcon,
    LayoutDashboard,
    Globe,
    UploadCloud,
    X,
    Terminal
} from 'lucide-react';

import { useSystemSettings } from '../context/SystemSettingsContext';
import { useToast } from '../context/ToastContext';
import { systemSettingsService } from '../services/systemSettingsService';
import type { GlobalUser, GlobalOrganization } from '../services/systemSettingsService';

export const DeveloperDashboard: React.FC = () => {
    const [activeTab, setActiveTab] = useState<'overview' | 'organizations' | 'users' | 'branding'>('overview');
    const { settings, updateSettings, isLoading } = useSystemSettings();
    const { showToast } = useToast();

    const [appName, setAppName] = useState('');
    const [appSubtitle, setAppSubtitle] = useState('');
    const [logoUrl, setLogoUrl] = useState('');
    const [logoError, setLogoError] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [isUploading, setIsUploading] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const [globalUsers, setGlobalUsers] = useState<GlobalUser[]>([]);
    const [globalOrgs, setGlobalOrgs] = useState<GlobalOrganization[]>([]);
    const [isLoadingData, setIsLoadingData] = useState(false);

    // Fetch data when tab changes
    useEffect(() => {
        const fetchData = async () => {
            if (activeTab === 'users') {
                setIsLoadingData(true);
                try {
                    const data = await systemSettingsService.getGlobalUsers();
                    setGlobalUsers(data);
                } catch (error) {
                    console.error(error);
                    showToast('Erro ao carregar usuários.', 'error');
                } finally {
                    setIsLoadingData(false);
                }
            } else if (activeTab === 'organizations') {
                setIsLoadingData(true);
                try {
                    const data = await systemSettingsService.getGlobalOrganizations();
                    setGlobalOrgs(data);
                } catch (error) {
                    console.error(error);
                    showToast('Erro ao carregar organizações.', 'error');
                } finally {
                    setIsLoadingData(false);
                }
            }
        };

        fetchData();
    }, [activeTab, showToast]);

    // Load initial values
    useEffect(() => {
        if (settings) {
            setAppName(settings.appName);
            setAppSubtitle(settings.appSubtitle);
            setLogoUrl(settings.appLogoUrl || '');
            setLogoError(false);
        }
    }, [settings]);

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        // Validations
        if (file.size > 2 * 1024 * 1024) { // 2MB
            showToast('O logo deve ter no máximo 2MB.', 'error');
            return;
        }

        setIsUploading(true);
        try {
            console.log('Iniciando upload...');
            const uploadedUrl = await systemSettingsService.uploadLogo(file);
            console.log('Upload concluído. URL recebida:', uploadedUrl);

            if (uploadedUrl) {
                setLogoUrl(uploadedUrl);
                showToast('Logo carregado! URL: ' + uploadedUrl, 'success');
            } else {
                showToast('Erro: O servidor não retornou a URL da imagem.', 'error');
            }
        } catch (error) {
            console.error(error);
            showToast('Erro ao enviar o logo.', 'error');
        } finally {
            setIsUploading(false);
            if (fileInputRef.current) fileInputRef.current.value = '';
        }
    };

    const handleSaveBranding = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSaving(true);
        try {
            await updateSettings({
                appName,
                appSubtitle,
                appLogoUrl: logoUrl
            });
            showToast('Branding global atualizado com sucesso!', 'success');
        } catch (error) {
            showToast('Erro ao atualizar branding.', 'error');
            console.error(error);
        } finally {
            setIsSaving(false);
        }
    };

    if (isLoading) return <div className="p-8 text-center">Carregando configurações...</div>;

    return (
        <div className="p-8 animate-in fade-in duration-500">
            <div className="max-w-7xl mx-auto space-y-8">
                {/* Header */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <div className="flex items-center gap-2 text-indigo-500 font-bold mb-1">
                            <Terminal size={16} />
                            <span>Developer Access Only</span>
                        </div>
                        <h1 className="text-4xl font-black text-text-main tracking-tight">Dashboard do Desenvolvedor</h1>
                        <p className="text-text-muted mt-1">Gestão Global do Sistema TS-GPI</p>
                    </div>
                </div>

                {/* Tabs Navigation */}
                <div className="flex items-center gap-2 p-1 bg-surface-soft rounded-2xl border border-border/20 w-fit">
                    <button
                        onClick={() => setActiveTab('overview')}
                        className={clsx(
                            "flex items-center gap-2 px-4 py-2 text-sm font-bold rounded-xl transition-all",
                            activeTab === 'overview'
                                ? "bg-surface text-indigo-500 shadow-sm border border-border/40"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <LayoutDashboard size={16} />
                        Visão Geral
                    </button>
                    <button
                        onClick={() => setActiveTab('organizations')}
                        className={clsx(
                            "flex items-center gap-2 px-4 py-2 text-sm font-bold rounded-xl transition-all",
                            activeTab === 'organizations'
                                ? "bg-surface text-indigo-500 shadow-sm border border-border/40"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <Building2 size={16} />
                        Organizações
                    </button>
                    <button
                        onClick={() => setActiveTab('users')}
                        className={clsx(
                            "flex items-center gap-2 px-4 py-2 text-sm font-bold rounded-xl transition-all",
                            activeTab === 'users'
                                ? "bg-surface text-indigo-500 shadow-sm border border-border/40"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <Users size={16} />
                        Usuários Globais
                    </button>
                    <button
                        onClick={() => setActiveTab('branding')}
                        className={clsx(
                            "flex items-center gap-2 px-4 py-2 text-sm font-bold rounded-xl transition-all",
                            activeTab === 'branding'
                                ? "bg-surface text-indigo-500 shadow-sm border border-border/40"
                                : "text-text-muted hover:text-text-main hover:bg-surface-hover"
                        )}
                    >
                        <ImageIcon size={16} />
                        Branding Global
                    </button>
                </div>

                {/* Content Area */}
                <div className="bg-surface rounded-3xl border border-border/40 min-h-[500px] overflow-hidden">
                    {activeTab === 'overview' && (
                        <div className="p-12 flex flex-col items-center justify-center text-center h-full">
                            <div className="w-16 h-16 rounded-2xl bg-indigo-500/10 flex items-center justify-center mb-6 text-indigo-500 ring-1 ring-indigo-500/20">
                                <Globe size={32} />
                            </div>
                            <h2 className="text-2xl font-bold text-text-main">Sistema Operacional</h2>
                            <p className="text-text-muted mt-2 max-w-sm">
                                Você está no nível mais alto de privilégios. Todas as alterações feitas aqui impactam todas as instâncias do app.
                            </p>
                        </div>
                    )}

                    {activeTab === 'branding' && (
                        <div className="p-8 max-w-2xl">
                            <h2 className="text-2xl font-bold mb-6 flex items-center gap-3">
                                <ImageIcon className="text-indigo-500" />
                                Identidade Visual do APP
                            </h2>

                            <form onSubmit={handleSaveBranding} className="space-y-6">
                                <div>
                                    <label className="block text-sm font-medium text-text-secondary mb-2">
                                        Nome da Aplicação
                                    </label>
                                    <input
                                        type="text"
                                        value={appName}
                                        onChange={(e) => setAppName(e.target.value)}
                                        className="w-full px-4 py-2 rounded-xl bg-surface-soft border border-border/50 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none transition-all"
                                        placeholder="Ex: GPI"
                                    />
                                    <p className="text-xs text-text-muted mt-1">Aparecerá no topo do menu lateral.</p>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-text-secondary mb-2">
                                        Subtítulo
                                    </label>
                                    <input
                                        type="text"
                                        value={appSubtitle}
                                        onChange={(e) => setAppSubtitle(e.target.value)}
                                        className="w-full px-4 py-2 rounded-xl bg-surface-soft border border-border/50 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none transition-all"
                                        placeholder="Ex: Gestão de Pintura Industrial"
                                    />
                                    <p className="text-xs text-text-muted mt-1">Nome extenso abaixo da sigla.</p>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-text-secondary mb-2">
                                        Logo do App (Público)
                                    </label>
                                    <div className="flex flex-col gap-3">
                                        <div className="flex gap-2">
                                            <input
                                                type="text"
                                                value={logoUrl}
                                                onChange={(e) => setLogoUrl(e.target.value)}
                                                className="flex-1 px-4 py-2 rounded-xl bg-surface-soft border border-border/50 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none transition-all font-mono text-sm text-text-muted"
                                                placeholder="https://... ou /uploads/..."
                                                readOnly
                                            />
                                            {logoUrl && (
                                                <button
                                                    type="button"
                                                    onClick={() => setLogoUrl('')}
                                                    className="p-2 text-text-muted hover:text-error hover:bg-error/10 rounded-xl transition-colors"
                                                    title="Limpar logo"
                                                >
                                                    <X size={20} />
                                                </button>
                                            )}
                                        </div>

                                        <button
                                            type="button"
                                            onClick={() => fileInputRef.current?.click()}
                                            disabled={isUploading}
                                            className="flex items-center justify-center gap-2 w-full py-4 border-2 border-dashed border-border/60 rounded-xl hover:border-indigo-500 hover:bg-indigo-500/5 transition-all text-text-muted hover:text-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                        >
                                            {isUploading ? (
                                                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-current"></div>
                                            ) : (
                                                <>
                                                    <UploadCloud size={20} />
                                                    <span className="font-bold text-sm">Carregar arquivo local (Desktop)</span>
                                                </>
                                            )}
                                        </button>
                                        <input
                                            type="file"
                                            ref={fileInputRef}
                                            className="hidden"
                                            accept="image/*"
                                            onChange={handleFileChange}
                                            aria-label="Carregar logo do aplicativo"
                                        />
                                        <p className="text-xs text-text-muted">A imagem será armazenada no servidor e acessível publicamente.</p>
                                    </div>
                                </div>

                                {/* Preview */}
                                <div className="p-4 bg-surface-soft rounded-xl border border-border/30">
                                    <span className="text-xs font-bold text-text-muted uppercase tracking-wider mb-2 block">Preview</span>
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center shrink-0 overflow-hidden shadow-lg">
                                            {logoUrl && !logoError ? (
                                                <img src={logoUrl} alt="Preview" onError={() => setLogoError(true)} className="w-full h-full object-cover" />
                                            ) : (
                                                <span className="text-white font-black text-xl">{appName?.[0] || 'G'}</span>
                                            )}
                                        </div>
                                        <div>
                                            <h1 className="font-black text-xl tracking-tight text-text-main leading-none">
                                                {appName || 'Nome App'}
                                            </h1>
                                            <p className="text-[10px] font-bold text-indigo-500 uppercase tracking-wider mt-1">
                                                {appSubtitle || 'Subtítulo do App'}
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div className="pt-4">
                                    <button
                                        type="submit"
                                        disabled={isSaving}
                                        className={clsx(
                                            "px-6 py-3 rounded-xl font-bold text-white shadow-lg shadow-indigo-500/20 transition-all flex items-center gap-2",
                                            isSaving
                                                ? "bg-indigo-400 cursor-not-allowed"
                                                : "bg-indigo-600 hover:bg-indigo-500 hover:scale-[1.02]"
                                        )}
                                    >
                                        {isSaving ? 'Salvando...' : 'Salvar Alterações Globais'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    )}

                    {(activeTab === 'organizations') && (
                        <div className="p-8">
                            <h2 className="text-xl font-bold mb-6 flex items-center gap-2">
                                <Building2 className="text-indigo-500" />
                                Estrutura Organizacional
                            </h2>
                            <p className="text-text-muted mb-6">Visão hierárquica das organizações e seus membros.</p>

                            {isLoadingData ? (
                                <div className="text-center py-8 text-text-muted">Carregando organizações...</div>
                            ) : (
                                <div className="space-y-6">
                                    {globalOrgs.map((org) => {
                                        const membersList = org.members || [];
                                        const admins = membersList.filter(m => m.role === 'admin');
                                        const commonUsers = membersList.filter(m => m.role !== 'admin');

                                        return (
                                            <div key={org._id || org.id} className={clsx(
                                                "bg-surface-soft border rounded-xl overflow-hidden transition-all",
                                                org.isBanned
                                                    ? "border-red-500/50 shadow-[0_0_15px_rgba(239,68,68,0.1)]"
                                                    : "border-border/40 hover:border-indigo-500/30"
                                            )}>
                                                <div className="p-4 bg-surface border-b border-border/40 flex justify-between items-center">
                                                    <div>
                                                        <div className="flex items-center gap-2 mb-1">
                                                            <div className="text-xs font-bold text-text-muted uppercase tracking-wider">Organização</div>
                                                            {org.isBanned && (
                                                                <span className="px-2 py-0.5 bg-red-500/10 text-red-500 rounded text-[10px] font-bold border border-red-500/20 flex items-center gap-1">
                                                                    <X size={10} /> BLOQUEADA
                                                                </span>
                                                            )}
                                                            {!org.isBanned && (
                                                                <span className="px-2 py-0.5 bg-green-500/10 text-green-500 rounded text-[10px] font-bold border border-green-500/20">
                                                                    ATIVA
                                                                </span>
                                                            )}
                                                        </div>
                                                        <div className="font-bold text-text-main text-base mb-0.5">{org.name || 'Organização Sem Nome'}</div>
                                                        <div className="font-mono text-indigo-400/80 text-xs select-all" title="ID da Organização">{org._id || org.id}</div>
                                                    </div>
                                                    <div className="flex items-center gap-4">
                                                        <div className="text-right">
                                                            <div className="text-xs font-bold text-text-muted uppercase tracking-wider mb-1">Total de Membros</div>
                                                            <span className="bg-surface-hover px-2 py-1 rounded text-sm font-bold">{org.memberCount || membersList.length}</span>
                                                        </div>
                                                        <button
                                                            onClick={async () => {
                                                                const orgTargetId = org._id || org.id || '';
                                                                if (!orgTargetId) return;
                                                                if (confirm(org.isBanned ? 'Deseja desbloquear esta organização?' : 'Deseja BLOQUEAR esta organização? Os usuários perderão o acesso imediatamente.')) {
                                                                    try {
                                                                        await systemSettingsService.toggleOrganizationBan(orgTargetId, !org.isBanned);
                                                                        showToast(`Organização ${org.isBanned ? 'desbloqueada' : 'bloqueada'} com sucesso!`, 'success');
                                                                        const data = await systemSettingsService.getGlobalOrganizations();
                                                                        setGlobalOrgs(data);
                                                                    } catch (e) {
                                                                        console.error(e);
                                                                        showToast('Erro ao alterar status.', 'error');
                                                                    }
                                                                }
                                                            }}
                                                            className={clsx(
                                                                "p-2 rounded-lg transition-colors border",
                                                                org.isBanned
                                                                    ? "border-green-500/30 bg-green-500/10 text-green-500 hover:bg-green-500/20"
                                                                    : "border-red-500/30 bg-red-500/10 text-red-500 hover:bg-red-500/20"
                                                            )}
                                                            title={org.isBanned ? "Desbloquear Organização" : "Bloquear Organização"}
                                                        >
                                                            {org.isBanned ? (
                                                                <Users size={18} />
                                                            ) : (
                                                                <X size={18} />
                                                            )}
                                                        </button>
                                                    </div>
                                                </div>

                                                <div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-6 opacity-90">
                                                    {/* Admins Column */}
                                                    <div>
                                                        <h3 className="text-sm font-bold text-indigo-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                                                            <Users size={14} /> Administradores
                                                        </h3>
                                                        <div className="space-y-2">
                                                            {admins.map(admin => (
                                                                <div key={admin.userId || admin.email} className="flex items-center gap-3 p-2 bg-surface rounded-lg border border-indigo-500/20">
                                                                    <div className="w-8 h-8 rounded-full bg-indigo-500/20 flex items-center justify-center text-indigo-500 font-bold text-xs">
                                                                        {(admin.name || 'A').charAt(0).toUpperCase()}
                                                                    </div>
                                                                    <div className="overflow-hidden">
                                                                        <div className="font-bold text-sm truncate text-text-main">{admin.name || 'Administrador'}</div>
                                                                        <div className="text-[10px] text-text-muted truncate">{admin.email}</div>
                                                                    </div>
                                                                    {admin.isBanned && <span className="ml-auto text-error text-[10px] uppercase font-bold">Banido</span>}
                                                                </div>
                                                            ))}
                                                            {admins.length === 0 && <p className="text-sm text-text-muted italic">Sem administradores.</p>}
                                                        </div>
                                                    </div>

                                                    {/* Users Column */}
                                                    <div>
                                                        <h3 className="text-sm font-bold text-text-secondary uppercase tracking-wider mb-3 flex items-center gap-2">
                                                            <Users size={14} /> Usuários & Convidados
                                                        </h3>
                                                        <div className="space-y-2">
                                                            {commonUsers.map(user => (
                                                                <div key={user.userId || user.email} className="flex items-center gap-3 p-2 bg-surface rounded-lg border border-border/40">
                                                                    <div className={clsx(
                                                                        "w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs",
                                                                        user.role === 'user' ? "bg-green-500/10 text-green-500" : "bg-gray-500/10 text-gray-500"
                                                                    )}>
                                                                        {(user.name || 'U').charAt(0).toUpperCase()}
                                                                    </div>
                                                                    <div className="overflow-hidden">
                                                                        <div className="font-bold text-sm truncate text-text-main">{user.name || 'Usuário'}</div>
                                                                        <div className="text-[10px] text-text-muted truncate">{user.email}</div>
                                                                    </div>
                                                                    <span className={clsx(
                                                                        "ml-auto text-[10px] uppercase font-bold px-1.5 py-0.5 rounded",
                                                                        user.role === 'user' ? "bg-green-500/10 text-green-500" : "bg-gray-500/10 text-gray-500"
                                                                    )}>
                                                                        {user.role}
                                                                    </span>
                                                                    {user.isBanned && <span className="text-error text-[10px] uppercase font-bold ml-1">Banido</span>}
                                                                </div>
                                                            ))}
                                                            {commonUsers.length === 0 && <p className="text-sm text-text-muted italic">Sem outros membros.</p>}
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="px-4 py-2 bg-surface border-t border-border/40 text-[10px] text-text-muted text-right">
                                                    Última atividade: {org.lastActive ? new Date(org.lastActive).toLocaleDateString() + ' ' + new Date(org.lastActive).toLocaleTimeString() : 'N/A'}
                                                </div>
                                            </div>
                                        );
                                    })}
                                    {globalOrgs.length === 0 && (
                                        <div className="p-8 text-center text-text-muted bg-surface-soft rounded-xl border border-border/40">
                                            Nenhuma organização encontrada.
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    )}

                    {(activeTab === 'users') && (
                        <div className="p-8">
                            <h2 className="text-xl font-bold mb-6 flex items-center gap-2">
                                <Users className="text-indigo-500" />
                                Base Global de Usuários
                            </h2>

                            {isLoadingData ? (
                                <div className="text-center py-8 text-text-muted">Carregando usuários...</div>
                            ) : (
                                <div className="overflow-x-auto">
                                    <table className="w-full text-left border-collapse">
                                        <thead>
                                            <tr className="border-b border-border/40 text-xs text-text-muted uppercase tracking-wider">
                                                <th className="p-4">Nome / Email</th>
                                                <th className="p-4">Role Global</th>
                                                <th className="p-4">Status</th>
                                                <th className="p-4 text-right">Cadastrado em</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {globalUsers.map((user) => (
                                                <tr key={user._id} className="border-b border-border/20 hover:bg-surface-soft/50 transition-colors">
                                                    <td className="p-4">
                                                        <div className="font-bold text-text-main">{user.name}</div>
                                                        <div className="text-xs text-text-muted">{user.email}</div>
                                                    </td>
                                                    <td className="p-4">
                                                        <span className={clsx(
                                                            "px-2 py-1 rounded text-xs font-bold uppercase",
                                                            user.role === 'admin' ? "bg-indigo-500/10 text-indigo-500" :
                                                                user.role === 'user' ? "bg-green-500/10 text-green-500" :
                                                                    "bg-gray-500/10 text-gray-500"
                                                        )}>
                                                            {user.role}
                                                        </span>
                                                    </td>
                                                    <td className="p-4">
                                                        {user.isBanned ? (
                                                            <span className="text-error font-bold text-xs flex items-center gap-1">
                                                                <X size={12} /> Banido
                                                            </span>
                                                        ) : (
                                                            <span className="text-green-500 font-bold text-xs">Ativo</span>
                                                        )}
                                                    </td>
                                                    <td className="p-4 text-right text-text-muted text-sm">
                                                        {new Date(user.createdAt).toLocaleDateString()}
                                                    </td>
                                                </tr>
                                            ))}
                                            {globalUsers.length === 0 && (
                                                <tr>
                                                    <td colSpan={4} className="p-8 text-center text-text-muted">Nenhum usuário encontrado.</td>
                                                </tr>
                                            )}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>
                    )}

                </div>
            </div>
        </div>
    );
};
