import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  Typography,
  Box,
  Divider,
  List,
  ListItem,
  ListItemText,
  CircularProgress,
} from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { ILeaveHistory } from '@/shared/types/leave';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface HistoriqueDialogProps {
  open: boolean;
  onClose: () => void;
  absenceId: string;
}

export default function HistoriqueDialog({ open, onClose, absenceId }: HistoriqueDialogProps) {
  const [historique, setHistorique] = useState<ILeaveHistory[]>([]);
  const [loading, setLoading] = useState(false);
  const { getLeaveHistory } = useAbsenceStoree();

  useEffect(() => {
    const fetchHistory = async () => {
      if (open && absenceId) {
        setLoading(true);
        try {
          const result = await getLeaveHistory(absenceId);
          if (result.success) {
            setHistorique(result.data);
          }
        } catch (error) {
          console.error('Failed to fetch history:', error);
        } finally {
          setLoading(false);
        }
      }
    };

    fetchHistory();
  }, [open, absenceId]);

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      maxWidth="md"
      fullWidth
      sx={{
        '& .MuiDialog-paper': {
          minWidth: '600px',
          maxHeight: '80vh'
        }
      }}
    >
      <DialogTitle>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h6">Historique des modifications</Typography>
          <IconButton onClick={onClose} size="small">
            <FontAwesome icon={faTimes} />
          </IconButton>
        </Box>
      </DialogTitle>
      
      <DialogContent>
        <ConditionalComponent 
          isValid={loading}
          defaultComponent={
            <List sx={{ width: '100%' }}>
              <ConditionalComponent 
                isValid={historique && historique.length > 0}
                defaultComponent={
                  <ListItem>
                    <ListItemText 
                      primary={
                        <Typography color="text.secondary" align="center">
                          Aucun historique disponible
                        </Typography>
                      }
                    />
                  </ListItem>
                }
              >
                {historique.map((item, index) => (
                  <React.Fragment key={index}>
                    <ListItem alignItems="flex-start">
                      <ListItemText
                        primary={
                          <Box display="flex" justifyContent="space-between" mb={1}>
                            <Typography variant="subtitle1" color="primary" sx={{ fontWeight: 'bold' }}>
                              {item.action}
                            </Typography>
                            <Typography variant="body2" color="text.secondary">
                              {item.date}
                            </Typography>
                          </Box>
                        }
                        secondary={
                          <Box>
                            <Typography variant="body2" color="text.primary" gutterBottom sx={{ fontWeight: 500 }}>
                              Par: {item.user}
                            </Typography>
                            
                            <Typography variant="body2" color="text.secondary">
                              {item.comment}
                            </Typography>
                            
                            <ConditionalComponent isValid={!!(item.previousState || item.newState)}>
                              <Box mt={1} sx={{ backgroundColor: 'rgba(0, 0, 0, 0.02)', p: 1, borderRadius: 1 }}>
                                <ConditionalComponent isValid={!!item.previousState}>
                                  <Typography variant="body2" color="text.secondary">
                                    Ancien statut: {item.previousState}
                                  </Typography>
                                </ConditionalComponent>
                                <ConditionalComponent isValid={!!item.newState}>
                                  <Typography variant="body2" color="text.secondary">
                                    Nouveau statut: {item.newState}
                                  </Typography>
                                </ConditionalComponent>
                              </Box>
                            </ConditionalComponent>
                          </Box>
                        }
                      />
                    </ListItem>
                    <ConditionalComponent isValid={index < historique.length - 1}>
                      <Divider component="li" />
                    </ConditionalComponent>
                  </React.Fragment>
                ))}
              </ConditionalComponent>
            </List>
          }
        >
          <Box display="flex" justifyContent="center" alignItems="center" p={3}>
            <CircularProgress />
          </Box>
        </ConditionalComponent>
      </DialogContent>
    </Dialog>
  );
}