import { 
  Drawer,
  Box,
  Typography,
  IconButton,
  TextField,
  Stack,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid
} from '@mui/material';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faArrowLeft,
  faPencil,
  faBell,
  faClock,
  faCalendar,
  faUser,
  faInfoCircle,
  faCircleCheck,
  faComments,
  faCar
} from '@fortawesome/free-solid-svg-icons';
import { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from "@/shared/components/form/buttons-action";
import { centerFlexColumn } from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import {
  drawerStyles,
  headerStyles,
  closeButtonStyles,
  titleStyles,
  actionButtonsStyles
} from '../styles/event-details-dialog.styles';
import { INTERVENTION_TYPES, STATUS_OPTIONS } from '../constants/event-details.constants';
import { 
  formatDuration, 
  formatEventDate,
  getStatusColor,
  getStatusLabel,
  getTypeLabel 
} from '../utils/event-details.utils';
import { EventDetailsDialogProps } from '../types/event-details.types';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

export default function PlanningEventDetailsDialog({ open, onClose, event, onEventUpdate }: EventDetailsDialogProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editedEvent, setEditedEvent] = useState(event);
  const [datePickerOpen, setDatePickerOpen] = useState(false);
  const [timePickerOpen, setTimePickerOpen] = useState(false);

  useEffect(() => {

    if (event?.start) {
    }
  }, [event]);

  useEffect(() => {
    if (event) {
    
      const eventData = {
        ...event,
        start: event.start ? new Date(event.start).toISOString() : null
      };
      
      setEditedEvent(eventData);
    }
  }, [event]);

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleSave = () => {
    onEventUpdate(editedEvent);
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditedEvent(event);
    setIsEditing(false);
  };

  const handleChange = (field: string, value: any) => {
    if (field === 'start') {
  
    }
    setEditedEvent(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleTimeInput = (name: string, value: string) => {
    // Allow empty value for fresh input
    if (!value) {
      return handleChange('start', null);
    }

    // Remove any non-digit characters except colon
    let timeValue = value.replace(/[^\d:]/g, '');
    
    // Handle backspace and deletion
    if (timeValue.length <= 5) {
      // If there's a colon, preserve it
      if (timeValue.includes(':')) {
        const [hours, minutes] = timeValue.split(':');
        // Validate hours
        if (hours && parseInt(hours) > 23) {
          timeValue = '23' + (minutes ? `:${minutes}` : ':');
        }
        // Validate minutes
        if (minutes && parseInt(minutes) > 59) {
          timeValue = hours + ':59';
        }
      } else {
        // Add colon after 2 digits
        if (timeValue.length >= 2) {
          timeValue = timeValue.slice(0, 2) + ':' + timeValue.slice(2);
        }
      }

      // Update the event time if we have a valid time
      if (timeValue.match(/^\d{2}:\d{2}$/)) {
        const [hours, minutes] = timeValue.split(':');
        const currentDate = editedEvent?.start ? new Date(editedEvent.start) : new Date();
        currentDate.setHours(parseInt(hours));
        currentDate.setMinutes(parseInt(minutes));
        handleChange('start', currentDate.toISOString());
      }
    }

    // Update the display value
    setEditedEvent(prev => ({
      ...prev,
      displayTime: timeValue
    }));
  };

  // Add this function to handle comment changes
  const handleCommentChange = (name: string, value: string) => {
    setEditedEvent(prev => ({
      ...prev,
      notes: value
    }));
  };

  if (!editedEvent) return null;

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      variant="persistent"
      sx={drawerStyles}
    >
      <Box sx={headerStyles}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <IconButton
            onClick={onClose}
            sx={{
              bgcolor: 'primary.main',
              color: 'white',
              width: 32,
              height: 32,
              '&:hover': {
                bgcolor: 'primary.dark'
              }
            }}
          >
            <FontAwesomeIcon icon={faArrowLeft} width={14} />
          </IconButton>
          <Typography 
            variant="h6" 
            sx={{ 
              ...titleStyles,
              // Make the title smaller when in edit mode
              fontSize: isEditing ? pxToRem(16) : pxToRem(20),
            }}
          >
            Détails de l&apos;intervention
          </Typography>
        </Box>

        <Box>
          <ConditionalComponent 
            isValid={!isEditing}
          >
            <IconButton 
              onClick={handleEdit}
              sx={{
                bgcolor: 'primary.main',
                color: 'white',
                width: 32,
                height: 32,
                '&:hover': {
                  bgcolor: 'primary.dark'
                }
              }}
            >
              <FontAwesomeIcon icon={faPencil} width={14} />
            </IconButton>
          </ConditionalComponent>
          <ConditionalComponent 
            isValid={isEditing}
          >
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography 
                variant="caption" 
                sx={{ 
                  backgroundColor: 'primary.lighter',
                  color: 'primary.main',
                  px: 1.5,
                  py: 0.5,
                  borderRadius: 1,
                  fontSize: '0.75rem'
                }}
              >
                Mode édition
              </Typography>
            </Box>
          </ConditionalComponent>
        </Box>
      </Box>

      <Box sx={{ px: 3, mt: 4 }}>
        <form>
          <Grid container spacing={2}>
            {/* Type d'intervention */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'type',
                  label: "Type d'intervention",
                  type: 'select',
                  icon: faInfoCircle,
                  options: INTERVENTION_TYPES
                }}
                value={editedEvent?.type}
                onChange={(name, value) => handleChange('type', value)}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Date */}
            <Grid item xs={12}>
              <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
                <DatePicker
                  label="Date"
                  value={editedEvent?.start ? new Date(editedEvent.start) : null}
                  onChange={(newValue) => {
                    if (newValue) {
                      const currentDate = editedEvent?.start ? new Date(editedEvent.start) : new Date();
                      const newDate = new Date(newValue);
                      newDate.setHours(currentDate.getHours());
                      newDate.setMinutes(currentDate.getMinutes());
                      handleChange('start', newDate.toISOString());
                    }
                  }}
                  readOnly={!isEditing}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      placeholder: 'DD/MM/YYYY',
                      InputProps: {
                        endAdornment: (
                          <FontAwesomeIcon 
                            icon={faCalendar} 
                            style={{ color: !isEditing ? '#9e9e9e' : '#7635dc' }}
                          />
                        ),
                      }
                    }
                  }}
                  sx={{
                    width: '100%',
                    '& .MuiInputBase-root': {
                      backgroundColor: !isEditing ? '#f5f5f5' : 'white',
                      cursor: !isEditing ? 'not-allowed' : 'pointer',
                    },
                    '& .MuiInputBase-input': {
                      cursor: !isEditing ? 'not-allowed' : 'text',
                      color: !isEditing ? 'text.disabled' : 'text.primary',
                    }
                  }}
                />
              </LocalizationProvider>
            </Grid>

            {/* Time field with updated handling */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'time',
                  label: 'Heure',
                  type: 'text',
                  icon: faClock,
                  placeholder: 'HH:mm'
                }}
                value={editedEvent?.displayTime || (editedEvent?.start ? format(new Date(editedEvent.start), 'HH:mm') : '')}
                onChange={(name, value) => handleTimeInput(name, value)}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Updated Duration field */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'estimatedDuration',
                  label: 'Durée',
                  type: 'text',
                  icon: faClock,
                }}
                value={formatDuration(editedEvent?.estimatedDuration)}
                onChange={(name, value) => {
                  // Extract number from string when editing
                  const hours = parseFloat(value.replace(/[^0-9.]/g, ''));
                  handleChange('estimatedDuration', hours);
                }}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Véhicule concerné */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'vehicle',
                  label: 'Véhicule concerné',
                  type: 'text',
                  icon: faCar
                }}
                value={editedEvent?.vehicle ? `${editedEvent.vehicle.immatriculation} - ${editedEvent.vehicle.marque} ${editedEvent.vehicle.modele}` : ''}
                onChange={(name, value) => handleChange('vehicle', value)}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Technicien */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'technician',
                  label: 'Technicien assigné',
                  type: 'text',
                  icon: faUser
                }}
                value={editedEvent?.technician}
                onChange={(name, value) => handleChange('technician', value)}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Status */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'status',
                  label: 'Statut',
                  type: 'select',
                  icon: faCircleCheck,
                  options: STATUS_OPTIONS
                }}
                value={editedEvent?.status}
                onChange={(name, value) => handleChange('status', value)}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            {/* Comments field */}
            <Grid item xs={12}>
              <FormField
                field={{
                  name: 'notes',
                  label: 'Commentaires',
                  type: 'textarea',
                  placeholder: 'Ajouter un commentaire...',
                  rows: 4 // Add this to make textarea bigger
                }}
                value={editedEvent?.notes || ''}
                onChange={handleCommentChange}
                isReadOnly={!isEditing}
                isDrawerElement
              />
            </Grid>

            <ConditionalComponent 
              isValid={isEditing}
            >
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 2 }}>
                  <ActionButtons
                    onSave={handleSave}
                    onCancel={handleCancel}
                    mode="edit"
                  />
                </Box>
              </Grid>
            </ConditionalComponent>
          </Grid>
        </form>
      </Box>
    </Drawer>
  );
} 