'use client';

import React from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  List,
  ListItem,
  ListItemText,
  Chip,
  IconButton,
  Divider,
} from '@mui/material';
import { formatDate, dateFormat } from '@/utils/format-time';
import { type IRevision, type IRevisionHistory } from '@/shared/types/flottes/revision';
import { getRevisionActionLabel, _revisionHistory, getRevisionStatut } from '@/shared/_mock/flottes/_revision';
import FontAwesome from '@/shared/components/fontawesome';
import { faClose, faHistory } from '@fortawesome/free-solid-svg-icons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface RevisionHistoryModalProps {
  open: boolean;
  onClose: () => void;
  revision: IRevision | null;
}

export default function RevisionHistoryModal({
  open,
  onClose,
  revision,
}: RevisionHistoryModalProps) {
  // Use ConditionalComponent to handle null revision
  if (!revision) return null;

  // Filter history for this specific revision
  const revisionHistory = _revisionHistory.filter(
    (h) => h.revisionId === revision.id
  ).sort((a, b) => new Date(b.actionDate).getTime() - new Date(a.actionDate).getTime());

  const hasHistory = revisionHistory.length > 0;

  const getActionChipColor = (action: string) => {
    switch (action) {
      case 'CREATED':
        return 'success';
      case 'UPDATED':
        return 'primary';
      case 'STATUS_CHANGED':
        return 'warning';
      case 'ARCHIVED':
        return 'error';
      case 'RESTORED':
        return 'success';
      case 'CT_DOCUMENT_UPLOADED':
      case 'CT_DOCUMENT_REMOVED':
        return 'info';
      default:
        return 'default';
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <FontAwesome icon={faHistory} width={20} />
          <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
            Historique - {revision.immatriculation}
          </Typography>
          <IconButton onClick={onClose} size="small">
            <FontAwesome icon={faClose} width={16} />
          </IconButton>
        </Box>
      </DialogTitle>
      
      <DialogContent>
        <Box sx={{ mb: 2 }}>
          <Typography variant="body2" color="text.secondary">
            Véhicule: {revision.idfFlotteVehicule} - {revision.personne}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Statut actuel: {getRevisionStatut(revision.statutCT)}
          </Typography>
        </Box>

        <Divider sx={{ mb: 2 }} />

        {/* Use ConditionalComponent for empty state vs history list */}
        <ConditionalComponent
          isValid={hasHistory}
          defaultComponent={
            <Box sx={{ textAlign: 'center', py: 4 }}>
              <Typography variant="body1" color="text.secondary">
                Aucun historique disponible pour cette révision
              </Typography>
            </Box>
          }
        >
          <List sx={{ width: '100%' }}>
            {revisionHistory.map((historyItem, index) => (
              <React.Fragment key={historyItem.id}>
                <ListItem alignItems="flex-start" sx={{ px: 0 }}>
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
                        <Chip
                          label={getRevisionActionLabel(historyItem.action)}
                          size="small"
                          color={getActionChipColor(historyItem.action) as any}
                          sx={{ fontWeight: 500 }}
                        />
                        <Typography variant="body2" color="text.secondary">
                          par {historyItem.actionBy}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          le {formatDate(historyItem.actionDate, dateFormat.dateTime)}
                        </Typography>
                      </Box>
                    }
                    secondary={
                      <Box>
                        <ConditionalComponent isValid={!!(historyItem.previousStatus && historyItem.newStatus)}>
                          <Typography variant="body2" sx={{ mb: 0.5 }}>
                            Statut: {getRevisionStatut(historyItem.previousStatus!)} → {getRevisionStatut(historyItem.newStatus!)}
                          </Typography>
                        </ConditionalComponent>
                        
                        <ConditionalComponent isValid={!!historyItem.comment}>
                          <Typography variant="body2" color="text.secondary">
                            {historyItem.comment}
                          </Typography>
                        </ConditionalComponent>
                        
                        <ConditionalComponent isValid={!!historyItem.changes}>
                          <Typography variant="body2" color="text.secondary">
                            Modification: {historyItem.changes?.field} - 
                            {historyItem.changes?.oldValue} → {historyItem.changes?.newValue}
                          </Typography>
                        </ConditionalComponent>
                      </Box>
                    }
                  />
                </ListItem>
                
                {/* Use ConditionalComponent for dividers between items */}
                <ConditionalComponent isValid={index < revisionHistory.length - 1}>
                  <Divider />
                </ConditionalComponent>
              </React.Fragment>
            ))}
          </List>
        </ConditionalComponent>
      </DialogContent>

      <DialogActions>
        <Button onClick={onClose} variant="outlined">
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  );
} 