import React, { useEffect, useState } from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { dateFormat, formatDate } from '@/utils/format-time';
import { IDriverAbsence } from '@/shared/types/driver-absence';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileAlt, faPenToSquare, faCircleCheck, faCircleXmark } from '@fortawesome/free-solid-svg-icons';
import { ActionsIconButton } from '@/shared/theme/css';
import { IconButton, Modal, Typography } from '@mui/material';
import { getLabel } from '@/shared/_mock';
import { _OPTION_DRIVER_ABSENCE, _OPTION_DRIVER_ABSENCE_UNPRO, _OPTION_TYPES_ABSENCE } from '@/shared/_mock/_absenceDriver';
import { _BINARY_Qst } from '@/shared/_mock/_trajets';
import { ContratStyledRow, getStatusColor, StatusChip } from '@/shared/sections/contract/styles';
import { AbsenceTableRowProps } from '@/shared/types/absence';
import StatusMenu from '@/shared/components/table/StatusMenu';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useDocumentStore } from '@/shared/api/stores/document-service/documentStore';
import { Box } from '@mui/system';
import CloseIcon from '@mui/icons-material/Close';
import { useDriverAbsenceStore } from '@/shared/api/stores/driverAbsenceStore';
import { DriverAbsenceStatut } from '@/shared/api/stores/driverAbsenceStore';
import { DOCUMENT_SERVICE_BASE_URL } from '@/config-global';

export default function AbsenceDriverTableRow({
  row,
  dense,
  handleEdit,
  handleDetails,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
  isTraiteTable,
}: AbsenceTableRowProps<IDriverAbsence>) {
  const [open, setOpen] = useState(false);
  const [docUrl, setDocUrl] = useState('');
  const theme = useTheme();
  const handleStatusChange = (row: IDriverAbsence, newStatus: string, field: keyof IDriverAbsence) => {
    if (onStatusChange) {
      onStatusChange(row, newStatus, field);
    }
  };

  const handleDocumentOpen = async (driverId: string, docId: number) => {
      setDocUrl(`${DOCUMENT_SERVICE_BASE_URL}/${driverId}/rapport-RAP-2023-001.pdf`);
      setOpen(true);
  }


  const handleClose = () => {
    setOpen(false);
  };

  const renderCellContent = (columnId: string, value: any) => {
    const display = (v: any) => (v === null || v === undefined || v === '' ? '--' : v);
    switch (columnId) {
      case 'dateDebut':
      case 'dateFin':
        return value ? formatDate(value, dateFormat.isoDate) : '--';
      case 'statut':
        return (
          <>
            <ConditionalComponent isValid={!!isTraiteTable}>
              <StatusMenu
                value={value}
                options={_OPTION_DRIVER_ABSENCE_UNPRO}
                onChange={(newStatus) => handleStatusChange(row, newStatus, 'statut')}
                chipComponent={StatusChip}
                sx={{ width: '130px' }}
              />
            </ConditionalComponent>
            <ConditionalComponent isValid={!isTraiteTable}>
              <StatusChip
                label={getLabel(value, _OPTION_DRIVER_ABSENCE)}
                status={value}
                theme={theme}
              />
            </ConditionalComponent>
          </>
        );
      case 'chauffeurAffecte':
        return (
          <StatusChip
            label={getLabel(value, _BINARY_Qst)}
            status={value}
            theme={theme}
            size="small"
          />
        );
      case 'justificatif':
        return (
          <CustomTooltip title="Document justificatif" arrow>
            <IconButton sx={{ ml: 1, ...ActionsIconButton }} onClick={() => handleDocumentOpen(row.driver?.id!, row.supportingDocumentId!)}>
              <FontAwesome icon={faFileAlt} width={18} />
            </IconButton>
          </CustomTooltip>
        );
      case 'typeAbsence':
        return display(getLabel(value, _OPTION_TYPES_ABSENCE));
      case 'validatedByName':
        return display(value);
      case 'authorizedByName':
        return display(value);
      case 'validePar':
        return !isTraiteTable ? display(value) : '--';
      default:
        return display(value);
    }
  };

  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}>
      {columns.map((column: any, index: number) => (
        <TableCell
          onDoubleClick={() => handleDetails(row)}
          key={column.id}
          align={column.align}
          sx={{
            whiteSpace: 'nowrap',
            ...(index === 0 && {
              position: 'relative',
            }),
            py: column.id === 'status' ? 0.2 : dense ? 0 : 1
          }}
        >
          <ConditionalComponent isValid={index === 0}>
            <SvgColor
              src="/assets/icons/ic_border.svg"
              sx={{
                position: 'absolute',
                top: 0,
                left: -4,
                height: '100%',
                color: getStatusColor(row.statut),
              }}
            />
          </ConditionalComponent>
          {renderCellContent(column.id, row[column.id as keyof IDriverAbsence])}
        </TableCell>
      ))}
      <ConditionalComponent isValid={!!isTraiteTable}>
        <TableCell align="center" sx={{ px: 1, whiteSpace: 'nowrap' }}>
          <CustomTooltip title="Valider l'absence" arrow>
            <IconButton 
              onClick={() => handleStatusChange(row, DriverAbsenceStatut.ACCEPTED, 'statut')} 
              size="small" 
              sx={{
                ...ActionsIconButton,
                color: 'success.main',
                '&:hover': {
                  backgroundColor: 'success.light',
                  color: 'success.dark'
                }
              }}
            >
              <FontAwesome icon={faCircleCheck} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Rejeter l'absence" arrow>
            <IconButton 
              onClick={() => handleStatusChange(row, DriverAbsenceStatut.REJECTED, 'statut')} 
              size="small" 
              sx={{
                ...ActionsIconButton,
                color: 'error.main',
                '&:hover': {
                  backgroundColor: 'error.light',
                  color: 'error.dark'
                }
              }}
            >
              <FontAwesome icon={faCircleXmark} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Modifier l'absence" arrow>
            <IconButton onClick={() => handleEdit(row)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faPenToSquare} width={16} />
            </IconButton>
          </CustomTooltip>
        </TableCell>
      </ConditionalComponent>

      <Modal open={open} onClose={handleClose}>
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            backgroundColor: 'white',
            padding: 2,
            borderRadius: 2,
            boxShadow: 24,
            width: '80%',
            maxHeight: '80vh',
            overflowY: 'auto',
          }}
        >
          <IconButton
            onClick={handleClose}
            sx={{
              position: 'absolute',
              top: 8,
              right: 8,
              color: theme.palette.grey[500],
            }}
          >
            <CloseIcon />
          </IconButton>
          <Typography variant="h6" gutterBottom>
            Document Preview
          </Typography>
          <iframe
            src={docUrl}
            width="100%"
            height="500px"
            style={{ border: 'none' }}
            title="Document Preview"
          />
        </Box>
      </Modal>
    </ContratStyledRow>
  );
}
