"use client";


import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { LayoutDashboard, Edit3, ShoppingBag, CreditCard, LogOut, Eye, MessageSquare, User as UserIcon, Rocket } from 'lucide-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { User } from '../../types';
import { MOCK_BUSINESSES } from '../../lib/mockData';
import DashboardOverview from '../../components/dashboard/DashboardOverview';
import DashboardProfile from '../../components/dashboard/DashboardProfile';
import DashboardProfileClient from '../../components/dashboard/DashboardProfileClient';
import DashboardMessages from '../../components/dashboard/DashboardMessages';
import DashboardOffers from '../../components/dashboard/DashboardOffers';
import PricingSection from '../../components/PricingSection';
import { useUser } from '../../components/UserProvider';

const DashboardPage = () => {
    const { user, logout } = useUser();
    const router = useRouter();
    const searchParams = useSearchParams();
    const chatId = searchParams.get('chatId') || searchParams.get('chat');
    
    const [currentView, setCurrentView] = useState<'overview' | 'profile' | 'offers' | 'subscription' | 'messages' | 'personal-profile'>('overview');
    const [business, setBusiness] = useState<any>(null);
    const [stats, setStats] = useState<{ totalViews: number, contactClicks: number } | null>(null);
    const [loading, setLoading] = useState(true);
    const [isMounted, setIsMounted] = useState(false);
    const [unreadCount, setUnreadCount] = useState(0);

    useEffect(() => {
        setIsMounted(true);
        
        // Handle view from URL
        const viewParam = searchParams.get('view');
        if (viewParam && ['overview', 'profile', 'offers', 'subscription', 'messages', 'personal-profile'].includes(viewParam)) {
            setCurrentView(viewParam as any);
        }
    }, [searchParams]);

    // Fetch user's business
    useEffect(() => {
        if (!user || !isMounted) return;

        const fetchBusiness = async () => {
            try {
                const res = await fetch('/api/businesses/me', {
                    headers: { 'x-user-id': user.id }
                });
                const data = await res.json();
                if (data && !data.error) {
                    setBusiness(data);
                    
                    // Fetch stats for this business
                    try {
                        const statsRes = await fetch(`/api/analytics/businesses/${data.id}`);
                        const statsData = await statsRes.json();
                        if (!statsData.error) {
                            setStats(statsData);
                        }
                    } catch (e) {
                        console.error('Error fetching stats:', e);
                    }
                }
            } catch (error) {
                console.error('Error fetching dashboard business:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchBusiness();
    }, [user, isMounted]);

    // Fetch unread messages count
    const fetchUnreadCount = async () => {
        if (!user || !isMounted) return;
        
        // If user has no id, try to find it via email (Session Reconciliation)
        let effectiveUserId = user.id;
        if (!effectiveUserId || effectiveUserId === 'undefined' || effectiveUserId === 'null') {
            try {
                const res = await fetch(`/api/users/profile?email=${encodeURIComponent(user.email)}`);
                const data = await res.json();
                if (data.id) {
                    effectiveUserId = data.id;
                    // Note: Ideally we'd update the global user object here too
                } else {
                    return; // Can't count without ID
                }
            } catch (e) { return; }
        }

        try {
            const res = await fetch('/api/messages/unread', {
                headers: { 'x-user-id': effectiveUserId }
            });
            const data = await res.json();
            if (!data.error) {
                setUnreadCount(data.count);
            }
        } catch (error) {
            console.error('Error fetching unread count:', error);
        }
    };

    useEffect(() => {
        fetchUnreadCount();
        const interval = setInterval(fetchUnreadCount, 15000); // Polling every 15s
        return () => clearInterval(interval);
    }, [user, isMounted]);

    // Update document title with unread count
    useEffect(() => {
        if (unreadCount > 0) {
            document.title = `(${unreadCount}) Messages - Afropreunariat`;
        } else {
            document.title = 'Tableau de Bord - Afropreunariat';
        }
    }, [unreadCount]);

    useEffect(() => {
        if (!user && isMounted) {
            router.push('/login');
        }
    }, [user, isMounted, router]);

    if (!isMounted || (loading && user)) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50">
                <div className="flex flex-col items-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-600"></div>
                    <p className="mt-4 text-gray-600 font-medium">Chargement de votre espace...</p>
                </div>
            </div>
        );
    }

    if (!user) {
        return null;
    }

    // Default business structure for new users
    const displayBusiness = business || {
        id: 'new',
        name: "Ma Boutique",
        category: "Technologie & IT",
        location: "Ma Ville",
        description: "Décrivez votre entreprise ici...",
        logoUrl: "https://picsum.photos/200/200?random=default",
        contactEmail: user?.email || "",
        contactPhone: "",
        slug: "",
        tags: [],
        socialLinks: {},
        verified: false,
        viewCount: 0,
        rating: 0,
        offers: []
    };

    return (
        <div className="min-h-screen bg-gray-100 flex">
            {/* 1. Sidebar */}
            <div className="hidden md:flex md:flex-col md:w-64 md:fixed md:inset-y-0 bg-white border-r border-gray-200">
                <div className="flex items-center h-16 flex-shrink-0 px-4 border-b border-gray-200">
                    <Link href="/" className="flex items-center gap-2">
                        <div className="w-8 h-8 bg-brand-600 rounded-lg flex items-center justify-center text-white font-bold font-serif">A</div>
                        <span className="font-serif font-bold text-lg text-gray-900">Afropreunariat</span>
                    </Link>
                </div>
                <div className="flex-1 flex flex-col overflow-y-auto pt-5 pb-4">
                    <div className="px-4 mb-6">
                        <div className="flex items-center relative group">
                            <div className="h-12 w-12 rounded-full bg-gradient-to-br from-brand-400 to-brand-600 flex items-center justify-center text-white font-bold shrink-0 relative shadow-lg shadow-brand-200 border-2 border-white">
                                {user.name.charAt(0)}
                                {unreadCount > 0 && (
                                    <>
                                        <span className="absolute -top-1.5 -right-1.5 block h-4 w-4 rounded-full bg-red-600 border-2 border-white animate-bounce"></span>
                                        <span className="absolute -top-1.5 -right-1.5 block h-4 w-4 rounded-full bg-red-400 animate-ping opacity-75"></span>
                                    </>
                                )}
                            </div>
                            <div className="ml-3">
                                <p className="text-sm font-bold text-gray-900 truncate">{user.name}</p>
                                <div className="flex items-center mt-0.5">
                                    <span className="h-2 w-2 rounded-full bg-green-500 mr-1.5 shadow-[0_0_8px_rgba(34,197,94,0.6)]"></span>
                                    <span className="text-[10px] font-bold text-green-600 uppercase tracking-tighter">En ligne</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <nav className="mt-2 flex-1 px-2 space-y-1">
                        <button onClick={() => setCurrentView('overview')} className={`${currentView === 'overview' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full`}>
                            <LayoutDashboard className={`${currentView === 'overview' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                            Tableau de Bord
                        </button>

                        <button onClick={() => setCurrentView('messages')} className={`${currentView === 'messages' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full relative`}>
                            <MessageSquare className={`${currentView === 'messages' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                            Messages
                            {unreadCount > 0 && (
                                <span className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1.5">
                                    <span className="flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white shadow-lg shadow-red-200">
                                        {unreadCount}
                                    </span>
                                    <span className="flex h-2 w-2 rounded-full bg-red-500 animate-pulse"></span>
                                </span>
                            )}
                        </button>

                        <button onClick={() => setCurrentView('personal-profile')} className={`${currentView === 'personal-profile' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full`}>
                            <UserIcon className={`${currentView === 'personal-profile' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                            Mon Profil Client
                        </button>

                        <div className="pt-4 pb-2">
                             <p className="px-3 text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Espace Business</p>
                        </div>

                        {user.role === 'ENTREPRENEUR' ? (
                            <>
                                <button onClick={() => setCurrentView('profile')} className={`${currentView === 'profile' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full`}>
                                    <Edit3 className={`${currentView === 'profile' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                                    Ma Fiche Entreprise
                                </button>
                                <button onClick={() => setCurrentView('offers')} className={`${currentView === 'offers' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full`}>
                                    <ShoppingBag className={`${currentView === 'offers' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                                    Mes Offres
                                </button>
                                <button onClick={() => setCurrentView('subscription')} className={`${currentView === 'subscription' ? 'bg-brand-50 text-brand-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'} group flex items-center px-2 py-2 text-sm font-medium rounded-md w-full`}>
                                    <CreditCard className={`${currentView === 'subscription' ? 'text-brand-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-5 w-5`} />
                                    Abonnement
                                </button>
                            </>
                        ) : (
                            <button 
                                onClick={() => setCurrentView('profile')} 
                                className="mt-2 group flex items-center px-2 py-3 text-sm font-bold rounded-md w-full bg-brand-600 text-white hover:bg-brand-700 transition-all shadow-md group border-2 border-brand-400"
                            >
                                <Rocket className="mr-3 flex-shrink-0 h-5 w-5 text-brand-200" />
                                Propulser mon Business
                            </button>
                        )}
                    </nav>
                </div>
                <div className="flex-shrink-0 flex border-t border-gray-200 p-4">
                    <button onClick={() => { logout(); router.push('/'); }} className="flex-shrink-0 w-full group block text-gray-600 hover:text-red-600 transition-colors">
                        <div className="flex items-center">
                            <LogOut className="inline-block h-5 w-5 mr-2" />
                            <span className="text-sm font-medium">Déconnexion</span>
                        </div>
                    </button>
                </div>
            </div>

            {/* 2. Main Content */}
            <div className="flex-1 flex flex-col md:pl-64 overflow-hidden">
                <header className="bg-white shadow-sm z-10 flex justify-between items-center px-6 py-4 sticky top-0">
                    <h1 className="text-2xl font-bold text-gray-900 sm:truncate">
                        {currentView === 'overview' && 'Vue d\'ensemble'}
                        {currentView === 'messages' && 'Mes Messages'}
                        {currentView === 'personal-profile' && 'Mon Profil Client'}
                        {currentView === 'profile' && (user.role === 'ENTREPRENEUR' ? 'Ma Fiche Entreprise' : 'Créer mon Business')}
                        {currentView === 'offers' && 'Gestion des Offres'}
                        {currentView === 'subscription' && 'Mon Abonnement'}
                    </h1>
                    <div className="flex items-center space-x-4">
                        <a href={displayBusiness.id === 'new' ? '/annuaire' : `/annuaire/${displayBusiness.slug || displayBusiness.id}`} target="_blank" rel="noopener noreferrer" className="hidden sm:inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none">
                            <Eye className="-ml-1 mr-2 h-4 w-4 text-gray-500" />
                            Voir ma fiche
                        </a>
                    </div>
                </header>

                <main className="flex-1 overflow-y-auto p-6">
                    <div className="max-w-7xl mx-auto space-y-6">
                        {business?.isSuspended && (
                            <div className="bg-orange-50 border-l-4 border-orange-500 p-4 rounded-r-lg shadow-sm animate-in fade-in slide-in-from-top duration-500">
                                <div className="flex">
                                    <div className="flex-shrink-0">
                                        <ShieldAlert className="h-5 w-5 text-orange-500" aria-hidden="true" />
                                    </div>
                                    <div className="ml-3">
                                        <p className="text-sm text-orange-700 font-bold uppercase tracking-tight">Boutique Suspendue</p>
                                        <p className="text-sm text-orange-600 mt-1 italic">
                                            "{business.suspensionReason || "Votre boutique a été temporairement masquée suite à une décision de la modération."}"
                                        </p>
                                        <p className="text-xs text-orange-500 mt-2 font-medium">
                                            Veuillez contacter l'administration pour plus d'informations.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        )}
                        {currentView === 'overview' && <DashboardOverview business={displayBusiness} stats={stats} />}
                        {currentView === 'messages' && <DashboardMessages onMessagesRead={fetchUnreadCount} initialConversationId={chatId} />}
                        {currentView === 'personal-profile' && <DashboardProfileClient />}
                        {currentView === 'profile' && <DashboardProfile business={displayBusiness} setBusiness={setBusiness} />}
                        {currentView === 'offers' && <DashboardOffers />}
                        {currentView === 'subscription' && (
                            <div className="space-y-6">
                                <div className="bg-white shadow rounded-lg p-6 flex justify-between items-center">
                                    <div>
                                        <h3 className="text-lg font-medium text-gray-900">Abonnement Actuel : <span className="text-brand-600 font-bold">Starter (Gratuit)</span></h3>
                                        <p className="text-sm text-gray-500">Passez au niveau supérieur pour débloquer plus de fonctionnalités.</p>
                                    </div>
                                    <span className="inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium bg-green-100 text-green-800">
                                        Actif
                                    </span>
                                </div>
                                <PricingSection />
                            </div>
                        )}
                    </div>
                </main>
            </div>
        </div>
    );
}

export default DashboardPage;
