import React, { useState } from 'react';
import {TableCell, useTheme } from '@mui/material';
import { IAppointment } from '@/shared/types/appointment';
import { formatDate } from '@/utils/format-time';
import { TableColumn } from '@/shared/types/common';
import TableActionColumn from '@/shared/components/table/table-action-column';
import SvgColor from '@/shared/components/svg-color';
import { StatusChip } from '../stytles';
import { getStatusColor } from '../../styles';
import { faBan } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import StatusSelect from '@/shared/components/dialog/statusSelect';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { APPOINTMENT_STATUS } from '../utils/constants';
import { DrawerStyledRow } from '@/shared/sections/contract/styles';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

const TOOLTIP_TITLES = {
  edit: "Modifier rendez-vous",
  active: "Rendez-vous actif",
  inactive: "Rendez-vous inactif",
};

type Props = {
  row: IAppointment;
  handleEdit?: (appointment: IAppointment) => void;
  handleCancel?: (appointment: IAppointment) => void;
  selected: boolean;
  handleView?: (appointment: IAppointment) => void;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
};

export default function AppointmentTableRow({
  row,
  handleEdit,
  handleCancel,
  handleView,
  columns,
}: Props) {
  const theme = useTheme();
  const [confirmCancelOpen, setConfirmCancelOpen] = useState(false);

  const handleStatusChange = (newStatus: string) => {
   
  };

  const renderCellContent = (columnId: string, row: IAppointment) => {
    switch (columnId) {
      case 'appointmentDate':
        return formatDate(row.date);
      case 'appointmentStatus':
        return (
          <StatusSelect
            value={row.status}
            options={APPOINTMENT_STATUS.map(option => ({
              ...option,
              color: typeof option.color === 'function' ? option.color(theme) : option.color,
              backgroundColor: typeof option.backgroundColor === 'function' ? 
                option.backgroundColor(theme) : option.backgroundColor,
            }))}
            onChange={handleStatusChange}
            chipComponent={StatusChip}
            fullWidth
          />
        );
      case 'appointmentType':
        return row.type;
      case 'driverFullName':
        return row.driverName;
      case 'medicalCenter':
        return row.medicalCenterName || '-';
      case 'doctorName':
        return row.doctorName || '-';
      case 'timeSlot':
        return row.time;
      default:
        return row[columnId as keyof IAppointment] || '-';
    }
  };
  

  const isEditable = row.status !== 'termine' && row.status !== 'annule';

  return (
    <>
   <DrawerStyledRow 
        onClick={() => handleView?.(row)} 
        style={{ cursor: 'pointer' }}
      >

        {columns.map((column: TableColumn, index: number) => (
          <TableCell
            key={column.id} 
            align={column.align}
            sx={{ 
              whiteSpace: 'nowrap',
              py: column.id === 'status' ? 0 : 1.8,
              pr: 0,
              ...(index === 0 && {
                position: 'relative',
              })
            }}
          >
            <ConditionalComponent isValid={index === 0}>
            <SvgColor
                src="/assets/icons/ic_border.svg"
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: -4,
                  height: '100%',
                  color: getStatusColor(row.status),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row)}
          </TableCell>
        ))}

        <TableCell 
          sx={{ px: 1, whiteSpace: 'nowrap', py: 0 }}
          onClick={(e) => e.stopPropagation()} 
        >
          <TableActionColumn
            handleEdit={() => handleEdit?.(row)}
            onToggle={(checked) => console.log('Toggle:', checked)}
            isActive={row.status !== 'annule'}
            tooltipTitles={TOOLTIP_TITLES}
            additionalActions={[
              {
                icon: <FontAwesomeIcon icon={faBan} size="sm" />,
                tooltip: "Annuler le rendez-vous",
                onClick: () => setConfirmCancelOpen(true),
              }
            ]}
          />
        </TableCell>
      </DrawerStyledRow>

      <ConfirmDialog
        open={confirmCancelOpen}
        title="Annulation du rendez-vous"
        content={`Êtes-vous sûr de vouloir annuler le rendez-vous avec ${row.driverName} prévu le ${formatDate(row.date)} à ${row.time} ?`}
        onConfirm={() => {
          handleCancel?.(row);
          setConfirmCancelOpen(false);
        }}
        onCancel={() => setConfirmCancelOpen(false)}
        confirmButtonText="Annuler le rendez-vous"
        cancelButtonText="Retour"
        confirmButtonColor="error"
      />
    </>
  );
}