import { IAgent } from '@/shared/types/client'
import { Card, CardContent, Input, List, ListItem, ListItemIcon, ListItemText, Button, Typography, CircularProgress } from '@mui/material'
import { faMicrosoft } from '@fortawesome/free-brands-svg-icons/faMicrosoft'
import { faBirthdayCake } from '@fortawesome/free-solid-svg-icons'
import React, { FC, useEffect, useState } from 'react'
import FontAwesome from '@/shared/components/fontawesome'
import { Box } from '@mui/system'
import { format } from 'date-fns'
import { fr } from 'date-fns/locale'
import { isValid } from 'date-fns'
import { useCollaboratorStore } from '@/shared/api/stores/CollaboratorStore'
import { enqueueSnackbar } from 'notistack'

interface SecondaryDetailsProps {
    collaborator: IAgent | null;
}

const SecondaryDetails: FC<SecondaryDetailsProps> = ({ collaborator }) => {
    const [skype, setSkype] = useState<string>(collaborator?.outlook || collaborator?.skype || '');
    const [isEditingSkype, setIsEditingSkype] = useState<boolean>(false);
    const [savingSkype, setSavingSkype] = useState<boolean>(false);
    const [whatsapp, setWhatsapp] = useState<string>(collaborator?.whatsapp || '');
    const [isEditingWhatsapp, setIsEditingWhatsapp] = useState<boolean>(false);
    const [savingWhatsapp, setSavingWhatsapp] = useState<boolean>(false);

    const { updateCollaboratorSkype, updateCollaboratorContact, updateCollaborator } = useCollaboratorStore();

    // Si Outlook ou WhatsApp ne sont pas définis, activer le mode édition par défaut
    useEffect(() => {
        if (!collaborator) return;
        setIsEditingSkype(!collaborator.outlook);
        setSkype(collaborator.outlook || '');
        setIsEditingWhatsapp(!collaborator.whatsapp);
        setWhatsapp(collaborator.whatsapp || '');
    }, [collaborator?.id]);

    const handleSkypeSave = async () => {
        if (!collaborator?.id || !skype.trim()) {
            enqueueSnackbar('Veuillez saisir un identifiant Outlook valide', { variant: 'warning' });
            return;
        }

        setSavingSkype(true);
        try {
            const updatedCollaborator = await updateCollaboratorContact(collaborator.id, 'outlook', skype.trim());

            if (updatedCollaborator) {
                enqueueSnackbar('Outlook mis à jour avec succès', { variant: 'success' });
                setIsEditingSkype(false);
                // Forcer l'affichage immédiat
                if (collaborator) {
                    (collaborator as any).outlook = skype.trim();
                }
            } else {
                enqueueSnackbar("Erreur lors de la mise à jour d'Outlook", { variant: 'error' });
            }
        } catch (error) {
            enqueueSnackbar("Erreur lors de la sauvegarde d'Outlook", { variant: 'error' });
        } finally {
            setSavingSkype(false);
        }
    };

    const formatBirthDate = (birthDate: string | null | undefined): string => {
        if (!birthDate) return 'Non renseigné';

        try {
            const date = new Date(birthDate);
            if (!isValid(date)) return 'Date invalide';

            // Obtenir l'année prochaine pour l'anniversaire
            const currentYear = new Date().getFullYear();
            const nextBirthday = new Date(date);
            nextBirthday.setFullYear(currentYear);

            // Si l'anniversaire de cette année est déjà passé, prendre l'année prochaine
            if (nextBirthday < new Date()) {
                nextBirthday.setFullYear(currentYear + 1);
            }

            return format(nextBirthday, 'dd MMMM yyyy', { locale: fr });
        } catch (error) {
            return 'Date invalide';
        }
    };

    if (!collaborator) {
        return (
            <Card sx={{ borderRadius: 1, height: '100%', width: "100%" }}>
                <CardContent>
                    <Typography variant="body1" color="text.secondary" sx={{ textAlign: 'center', mt: 2 }}>
                        Chargement des informations...
                    </Typography>
                </CardContent>
            </Card>
        );
    }

    return (
        <Card sx={{
            borderRadius: 2,
            height: '100%',
            width: "100%",
            boxShadow: 2,
            background: 'linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%)',
            border: '1px solid',
            borderColor: 'grey.200'
        }}>
            <CardContent sx={{ p: 3 }}>
                <Typography
                    variant="h6"
                    sx={{
                        mb: 3,
                        fontWeight: 600,
                        color: 'primary.main',
                        display: 'flex',
                        alignItems: 'center',
                        gap: 1
                    }}
                >
                    <Box
                        sx={{
                            width: 8,
                            height: 8,
                            borderRadius: '50%',
                            bgcolor: 'primary.main'
                        }}
                    />
                    Informations personnelles
                </Typography>

                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                    {/* Skype */}
                    <Box sx={{
                        p: 2.5,
                        bgcolor: 'grey.50',
                        borderRadius: 2,
                        border: '1px solid',
                        borderColor: 'grey.200',
                        transition: 'all 0.2s ease',
                        '&:hover': {
                            bgcolor: 'grey.100',
                            borderColor: 'primary.light',
                            boxShadow: 1
                        }
                    }}>
                        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                            <Box sx={{ 
                                p: 1, 
                                bgcolor: '#0078D4', 
                                borderRadius: 1,
                                mr: 2,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}>
                                <FontAwesome icon={faMicrosoft} width={16} color="white" />
                            </Box>
                            <Typography variant="subtitle1" sx={{ fontWeight: 600, color: 'text.primary' }}>
                                Outlook
                            </Typography>
                        </Box>

                        {isEditingSkype ? (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                <Input
                                    placeholder="Ajouter un identifiant Outlook"
                                    value={skype}
                                    onChange={(e) => setSkype(e.target.value)}
                                    sx={{
                                        flex: 1,
                                        '& .MuiInput-input': {
                                            fontFamily: 'monospace',
                                            fontSize: '1.1rem'
                                        }
                                    }}
                                    autoFocus
                                />
                                <Box sx={{ display: 'flex', gap: 1, ml: 'auto' }}>
                                    <Button
                                        size="small"
                                        variant="contained"
                                        onClick={handleSkypeSave}
                                        sx={{
                                            textTransform: 'none',
                                            borderRadius: 1.5
                                        }}
                                        disabled={savingSkype}
                                    >
                                        {savingSkype ? <CircularProgress size={16} /> : 'Sauvegarder'}
                                    </Button>
                                    <Button
                                        size="small"
                                        variant="outlined"
                                        onClick={() => {
                                            setIsEditingSkype(false);
                                            setSkype(collaborator?.outlook ||  '');
                                        }}
                                        sx={{
                                            textTransform: 'none',
                                            borderRadius: 1.5
                                        }}
                                        disabled={savingSkype}
                                    >
                                        Annuler
                                    </Button>
                                </Box>
                            </Box>
                        ) : (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                <Typography
                                    variant="body1"
                                    sx={{
                                        color: 'text.primary',
                                        fontWeight: 500,
                                        fontFamily: 'monospace',
                                        fontSize: '1.1rem'
                                    }}
                                >
                                    {(collaborator.outlook ) || 'Non défini'}
                                </Typography>
                                <Box sx={{ ml: 'auto' }}>
                                    <Button
                                        size="small"
                                        variant="contained"
                                        onClick={() => {
                                            setIsEditingSkype(true);
                                            setSkype(collaborator?.outlook || '');
                                        }}
                                        sx={{
                                            textTransform: 'none',
                                            borderRadius: 1.5,
                                        }}
                                        disabled={savingSkype}
                                    >
                                        {collaborator.outlook ? 'Modifier' : 'Affecter'}
                                    </Button>
                                </Box>
                            </Box>
                        )}
                    </Box>

                    {/* WhatsApp */}
                    <Box sx={{
                        p: 2.5,
                        bgcolor: 'grey.50',
                        borderRadius: 2,
                        border: '1px solid',
                        borderColor: 'grey.200',
                        transition: 'all 0.2s ease',
                        '&:hover': {
                            bgcolor: 'grey.100',
                            borderColor: 'primary.light',
                            boxShadow: 1
                        }
                    }}>
                        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                            <Box sx={{
                                p: 1,
                                bgcolor: '#25D366',
                                borderRadius: 1,
                                mr: 2,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}>
                                <Typography variant="caption" sx={{ color: 'white', fontWeight: 700 }}>WA</Typography>
                            </Box>
                            <Typography variant="subtitle1" sx={{ fontWeight: 600, color: 'text.primary' }}>
                                WhatsApp
                            </Typography>
                        </Box>

                        {isEditingWhatsapp ? (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                <Input
                                    placeholder="Ajouter un numéro WhatsApp"
                                    value={whatsapp}
                                    onChange={(e) => setWhatsapp(e.target.value)}
                                    sx={{ flex: 1 }}
                                    autoFocus
                                />
                                <Box sx={{ display: 'flex', gap: 1, ml: 'auto' }}>
                                    <Button size="small" variant="contained" onClick={() => {
                                        const newVal = whatsapp.trim();
                                        updateCollaboratorContact(collaborator!.id, 'whatsapp', newVal).then((res) => {
                                            enqueueSnackbar('Numéro WhatsApp mis à jour avec succès', { variant: 'success' });
                                            setIsEditingWhatsapp(false);
                                            if (collaborator) {
                                                (collaborator as any).whatsapp = newVal;
                                            }
                                        }).catch(() => enqueueSnackbar('Erreur lors de la sauvegarde du numéro WhatsApp', { variant: 'error' }));
                                    }} sx={{ textTransform: 'none', borderRadius: 1.5 }} disabled={savingWhatsapp}>
                                        {savingWhatsapp ? <CircularProgress size={16} /> : 'Sauvegarder'}
                                    </Button>
                                    <Button size="small" variant="outlined" onClick={() => { setIsEditingWhatsapp(false); setWhatsapp(collaborator?.whatsapp || ''); }} sx={{ textTransform: 'none', borderRadius: 1.5 }} disabled={savingWhatsapp}>
                                        Annuler
                                    </Button>
                                </Box>
                            </Box>
                        ) : (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                <Typography variant="body1" sx={{ color: 'text.primary', fontWeight: 500 }}>
                                    {collaborator.whatsapp || 'Non défini'}
                                </Typography>
                                <Box sx={{ display: 'flex', gap: 1, ml: 'auto' }}>
                                    <Button size="small" variant="contained" onClick={() => { setIsEditingWhatsapp(true); setWhatsapp(collaborator?.whatsapp || ''); }} sx={{ textTransform: 'none', borderRadius: 1.5 }}>
                                        {collaborator.whatsapp ? 'Modifier' : 'Affecter'}
                                    </Button>
                                </Box>
                            </Box>
                        )}
                    </Box>

                    {/* Anniversaire */}
                    <Box sx={{
                        p: 2.5,
                        bgcolor: 'grey.50',
                        borderRadius: 2,
                        border: '1px solid',
                        borderColor: 'grey.200',
                        transition: 'all 0.2s ease',
                        '&:hover': {
                            bgcolor: 'grey.100',
                            borderColor: 'primary.light',
                            boxShadow: 1
                        }
                    }}>
                        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                            <Box sx={{
                                p: 1,
                                bgcolor: '#FF6B6B',
                                borderRadius: 1,
                                mr: 2,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center'
                            }}>
                                <FontAwesome icon={faBirthdayCake} width={16} color="white" />
                            </Box>
                            <Typography variant="subtitle1" sx={{ fontWeight: 600, color: 'text.primary' }}>
                                Anniversaire
                            </Typography>
                        </Box>

                        <Typography
                            variant="body1"
                            sx={{
                                color: 'text.primary',
                                fontWeight: 500,
                                fontSize: '1.1rem'
                            }}
                        >
                            {formatBirthDate(collaborator.birthDate)}
                        </Typography>
                    </Box>
                </Box>
            </CardContent>
        </Card>
    )
}

export default SecondaryDetails
