'use client';

import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { AgencyBranding } from '@/components/layout/AgencyBranding';
import AuthGuard from '@/components/auth/AuthGuard';
import { useState, useEffect } from 'react';
import {
    HomeIcon,
    RocketLaunchIcon,
    ChartBarIcon,
    BriefcaseIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    FolderIcon,
    ShareIcon,
} from '@heroicons/react/24/outline';

const AGENCY_MENU_ITEMS = [
    { id: 'dashboard', label: 'Visão Geral', href: '/dashboard', icon: HomeIcon },
    {
        id: 'crm',
        label: 'CRM',
        href: '/crm',
        icon: RocketLaunchIcon,
        subItems: [
            { label: 'Dashboard', href: '/crm' },
            { label: 'Clientes', href: '/crm/clientes' },
            { label: 'Funis', href: '/crm/funis' },
            { label: 'Negociações', href: '/crm/negociacoes' },
        ]
    },
    {
        id: 'erp',
        label: 'ERP',
        href: '/erp',
        icon: ChartBarIcon,
        subItems: [
            { label: 'Dashboard', href: '/erp' },
            { label: 'Fluxo de Caixa', href: '/erp/fluxo-caixa' },
            { label: 'Contas a Pagar', href: '/erp/contas-pagar' },
            { label: 'Contas a Receber', href: '/erp/contas-receber' },
        ]
    },
    {
        id: 'projetos',
        label: 'Projetos',
        href: '/projetos',
        icon: BriefcaseIcon,
        subItems: [
            { label: 'Dashboard', href: '/projetos' },
            { label: 'Meus Projetos', href: '/projetos/lista' },
            { label: 'Tarefas', href: '/projetos/tarefas' },
            { label: 'Cronograma', href: '/projetos/cronograma' },
        ]
    },
    {
        id: 'helpdesk',
        label: 'Helpdesk',
        href: '/helpdesk',
        icon: LifebuoyIcon,
        subItems: [
            { label: 'Dashboard', href: '/helpdesk' },
            { label: 'Chamados', href: '/helpdesk/chamados' },
            { label: 'Base de Conhecimento', href: '/helpdesk/kb' },
        ]
    },
    {
        id: 'pagamentos',
        label: 'Pagamentos',
        href: '/pagamentos',
        icon: CreditCardIcon,
        subItems: [
            { label: 'Dashboard', href: '/pagamentos' },
            { label: 'Cobranças', href: '/pagamentos/cobrancas' },
            { label: 'Assinaturas', href: '/pagamentos/assinaturas' },
        ]
    },
    {
        id: 'contratos',
        label: 'Contratos',
        href: '/contratos',
        icon: DocumentTextIcon,
        subItems: [
            { label: 'Dashboard', href: '/contratos' },
            { label: 'Ativos', href: '/contratos/ativos' },
            { label: 'Modelos', href: '/contratos/modelos' },
        ]
    },
    {
        id: 'documentos',
        label: 'Documentos',
        href: '/documentos',
        icon: FolderIcon,
        subItems: [
            { label: 'Meus Arquivos', href: '/documentos' },
            { label: 'Compartilhados', href: '/documentos/compartilhados' },
            { label: 'Lixeira', href: '/documentos/lixeira' },
        ]
    },
    {
        id: 'social',
        label: 'Redes Sociais',
        href: '/social',
        icon: ShareIcon,
        subItems: [
            { label: 'Dashboard', href: '/social' },
            { label: 'Agendamento', href: '/social/agendamento' },
            { label: 'Relatórios', href: '/social/relatorios' },
        ]
    },
];

interface AgencyLayoutClientProps {
    children: React.ReactNode;
    colors?: {
        primary: string;
        secondary: string;
    } | null;
}

export function AgencyLayoutClient({ children, colors }: AgencyLayoutClientProps) {
    const [filteredMenuItems, setFilteredMenuItems] = useState(AGENCY_MENU_ITEMS);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchTenantSolutions = async () => {
            try {
                console.log('🔍 Buscando soluções do tenant...');
                const response = await fetch('/api/tenant/solutions', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    },
                });

                console.log('📡 Response status:', response.status);

                if (response.ok) {
                    const data = await response.json();
                    console.log('📦 Dados recebidos:', data);
                    const solutions = data.solutions || [];
                    console.log('✅ Soluções:', solutions);

                    // Mapear slugs de solutions para IDs de menu
                    const solutionSlugs = solutions.map((s: any) => s.slug.toLowerCase());
                    console.log('🏷️ Slugs das soluções:', solutionSlugs);

                    // Sempre mostrar dashboard + soluções disponíveis
                    const filtered = AGENCY_MENU_ITEMS.filter(item => {
                        if (item.id === 'dashboard') return true;
                        return solutionSlugs.includes(item.id);
                    });

                    console.log('📋 Menu filtrado:', filtered.map(i => i.id));
                    setFilteredMenuItems(filtered);
                } else {
                    console.error('❌ Erro na resposta:', response.status);
                    // Em caso de erro, mostrar todos (fallback)
                    setFilteredMenuItems(AGENCY_MENU_ITEMS);
                }
            } catch (error) {
                console.error('❌ Error fetching solutions:', error);
                // Em caso de erro, mostrar todos (fallback)
                setFilteredMenuItems(AGENCY_MENU_ITEMS);
            } finally {
                setLoading(false);
            }
        };

        fetchTenantSolutions();
    }, []);

    return (
        <AuthGuard>
            <AgencyBranding colors={colors} />
            <DashboardLayout menuItems={loading ? [AGENCY_MENU_ITEMS[0]] : filteredMenuItems}>
                {children}
            </DashboardLayout>
        </AuthGuard>
    );
}
