"use client";


import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { LayoutDashboard, Edit3, ShoppingBag, CreditCard, LogOut, Eye } from 'lucide-react';
import { useRouter } 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 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 [currentView, setCurrentView] = useState<'overview' | 'profile' | 'offers' | 'subscription'>('overview');
    const [business, setBusiness] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [isMounted, setIsMounted] = useState(false);

    useEffect(() => {
        setIsMounted(true);
    }, []);

    // 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);
                }
            } catch (error) {
                console.error('Error fetching dashboard business:', error);
            } finally {
                setLoading(false);
            }
        };

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

    if (!isMounted) return null;

    if (!user) {
        if (typeof window !== 'undefined') router.push('/login');
        return null;
    }

    if (loading) {
        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>
        );
    }

    // 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: "",
        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">
                            <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 font-bold shrink-0">
                                {user.name.charAt(0)}
                            </div>
                            <div className="ml-3">
                                <p className="text-sm font-medium text-gray-700 truncate">{user.name}</p>
                                <div className="flex items-center mt-1">
                                    <span className="h-2 w-2 rounded-full bg-green-400 mr-1"></span>
                                    <span className="text-xs text-gray-500">Actif</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('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`} />
                            Éditer mon profil
                        </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>
                    </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 === 'profile' && 'Mon Profil'}
                        {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">
                        {currentView === 'overview' && <DashboardOverview business={displayBusiness} />}
                        {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;
