import { useState, useEffect } from 'react';
import { Dialog, DialogContent, Typography, Stack, IconButton, Box, Chip, Avatar, Button, Divider, Menu, MenuItem, ListItemIcon, ListItemText, Select, FormControl, Drawer, Grid, InputLabel } from '@mui/material';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faXmark, 
  faUser, 
  faClock, 
  faFileLines, 
  faCircleExclamation,
  faComments,
  faFile,
  faPencil,
  faBell,
  faArrowRotateRight,
  faArchive,
  faEllipsisVertical,
  faCalendar,
  faLocationDot,
  faInfoCircle,
  faArrowLeft,
} from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import FormField from '@/shared/components/form/form-field';
import { ModeType } from '@/shared/types/common';
import { centerFlexColumn } from '@/shared/theme/css';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { CalendarEvent, EventStatus, FormField as IFormField, DialogProps } from '../types/calendar-types';
import ActionButtons from "@/shared/components/form/buttons-action";
import {
  STATUS_OPTIONS,
  EVENT_TYPES,
  DIALOG_CONSTANTS
} from '../constants/event.constants';
import {
  drawerStyles,
  headerStyles,
  closeButtonStyles,
  titleStyles,
  actionButtonsStyles,
  selectStyles,
  textareaStyles
} from '../styles/event-details-dialog.styles';
import { getFieldsForEmployeeType } from '../utils/event-fields.utils';
import { getFieldValue } from '../utils/event-values.utils';
import { useEventData } from '../hooks/use-event-data';

