'use client';

import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { AgencyBranding } from '@/components/layout/AgencyBranding';
import AuthGuard from '@/components/auth/AuthGuard';
import { CRMFilterProvider } from '@/contexts/CRMFilterContext';
import { useState, useEffect } from 'react';
import {
    HomeIcon,
    RocketLaunchIcon,
    UserPlusIcon,
    RectangleStackIcon,
    UsersIcon,
    MegaphoneIcon,
} from '@heroicons/react/24/outline';

const AGENCY_MENU_ITEMS = [
    { id: 'dashboard', label: 'Dashboard', href: '/dashboard', icon: HomeIcon },
    {
        id: 'crm',
        label: 'CRM',
        href: '/crm',
        icon: RocketLaunchIcon,
        requiredSolution: 'crm',
        subItems: [
            { label: 'Visão Geral', href: '/crm', icon: HomeIcon },
            { label: 'Funis de Vendas', href: '/crm/funis', icon: RectangleStackIcon },
            { label: 'Clientes', href: '/crm/clientes', icon: UsersIcon },
            { label: 'Campanhas', href: '/crm/campanhas', icon: MegaphoneIcon },
            { label: 'Leads', href: '/crm/leads', icon: UserPlusIcon },
        ]
    },
];

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;
                        const requiredSolution = (item as any).requiredSolution;
                        return solutionSlugs.includes((requiredSolution || item.id).toLowerCase());
                    });

                    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 allowedTypes={['agency_user']}>
            <CRMFilterProvider>
                <AgencyBranding colors={colors} />
                <DashboardLayout menuItems={loading ? [AGENCY_MENU_ITEMS[0]] : filteredMenuItems}>
                    {children}
                </DashboardLayout>
            </CRMFilterProvider>
        </AuthGuard>
    );
}
