"use client"
import { useEffect, useState } from 'react';
import { Box, CircularProgress, Paper, Typography } from '@mui/material';
import AdminApplicationDashboard from '@/shared/sections/home/admin-dash';
import EmployeDashboard from '@/shared/sections/home/employee-dash';
import ResponsableAgenceDashboard from '@/shared/sections/home/manager-dash';
import ClientDashbord from '@/shared/sections/home/client-dash';
import UserHome from '@/shared/sections/home/user-dash';
import { useSnackbar } from '@/components/snackbar';
import { getTokenInfo } from "@/utils/token";

type DashboardStateType = {
  roles: string[];
  selectedAgencyRole: string;
  selectedAgencyName: string;
  loading: boolean;
};

export default function Home() {
  const { enqueueSnackbar } = useSnackbar();
  const [state, setState] = useState<DashboardStateType>({
    roles: [],
    selectedAgencyRole: '',
    selectedAgencyName: '',
    loading: true
  });

  useEffect(() => {
    const initializeDashboard = () => {
      try {
        const roles = JSON.parse(localStorage.getItem('role') || '[]');
        const agencyRoles = JSON.parse(localStorage.getItem('agency_role') || '{}');
        const selectedAgencyId = localStorage.getItem('selectedAgency') || '';
        const selectedAgencyDetails = JSON.parse(localStorage.getItem('selectedAgencyDetails') || '{}');
    
        if (Object.keys(agencyRoles).length > 0) {
          const currentAgencyId = selectedAgencyId || Object.keys(agencyRoles)[0];
          const currentRole = agencyRoles[currentAgencyId];
          
          if (!selectedAgencyId) {
            localStorage.setItem('selectedAgency', currentAgencyId);
            localStorage.setItem('selectedAgencyDetails', JSON.stringify({
              id: currentAgencyId,
              role: currentRole
            }));
          }

          setState({
            roles,
            selectedAgencyRole: currentRole,
            selectedAgencyName: selectedAgencyDetails.name || '',
            loading: false
          });
        } else {
          setState({
            roles,
            selectedAgencyRole: '',
            selectedAgencyName: '',
            loading: false
          });
        }
      } catch (error) {
        console.error('❌ Error initializing dashboard:', error);
        setState(prev => ({ ...prev, loading: false }));
      }
    };

    initializeDashboard();

    const handleAgencyChange = (event: CustomEvent) => {
      const { role, name } = event.detail;
      setState(prev => ({
        ...prev,
        selectedAgencyRole: role,
        selectedAgencyName: name,
        loading: false
      }));
    };

    window.addEventListener('agencyChange', handleAgencyChange as EventListener);
    return () => window.removeEventListener('agencyChange', handleAgencyChange as EventListener);
  }, []);

  const renderDashboard = () => {
    if (state.loading) {
      return (
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh">
          <CircularProgress />
        </Box>
      );
    }
    
    const agencyRoles = JSON.parse(localStorage.getItem('agency_role') || '{}');
    const selectedAgencyId = localStorage.getItem('selectedAgency') || '';
    
    if (state.roles.includes('ADMIN')) {
      return <AdminApplicationDashboard />;
    }

    if (Object.keys(agencyRoles).length > 0 && state.selectedAgencyRole) {
      switch (state.selectedAgencyRole.toUpperCase()) {
        case 'MANAGER':
          return <ResponsableAgenceDashboard agencyId={selectedAgencyId || undefined} />;
        case 'COLLABORATOR':
          return <EmployeDashboard agencyId={selectedAgencyId || undefined} />;
        case 'CLIENT':
          return <ClientDashbord agencyId={selectedAgencyId || undefined} />;
      }
    }
    
    const token = localStorage.getItem('token');
    let userInfo = null;
    
    if (token) {
      const tokenInfo = getTokenInfo(token);
      userInfo = {
        name: tokenInfo.name,
        email: tokenInfo.email
      };
    }

    return <UserHome user={userInfo} />;
  };

  return renderDashboard();
}