export default function EventDetailsDialog({ 
  open, 
  onClose,
  event,
  onEventUpdate 
}: DialogProps) {
  const [mode, setMode] = useState<ModeType>('view');
  const { formData, setFormData, status, setStatus, drivers, agencies, collaborators, setSelectedAgency } = useEventData(event, open);

  const isReadOnly = mode === 'view';

  const handleModifyClick = () => setMode('edit');

  const handleSave = () => {
  if (!formData) return;

  let employeeId = formData.employeeId;

  if (!employeeId && formData.employeeName) {
    const isDriver = formData.employeeType === 'DRIVER';
    const options = isDriver
      ? drivers
      : collaborators;

    const match = options.find(opt => 
      `${opt.firstName} ${opt.lastName}`.trim().toLowerCase() === formData.employeeName?.trim().toLowerCase()
    );

    if (match) {
      employeeId = match.id.toString();
    }
  }

  const payload = {
    ...formData,
    employeeId, 
    status,
    notes: formData.description,
    files: formData.files,
    comments: formData.comments
  };

  onEventUpdate?.(payload);
  setMode('view');
};


  const handleCancel = () => {
    if (event) {
      setFormData(event);
      const newStatus = (event.status || 'PENDING') as EventStatus;
      setStatus(newStatus);
    }
    setMode('view');
  };

  const handleFieldChange = (name: string, value: any) => {
    if (formData) {
      const updatedData = {
        ...formData,
        [name]: value
      };
      setFormData(updatedData as CalendarEvent);
    }
  };

  const renderField = (field: IFormField) => {
    
    if (field.name === 'time') {
      return (
        <FormField
          field={{
            name: field.name,
            label: field.label,
            type: isReadOnly ? 'text' : 'time',
            icon: faClock
          }}
          value={isReadOnly 
            ? getFieldValue(field, formData!, status) 
            : (formData?.hour || '')
          }
          onChange={isReadOnly ? () => {} : (name, value) => {
            handleFieldChange('hour', value);
          }}
          isReadOnly={isReadOnly}
          isDrawerElement
        />
      );
    }
    if (field.name === 'agencyName') {
      if (isReadOnly) {
        const agencyValue = formData?.employeeType === 'SEDENTARY' 
          ? (formData?.agence || 'Non spécifiée') 
          : 'Non applicable';
    
        return (
          <FormField
            field={{
              name: field.name,
              label: 'Agence',
              type: 'text',
              icon: field.icon
            }}
            value={agencyValue}
            onChange={() => {}}
            isReadOnly={true}
            isDrawerElement
          />
        );
      } else {
        if (agencies.length === 0) {
          return (
            <FormField
              field={{
                name: field.name,
                label: 'Agence',
                type: 'text',
                icon: field.icon
              }}
              value={formData?.agence || 'Chargement des agences...'}
              onChange={handleFieldChange}
              isReadOnly={true}
              isDrawerElement
            />
          );
        }
    
        const agencyOptions = agencies.map(agency => ({
          value: agency.id.toString(),
          label: agency.name
        }));
    
        let currentValue = '';
      if (formData?.agenceId) {
             currentValue = formData.agenceId.toString();
      } else if (formData?.agence) {
      const matchedAgency = agencies.find(opt => opt.name === formData.agence);
      if (matchedAgency) {
    currentValue = matchedAgency.id.toString();
  }
}
    
        return (
          <FormField
            field={{
              name: field.name,
              label: 'Agence',
              type: 'select',
              icon: field.icon,
              options: agencyOptions
            }}
            value={currentValue}
            onChange={(name, value) => {
              const selectedAgency = agencyOptions.find(opt => opt.value === value);
              handleFieldChange('agenceId', value);
              handleFieldChange('agence', selectedAgency?.label || '');
              setSelectedAgency(value); 
            }}
            isReadOnly={isReadOnly}
            isDrawerElement
          />
        );
      }
    }
    
    
    if (field.name === 'employeeName') {
      if (isReadOnly) {
        return (
          <FormField
            field={{
              name: field.name,
              label: formData?.employeeType === 'DRIVER' ? 'Chauffeur' : 'Agent',
              type: 'text',
              icon: field.icon
            }}
            value={formData?.employeeName || 'Non spécifié'}
            onChange={() => {}}
            isReadOnly={true}
            isDrawerElement
          />
        );
      } else {
        const isDriver = formData?.employeeType === 'DRIVER';
        
        if ((isDriver && drivers.length === 0) || (!isDriver && collaborators.length === 0)) {
          return (
            <FormField
              field={{
                name: field.name,
                label: isDriver ? 'Chauffeur' : 'Agent',
                type: 'text',
                icon: field.icon
              }}
              value={formData?.employeeName || 'Chargement des données...'}
              onChange={handleFieldChange}
              isReadOnly={true}
              isDrawerElement
            />
          );
        }
        
        const options = isDriver 
          ? drivers.map(driver => ({
              value: driver.id.toString(),
              label: `${driver.firstName} ${driver.lastName}`.trim()
            }))
          : collaborators.map(agent => ({
              value: agent.id.toString(),
              label: `${agent.firstName} ${agent.lastName}`
            }));

        let currentValue = '';

        if (formData?.employeeId) {
          currentValue = formData.employeeId.toString();
        }
        else if (formData?.employeeName) {
          currentValue = formData.employeeName;
        }
        
        return (
          <FormField
            field={{
              name: field.name,
              label: isDriver ? 'Chauffeur' : 'Agent',
              type: 'select',
              icon: field.icon,
              options: options
            }}
            value={currentValue}
            onChange={(name, value) => {
              const selectedOption = options.find(opt => opt.value === value);
              handleFieldChange('employeeId', value);
              handleFieldChange('employeeName', selectedOption?.label || '');
            }}
            isReadOnly={isReadOnly}
            isDrawerElement
          />
        );
      }
    }

    if (!field.hasCustomRender) {
      return (
        <Box sx={{ width: '100%' }}>
          <CustomTooltip 
            title={getFieldValue(field, formData!, status)} 
            arrow 
            placement="top"
          >
            <Box>
              <FormField
                field={{
                  name: field.name,
                  label: field.label,
                  type: field.type,
                  icon: field.icon
                }}
                value={getFieldValue(field, formData!, status)}
                onChange={handleFieldChange}
                isReadOnly={isReadOnly}
                isDrawerElement
                sx={{
                  '& .MuiInputBase-input': {
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }
                }}
              />
            </Box>
          </CustomTooltip>
        </Box>
      );
    }

    switch (field.name) {
      case 'type':
        return (
          <FormField
            field={{
              name: field.name,
              label: 'Type',
              type: 'select',
              icon: field.icon,
              options: [...EVENT_TYPES]
            }}
            value={formData!.type}
            onChange={(name, value) => handleFieldChange('type', value)}
            isReadOnly={isReadOnly}
            isDrawerElement
          />
        );
      
      case 'status':
        return (
          <FormField
            field={{
              name: field.name,
              label: 'Statut',
              type: 'select',
              icon: field.icon,
              options: [...STATUS_OPTIONS]
            }}
            value={status}
            onChange={(name, value) => {
              const newStatus = value as EventStatus;
              setStatus(newStatus);
              if (formData) {
                setFormData({
                  ...formData,
                  status: newStatus
                });
              }
            }}
            isReadOnly={isReadOnly}
            isDrawerElement
          />
        );

      case 'description':
      case 'comments':
        return (
          <FormField
            field={{
              name: field.name,
              label: field.label,
              type: 'textarea',
              icon: field.icon
            }}
            value={field.name === 'description' 
              ? (formData?.description || '') 
              : (formData?.comments || '')
            }
            onChange={handleFieldChange}
            isReadOnly={isReadOnly}
            isDrawerElement
            sx={textareaStyles}
          />
        );

      default:
        return null;
    }
  };

  if (!formData || !event) 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={closeButtonStyles}
          >
            <FontAwesome icon={faArrowLeft} width={16} />
          </IconButton>
          <Typography variant="h6" sx={titleStyles}>
            {DIALOG_CONSTANTS.TITLES.DETAILS}
          </Typography>
        </Box>

        {isReadOnly && (
          <Box sx={actionButtonsStyles}>
            <CustomTooltip title="Modifier" arrow placement="bottom">
              <IconButton
                onClick={handleModifyClick}
                sx={{ borderRadius: '50%' }}
              >
                <FontAwesome icon={faPencil} width={12} />
              </IconButton>
            </CustomTooltip>

            <CustomTooltip title="Notifier" arrow placement="bottom">
              <IconButton sx={{ borderRadius: '50%' }}>
                <FontAwesome icon={faBell} width={12} />
              </IconButton>
            </CustomTooltip>
          </Box>
        )}
        {!isReadOnly && (
          <Box sx={{ ...actionButtonsStyles, display: 'flex', alignItems: 'center' }}>
            <Typography 
              variant="caption" 
              color="text.secondary"
              sx={{ 
                backgroundColor: 'primary.lighter',
                color: 'primary.main',
                px: 1.5,
                py: 0.5,
                borderRadius: 1,
                fontSize: '0.75rem'
              }}
            >
              Mode édition
            </Typography>
          </Box>
        )}
      </Box>

      <Box sx={{ px: 3, mt: 4 }}>
        <form>
          <Grid container spacing={1.5} sx={{ '& .MuiGrid-item': { mb: 0.5 } }}>
            {getFieldsForEmployeeType(formData.employeeType || 'DRIVER').map((field) => (
              <Grid 
                item 
                xs={12} 
                sm={field.type === 'textarea' || field.name === 'comments' || field.name === 'files' ? 12 : 6}
                key={field.name}
                sx={{
                  ...centerFlexColumn,
                  '& .MuiFormControl-root': {
                    marginBottom: '6px',
                    ...(field.name === 'description' && {
                      '& .MuiInputBase-root': {
                        minHeight: '120px',
                        '& .MuiInputBase-input': {
                          height: 'auto !important',
                          minHeight: '100px !important',
                        }
                      }
                    })
                  },
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', mb: 0.5 }}>
                  <FontAwesome 
                    icon={field.icon} 
                    width={12}
                    color="primary.main" 
                    style={{ marginRight: '6px' }}
                  />
                  {renderField(field)}
                </Box>
              </Grid>
            ))}

            {!isReadOnly && (
              <Grid item xs={12}>
                <ActionButtons
                  onSave={handleSave}
                  onCancel={handleCancel}
                  mode="edit"
                />
              </Grid>
            )}
            {isReadOnly && (
              <Grid item xs={12}>
                <Box 
                  sx={{ 
                    display: 'flex', 
                    justifyContent: 'center', 
                    alignItems: 'center',
                    py: 1,
                    borderTop: 1,
                    borderColor: 'divider',
                    mt: 2
                  }}
                >
                  <Typography 
                    variant="caption"
                    sx={{ 
                      color: 'text.disabled',
                      fontSize: '0.75rem'
                    }}
                  >
                  </Typography>
                </Box>
              </Grid>
            )}
          </Grid>
        </form>
      </Box>
    </Drawer>
  );
} 