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 { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import { EmployeeEvent, EVENT_COLORS } from '@/shared/_mock/_employeeEvents';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import FontAwesome from '@/shared/components/fontawesome';
import { pxToRem } from '@/shared/theme/typography';
import FormContainer from '@/layouts/form/form-container';
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 {
  EVENT_DETAIL_FIELDS,
  STATUS_OPTIONS,
  EVENT_TYPES,
  DIALOG_CONSTANTS
} from '../constants/event.constants';
import {
  drawerStyles,
  headerStyles,
  closeButtonStyles,
  titleStyles,
  actionButtonsStyles,
  selectStyles,
  textareaStyles
} from '../styles/event-details-dialog.styles';

const getFieldValue = (field: IFormField, formData: CalendarEvent, status: EventStatus) => {
  switch (field.name) {
    case 'date':
      return format(new Date(formData.start), 'dd MMMM yyyy', { locale: fr });
    case 'time':
      return format(new Date(formData.start), 'HH:mm');
    case 'employeeName':
      return formData.employeeName || '';
    case 'location':
      return formData.location || '';
    case 'type':
      return formData.type;
    case 'status':
      return status;
    case 'description':
      return formData.description || '';
    case 'files':
      return formData.files ? `${formData.files.length} document(s)` : 'Aucun document';
    case 'comments':
      return formData.comments || '';
    default:
      return '';
  }
};

export default function EventDetailsDialog({ 
  open, 
  onClose,
  event,
  onEventUpdate 
}: DialogProps) {
  const [mode, setMode] = useState<ModeType>('view');
  const [formData, setFormData] = useState<CalendarEvent | null>(null);
  const [status, setStatus] = useState<EventStatus>('pending');

  useEffect(() => {
    if (event) {
      setFormData(event);
      const newStatus = (event.status || 'pending') as EventStatus;
      setStatus(newStatus);
    }
  }, [event]);

  const isReadOnly = mode === 'view';

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

  const handleSave = () => {
    if (formData) {
      onEventUpdate?.({
        ...formData,
        status,
        files: formData.files,
        comments: formData.comments
      });
      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: 'text',
            icon: faClock
          }}
          value={getFieldValue(field, formData!, status)}
          onChange={handleFieldChange}
          isReadOnly={true}
          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={(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={(value) => {
              const newStatus = value as EventStatus;
              setStatus(newStatus);
            }}
            isReadOnly={isReadOnly}
            isDrawerElement
          />
        );

      case 'description':
      case 'comments':
        return (
          <FormField
            field={{
              name: field.name,
              label: field.label,
              type: 'textarea',
              icon: field.icon
            }}
            value={getFieldValue(field, formData!, status)}
            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 } }}>
            {EVENT_DETAIL_FIELDS.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>
  );
} 