import React, { useEffect, useState } from 'react';
import {
    Box,
    Typography,
    FormControl,
    RadioGroup,
    FormControlLabel,
    Radio,
    Grid,
    Select,
    MenuItem,
    Checkbox,
    FormGroup,
    Paper,
    Avatar,
    Button,
    Chip,
    AlertColor,
    Snackbar,
    Alert
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import HomeIcon from '@mui/icons-material/Home';
import DoDisturbIcon from '@mui/icons-material/DoDisturb';
import PersonOffIcon from '@mui/icons-material/PersonOff';
import CommuteIcon from '@mui/icons-material/Commute';
import SickIcon from '@mui/icons-material/Sick';
import FamilyRestroomIcon from '@mui/icons-material/FamilyRestroom';
import BeachAccessIcon from '@mui/icons-material/BeachAccess';
import BusinessIcon from '@mui/icons-material/Business';
import SaveIcon from '@mui/icons-material/Save';
import { useWorkStatusStore } from '@/shared/api/stores/WorkStatusStore';
import { DateRangeOption, StatusType } from '@/shared/types/client';

const WorkStatusComponent = () => {
    const [status, setStatus] = useState('bureau');
    const [selectedDates, setSelectedDates] = useState('');
    const [disableNotifications, setDisableNotifications] = useState(false);
    const [disableOnline, setDisableOnline] = useState(false);

    const dateOptions = [
        { value: 'today', label: "Aujourd'hui" }, 
        { value: 'tomorrow', label: 'Demain' },
        { value: 'week', label: 'Cette semaine' }
    ];

    const statusOptions = [
        {
            value: 'bureau',
            label: 'Au bureau',
            icon: <BusinessIcon sx={{ fontSize: 20 }} />,
            color: '#4caf50'
        },
        {
            value: 'domicile',
            label: 'Travail à domicile',
            icon: <HomeIcon sx={{ fontSize: 20 }} />,
            color: '#2196f3'
        },
        {
            value: 'hors_bureau',
            label: 'Travail hors du bureau',
            icon: <CommuteIcon sx={{ fontSize: 20 }} />,
            color: '#ff9800'
        },
        {
            value: 'absent',
            label: 'Absent(e) du bureau',
            icon: <PersonOffIcon sx={{ fontSize: 20 }} />,
            color: '#f44336'
        },
        {
            value: 'ne_pas_deranger',
            label: 'Ne pas déranger',
            icon: <DoDisturbIcon sx={{ fontSize: 20 }} />,
            color: '#9c27b0'
        },
        {
            value: 'conge_maladie',
            label: 'En congé maladie',
            icon: <SickIcon sx={{ fontSize: 20 }} />,
            color: '#e91e63'
        },
        {
            value: 'en_famille',
            label: 'En famille',
            icon: <FamilyRestroomIcon sx={{ fontSize: 20 }} />,
            color: '#ff5722'
        },
        {
            value: 'en_conge',
            label: 'En congé',
            icon: <BeachAccessIcon sx={{ fontSize: 20 }} />,
            color: '#00bcd4'
        }
    ];

    const { createOrUpdateStatus, getTodayStatus } = useWorkStatusStore();
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<AlertColor>('success');


    const statusMap: Record<string, StatusType> = {
        bureau: StatusType.IN_OFFICE,
        domicile: StatusType.WORK_FROM_HOME,
        hors_bureau: StatusType.WORK_OFFSITE,
        absent: StatusType.OUT_OF_OFFICE,
        ne_pas_deranger: StatusType.DO_NOT_DISTURB,
        conge_maladie: StatusType.SICK_LEAVE,
        en_famille: StatusType.FAMILY_TIME,
        en_conge: StatusType.ON_LEAVE,
    };

    const dateMap: Record<string, DateRangeOption> = {
        today: DateRangeOption.TODAY,
        tomorrow: DateRangeOption.TOMORROW,
        week: DateRangeOption.THIS_WEEK,
    };

    useEffect(() => {
        const userId = localStorage.getItem('userId');
        if (userId) {
            getTodayStatus(parseInt(userId, 10)).then(() => {
                const current = useWorkStatusStore.getState().currentStatus;
                if (current) {
                    const statusKey = Object.entries(statusMap).find(([key, value]) => value === current.status)?.[0];
                    if (statusKey) setStatus(statusKey);
                    const dateKey = Object.entries(dateMap).find(([key, value]) => value === current.dateRangeOption)?.[0];
                    if (dateKey) setSelectedDates(dateKey);
                }
            });
        }
    }, [getTodayStatus]);

    const handleSave = async () => {
        const userId = localStorage.getItem('userId');
        if (!userId) {
            setSnackbarSeverity('error');
            setSnackbarMessage("Utilisateur non connecté");
            setSnackbarOpen(true);
            return;
        }

        const collaboratorId = parseInt(userId, 10);
        const statusBackend = statusMap[status];
        const dateBackend = selectedDates ? dateMap[selectedDates] : DateRangeOption.TODAY;

        try {
            await getTodayStatus(collaboratorId);

            await createOrUpdateStatus({
                collaboratorId,
                status: statusBackend,
                dateRangeOption: dateBackend,
                customStartDate: null,
                customEndDate: null,
            });

            setSnackbarSeverity('success');
            setSnackbarMessage("Statut du jour mis à jour avec succès.");
            setSnackbarOpen(true);
        } catch (err) {
            setSnackbarSeverity('error');
            setSnackbarMessage("Erreur lors de l'enregistrement du statut.");
            setSnackbarOpen(true);
            console.error(err);
        }
    };


    return (
        <Paper sx={{ p: 4, borderRadius: 2, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <Typography variant="h4" component="h1" sx={{ fontWeight: 600, color: '#1976d2' }}>
                    Statut de travail
                </Typography>
            </Box>
            <Typography variant="body1" sx={{ mb: 4, color: 'text.secondary', fontSize: '1.1rem' }}>
                Informez tout le monde de votre statut
            </Typography>

            <FormControl component="fieldset" fullWidth>
                <RadioGroup value={status} onChange={(e) => setStatus(e.target.value)}>
                    <Grid container spacing={2}>
                        {statusOptions.map((option) => (
                            <Grid item xs={12} sm={6} md={4} key={option.value}>
                                <FormControlLabel
                                    value={option.value}
                                    control={
                                        <Radio sx={{ '&.Mui-checked': { color: option.color } }} />
                                    }
                                    label={
                                        <Box sx={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            p: 1,
                                            borderRadius: 1,
                                            bgcolor: status === option.value ? `${option.color}10` : 'transparent',
                                            border: status === option.value ? `1px solid ${option.color}30` : '1px solid transparent',
                                            transition: 'all 0.2s ease-in-out'
                                        }}>
                                            <Avatar sx={{
                                                mr: 2,
                                                width: 32,
                                                height: 32,
                                                bgcolor: option.color,
                                                boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
                                            }}>
                                                {option.icon}
                                            </Avatar>
                                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                                {option.label}
                                            </Typography>
                                        </Box>
                                    }
                                    sx={{
                                        width: '100%',
                                        m: 0,
                                        '& .MuiFormControlLabel-label': { width: '100%' }
                                    }}
                                />
                            </Grid>
                        ))}
                    </Grid>
                </RadioGroup>
            </FormControl>

            <Box sx={{ mt: 4, mb: 3 }}>
                <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2, color: 'text.primary' }}>
                    Période (facultatif)
                </Typography>
                <FormControl fullWidth variant="outlined" sx={{ bgcolor: '#f8f9fa', borderRadius: 2 }}>
                    <Select
                        value={selectedDates}
                        onChange={(e) => setSelectedDates(e.target.value)}
                        IconComponent={KeyboardArrowDownIcon}
                        displayEmpty
                        renderValue={(value) => {
                            if (!value) return "Choisir les dates (facultatif)";
                            const selectedOption = dateOptions.find(option => option.value === value);
                            return selectedOption ? selectedOption.label : "Choisir les dates (facultatif)";
                        }}
                        sx={{
                            '& .MuiOutlinedInput-notchedOutline': { border: 'none' },
                            color: 'text.secondary',
                            '&:hover': { bgcolor: '#e9ecef' }
                        }}
                    >
                        {dateOptions.map((option) => (
                            <MenuItem key={option.value} value={option.value}>
                                {option.label}
                            </MenuItem>
                        ))}
                    </Select>
                </FormControl>
            </Box>

            <Box sx={{ mt: 4, mb: 3 }}>
                <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2, color: 'text.primary' }}>
                    Paramètres de notification
                </Typography>
                <FormGroup>
                    <FormControlLabel
                        control={
                            <Checkbox
                                checked={disableNotifications}
                                onChange={(e) => setDisableNotifications(e.target.checked)}
                                sx={{ color: '#1976d2' }}
                            />
                        }
                        label="D&#233;sactiver les notifications par e-mail et par mobile pendant votre absence du bureau"
                        sx={{ mb: 1 }}
                    />
                </FormGroup>
            </Box>

            <Box sx={{ mt: 4, mb: 3 }}>
                <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2, color: 'text.primary' }}>
                    Indication de l&#39;activité de l&#39;utilisateur
                </Typography>
                <FormGroup>
                    <FormControlLabel
                        control={
                            <Checkbox
                                checked={disableOnline}
                                onChange={(e) => setDisableOnline(e.target.checked)}
                                sx={{ color: '#1976d2' }}
                            />
                        }
                        label="D&#233;sactiver l&#39;option en ligne (vous ne verrez pas non plus si d&#39;autres personnes sont en ligne)"            />
                </FormGroup>
            </Box>

            <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                <Button variant="outlined" sx={{ px: 3, py: 1.5, borderRadius: 2, textTransform: 'none', fontSize: '1rem' }}>
                    Annuler
                </Button>
                <Button
                    variant="contained"
                    startIcon={<SaveIcon />}
                    onClick={handleSave}
                    sx={{
                        px: 3,
                        py: 1.5,
                        borderRadius: 2,
                        textTransform: 'none',
                        fontSize: '1rem',
                        bgcolor: '#1976d2',
                        '&:hover': { bgcolor: '#1565c0' }
                    }}
                >
                    Enregistrer
                </Button>
            </Box>

            <Snackbar
                open={snackbarOpen}
                autoHideDuration={4000}
                onClose={() => setSnackbarOpen(false)}
                anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            >
                <Alert onClose={() => setSnackbarOpen(false)} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </Paper>
    );
};

export default WorkStatusComponent;