'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Sidebar } from 'primereact/sidebar';
import { Button } from 'primereact/button';
import { Menubar } from 'primereact/menubar';
import { Menu } from 'primereact/menu';
import { Avatar } from 'primereact/avatar';
import { Badge } from 'primereact/badge';
import { Ripple } from 'primereact/ripple';
import { StyleClass } from 'primereact/styleclass';
import { useRouter } from 'next/navigation';
import { useDevAuth } from '../auth/DevAuthProvider';
import Link from 'next/link';

interface AppLayoutProps {
  children: React.ReactNode;
}

export const AppLayout: React.FC<AppLayoutProps> = ({ children }) => {
  const [sidebarVisible, setSidebarVisible] = useState(false);
  const [profileMenuVisible, setProfileMenuVisible] = useState(false);
  const { user, logout, isAuthenticated } = useDevAuth();
  const router = useRouter();
  const profileMenuRef = useRef<Menu>(null);

  // Menu items pour la sidebar
  const sidebarItems = [
    {
      label: 'Tableau de Bord',
      icon: 'pi pi-home',
      command: () => router.push('/dashboard')
    },
    {
      label: 'Chantiers',
      icon: 'pi pi-building',
      items: [
        { label: 'Tous les chantiers', icon: 'pi pi-list', command: () => router.push('/chantiers') },
        { label: 'Nouveau chantier', icon: 'pi pi-plus', command: () => router.push('/chantiers/nouveau') },
        { label: 'Planning', icon: 'pi pi-calendar', command: () => router.push('/chantiers/planning') }
      ]
    },
    {
      label: 'Clients',
      icon: 'pi pi-users',
      items: [
        { label: 'Tous les clients', icon: 'pi pi-list', command: () => router.push('/clients') },
        { label: 'Nouveau client', icon: 'pi pi-plus', command: () => router.push('/clients/nouveau') }
      ]
    },
    {
      label: 'Devis & Factures',
      icon: 'pi pi-file-edit',
      items: [
        { label: 'Devis', icon: 'pi pi-file', command: () => router.push('/devis') },
        { label: 'Factures', icon: 'pi pi-receipt', command: () => router.push('/factures') },
        { label: 'Nouveau devis', icon: 'pi pi-plus', command: () => router.push('/devis/nouveau') }
      ]
    },
    {
      label: 'Matériel',
      icon: 'pi pi-cog',
      items: [
        { label: 'Inventaire', icon: 'pi pi-list', command: () => router.push('/materiel') },
        { label: 'Maintenance', icon: 'pi pi-wrench', command: () => router.push('/materiel/maintenance') },
        { label: 'Réservations', icon: 'pi pi-calendar-plus', command: () => router.push('/materiel/reservations') }
      ]
    },
    {
      label: 'Équipes',
      icon: 'pi pi-users',
      items: [
        { label: 'Employés', icon: 'pi pi-user', command: () => router.push('/employes') },
        { label: 'Équipes', icon: 'pi pi-users', command: () => router.push('/equipes') },
        { label: 'Planning', icon: 'pi pi-calendar', command: () => router.push('/employes/planning') }
      ]
    },
    {
      label: 'Fournisseurs',
      icon: 'pi pi-truck',
      items: [
        { label: 'Tous les fournisseurs', icon: 'pi pi-list', command: () => router.push('/fournisseurs') },
        { label: 'Nouveau fournisseur', icon: 'pi pi-plus', command: () => router.push('/fournisseurs/nouveau') }
      ]
    },
    {
      label: 'Rapports',
      icon: 'pi pi-chart-bar',
      items: [
        { label: 'Statistiques', icon: 'pi pi-chart-line', command: () => router.push('/rapports/statistiques') },
        { label: 'Finances', icon: 'pi pi-euro', command: () => router.push('/rapports/finances') },
        { label: 'Performance', icon: 'pi pi-chart-pie', command: () => router.push('/rapports/performance') }
      ]
    }
  ];

  // Menu items pour le profil
  const profileItems = [
    {
      label: 'Mon Profil',
      icon: 'pi pi-user',
      command: () => router.push('/profil')
    },
    {
      label: 'Paramètres',
      icon: 'pi pi-cog',
      command: () => router.push('/parametres')
    },
    {
      separator: true
    },
    {
      label: 'Déconnexion',
      icon: 'pi pi-sign-out',
      command: () => {
        logout();
        window.location.href = '/api/auth/login';
      }
    }
  ];

  // Menu items pour la barre de navigation
  const navItems = [
    {
      label: 'Accueil',
      icon: 'pi pi-home',
      command: () => router.push('/dashboard')
    },
    {
      label: 'Chantiers',
      icon: 'pi pi-building',
      command: () => router.push('/chantiers')
    },
    {
      label: 'Clients',
      icon: 'pi pi-users',
      command: () => router.push('/clients')
    },
    {
      label: 'Matériel',
      icon: 'pi pi-cog',
      command: () => router.push('/materiel')
    }
  ];

  const start = (
    <div className="flex align-items-center">
      <Button
        icon="pi pi-bars"
        className="p-button-text p-button-rounded p-button-plain mr-2"
        onClick={() => setSidebarVisible(true)}
      />
      <Link href="/dashboard" className="flex align-items-center text-decoration-none">
        <img src="/layout/images/logo/logo-dark.png" alt="BTP Xpress" height="40" className="mr-2" />
        <span className="text-2xl font-bold text-primary">BTP Xpress</span>
      </Link>
    </div>
  );

  const end = (
    <div className="flex align-items-center">
      <Button
        icon="pi pi-bell"
        className="p-button-text p-button-rounded p-button-plain mr-2"
        badge="3"
        badgeClassName="p-badge-danger"
      />
      <Avatar
        image={user?.avatar || '/default-avatar.png'}
        shape="circle"
        size="normal"
        className="cursor-pointer"
        onClick={(e) => profileMenuRef.current?.toggle(e)}
      />
      <Menu
        ref={profileMenuRef}
        model={profileItems}
        popup
        className="mt-2"
      />
    </div>
  );

  if (!isAuthenticated) {
    return <>{children}</>;
  }

  return (
    <div className="layout-wrapper">
      {/* Navigation principale */}
      <Menubar
        model={navItems}
        start={start}
        end={end}
        className="layout-topbar"
      />

      {/* Sidebar */}
      <Sidebar
        visible={sidebarVisible}
        onHide={() => setSidebarVisible(false)}
        className="layout-sidebar"
        modal={false}
      >
        <div className="layout-sidebar-content">
          <div className="layout-menu">
            {sidebarItems.map((item, index) => (
              <div key={index} className="layout-menuitem">
                {item.items ? (
                  <div>
                    <div className="layout-menuitem-text">
                      <i className={item.icon}></i>
                      <span>{item.label}</span>
                    </div>
                    <div className="layout-submenu">
                      {item.items.map((subItem, subIndex) => (
                        <div
                          key={subIndex}
                          className="layout-submenuitem"
                          onClick={subItem.command}
                        >
                          <i className={subItem.icon}></i>
                          <span>{subItem.label}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <div
                    className="layout-menuitem-text"
                    onClick={item.command}
                  >
                    <i className={item.icon}></i>
                    <span>{item.label}</span>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </Sidebar>

      {/* Contenu principal */}
      <div className="layout-main">
        <div className="layout-content">
          {children}
        </div>
      </div>
    </div>
  );
};
