"use client";
import UserProfileCard from "../components/big-card-infos";
import SecondaryDetails from "../components/secondary-details";
import { Box } from "@mui/system";
import TeamsCard from "../components/teams-card";
import { useState, useEffect } from "react";
import AccountScheduleModal from "../components/Account-schedule-modal";
import { Typography } from "@mui/material";
import { IClient, MainBranch, PortalAssignment,UserStatus ,AddressType, IAgent} from "@/shared/types/client";
import { Civility } from "@/shared/types/common";
import { useCollaboratorStore } from "@/shared/api/stores/CollaboratorStore";
import ConditionalComponent from "@/shared/components/table/ConditionalComponent";

export const _clients: IClient[] = [
    {
      id: "1",
      createdAt: "2024-01-01T10:00:00Z",
      updatedAt: "2024-04-01T12:00:00Z",
      firstName: "Jean",
      lastName: "Dupont",
      email: "jean.dupont@example.com",
      phoneNumber: "0601020304",
      password: "securePassword123",
      isArchived: false,
      clientName: "Société Dupont SARL",
      landlinePhone: "0145678910",
      mainBranch: MainBranch.CLIENT,
      agencyName: "Agence Paris",
      portalAssignment: PortalAssignment.CLIENT,
      signatureDate: "2024-01-15",
      colorCode: "#FF5733",
      department: "75",
      siret: "12345678900012",
      tva: "FR12345678901",
      agency_id: 101,
      apeCode: "6201",
      paymentDate: "2024-02-01",
      observation: "Client prioritaire",
      bankName: "BNP Paribas",
      iban: "FR7612345678901234567890123",
      auxiliaryAccount: "411000",
      salesAccount: "707000",
      accountingAccount: "401000",
      accountHolder: "Jean Dupont",
      accountAddress: "10 rue de Paris, 75001 Paris",
      swiftBic: "BNPAFRPPXXX",
      typeClient: "CLIENT_DO",
      addresses: [
        {
          id: "addr-001",
          createdAt: "2024-01-01T00:00:00Z",
          updatedAt: "2024-01-01T00:00:00Z",
          street: "10 rue de Paris",
          city: "Paris",
          zipCode: "75001",
          country: "France",
          latitude: 48.8566,
          longitude: 2.3522,
          addressType: AddressType.CLIENT
        }
      ],
      birthDate: "1980-05-15",
      birthPlace: "Lyon",
      civility: Civility.MR,
      photoUrl: "https://example.com/photos/jean.jpg",
      userStatus: UserStatus.ACTIF,
      roles: []
    },
  ];
  

export default function ClientProfileInfos() {
    const [open, setOpen] = useState(false);
    const [collaborator, setCollaborator] = useState<IAgent | null>(null);
    
    const { getCollaboratorById, loading } = useCollaboratorStore();

    useEffect(() => {
        loadCollaborator();
    }, []);

    const loadCollaborator = async () => {
        const userId = localStorage.getItem('userId');
        if (!userId) {
            console.error('Aucun userId trouvé dans le localStorage');
            return;
        }
        
        try {
            const collaboratorData = await getCollaboratorById(userId);
            setCollaborator(collaboratorData);
        } catch (error) {
            console.error('Erreur lors du chargement du collaborateur:', error);
        }
    };

    return (
        <>
            <Box sx={{ 
                height: '100%', 
                width: "100%", 
                padding: { xs: 2, sm: 3, md: 4, lg: 5 }, 
                display: 'flex', 
                flexDirection: 'column', 
                gap: { xs: 2, sm: 3, md: 4 },
                bgcolor: 'grey.50',
                minHeight: '100vh'
            }}>
                {/* En-tête avec titre et indicateur de chargement */}
                <Box sx={{ 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'space-between',
                    mb: 2
                }}>
                    <Typography 
                        variant="h4" 
                        component="h1" 
                        sx={{ 
                            fontWeight: 600,
                            color: 'primary.main',
                            fontSize: { xs: '1.5rem', sm: '2rem', md: '2.125rem' }
                        }}
                    >
                        Profil Collaborateur
                    </Typography>
                    
                    {loading && (
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Box
                                sx={{
                                    width: 20,
                                    height: 20,
                                    borderRadius: '50%',
                                    border: '2px solid',
                                    borderColor: 'primary.main',
                                    borderTopColor: 'transparent',
                                    animation: 'spin 1s linear infinite',
                                    '@keyframes spin': {
                                        '0%': { transform: 'rotate(0deg)' },
                                        '100%': { transform: 'rotate(360deg)' }
                                    }
                                }}
                            />
                            <Typography variant="body2" color="primary">
                                Chargement...
                            </Typography>
                        </Box>
                    )}
                </Box>

                {/* Carte principale du profil */}
                <Box sx={{ mb: { xs: 2, sm: 3 } }}>
                    <UserProfileCard open={() => setOpen(true)} collaborator={collaborator} />
                </Box>

                {/* Section des détails et équipes */}
                <Box sx={{ 
                    display: 'flex', 
                    width: "100%", 
                    gap: { xs: 2, sm: 3 }, 
                    flexDirection: { xs: 'column', lg: 'row' }, 
                    flex: 1
                }}>
                    {/* Détails secondaires */}
                    <Box sx={{ flex: { lg: 1 } }}>
                        <SecondaryDetails collaborator={collaborator} />
                    </Box>
                    
                    {/* Carte des équipes */}
                    <Box sx={{ flex: { lg: 1 } }}>
                        <TeamsCard teams={collaborator?.teams} />
                    </Box>
                </Box>

                {/* Message d'erreur si problème de chargement */}
                <ConditionalComponent isValid={!loading && !collaborator}>
                    <Box sx={{ 
                        textAlign: 'center', 
                        py: 4,
                        bgcolor: 'error.light',
                        borderRadius: 2,
                        color: 'error.contrastText'
                    }}>
                        <Typography variant="h6" gutterBottom>
                            Erreur de chargement
                        </Typography>
                        <Typography variant="body2">
                            Impossible de charger les informations du collaborateur.
                        </Typography>
                    </Box>
                </ConditionalComponent>
            </Box>

            {/* Modal de l'emploi du temps */}
            <AccountScheduleModal
                open={open}
                onClose={() => setOpen(false)}
                collaborator={collaborator}
            />
        </>
    );
}