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 } 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 } 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';

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) => {
    let doc = await useDocumentStore.getState().getDocumentById(docId, parseInt(driverId));
    if (doc?.downloadUrl) {
      setDocUrl(doc.downloadUrl);
      setOpen(true);
    }
  }


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

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateDebut':
      case 'dateFin':
        return formatDate(value, dateFormat.isoDate);
      case 'statut':
        return isTraiteTable ? (
          <StatusMenu
            value={value}
            options={_OPTION_DRIVER_ABSENCE}
            onChange={(newStatus) => handleStatusChange(row, newStatus, 'statut')}
            chipComponent={StatusChip}
            sx={{ width: '130px' }}
          />
        ) : (
          <StatusChip
            label={getLabel(value, _OPTION_DRIVER_ABSENCE)}
            status={value}
            theme={theme}
          />
        );
      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>
        );
      default:
        return 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="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>
  );
}
