'use client';

import React, { useState } from 'react';
import { TableCell, Chip, Box, IconButton } from '@mui/material';
import { type IRevision, StatutCT, UserType } from '@/shared/types/flottes/revision';
import { type TableColumn } from '@/shared/types/common';
import { ContratStyledRow, StatusChip } from '@/shared/sections/contract/styles';
import { formatDate, dateFormat } from '@/utils/format-time';
import SvgColor from '@/shared/components/svg-color';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileAlt, faHistory, faPenToSquare, faCopy, faToggleOn, faToggleOff } from '@fortawesome/free-solid-svg-icons';
import { getRevisionStatut, getRevisionStatusColor, STATUS_COLORS, REVISION_STATUS_OPTIONS } from '@/shared/_mock/flottes/_revision';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { ActionsIconButton } from '@/shared/theme/css';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { useTheme } from '@mui/material/styles';

interface Props {
  row: IRevision;
  handleEditRevision: (revision: IRevision) => void;
  handleDetailsRevision: (revision: IRevision) => void;
  handleCopyRevision?: (revision: IRevision) => void;
  handleViewHistory?: (revision: IRevision) => void;
  selected: boolean;
  onSelectRow: () => void;
  columns: TableColumn[];
  onStatusChange?: (revision: IRevision, newStatus: boolean) => void;
}

export default function RevisionTableRow({
  row,
  handleEditRevision,
  handleDetailsRevision,
  handleCopyRevision,
  handleViewHistory,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
}: Props) {
  const theme = useTheme();
  const [historyModalOpen, setHistoryModalOpen] = useState(false);

  const handleHistoryClick = () => {
    if (handleViewHistory) {
      handleViewHistory(row);
    } else {
      setHistoryModalOpen(true);
    }
  };

  const handleStatusMenuChange = (newStatus: string) => {
    // For now, just log the change - in real app this would call an API
    console.log('Status changed to:', newStatus, 'for revision:', row.id);
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'immatriculation':
        return (
          <Box sx={{ minWidth: '120px', fontWeight: 500 }}>
            {value}
          </Box>
        );

      case 'type':
        return (
          <Chip
            label={value}
            size="small"
            color={value === UserType.CHAUFFEUR ? 'primary' : 'secondary'}
            sx={{ fontWeight: 500, minWidth: '85px' }}
          />
        );

      case 'personne':
        return (
          <Box
            sx={{
              minWidth: '140px',
              maxWidth: '140px',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
            title={value}
          >
            {value}
          </Box>
        );

      case 'dateRevision':
      case 'dateCT':
        return (
          <Box sx={{ minWidth: '100px' }}>
            {value ? formatDate(value, dateFormat.isoDate) : '-'}
          </Box>
        );

      case 'derniereMiseAJour':
        return (
          <Box sx={{ minWidth: '110px' }}>
            {value ? formatDate(value, dateFormat.isoDate) : '-'}
          </Box>
        );

      case 'statutCT':
        // Use StatusMenu like in absence system
        const RevisionStatusChip = (props: any) => (
          <StatusChip 
            {...props}
            status={getRevisionStatut(props.status)}
            theme={theme}
            sx={{
              backgroundColor: getRevisionStatusColor(props.status),
              color: 'white',
              fontWeight: 500,
              minWidth: '90px',
            }}
          />
        );

        return (
          <Box sx={{ minWidth: '130px' }}>
            <StatusMenu
              value={getRevisionStatut(value as StatutCT)}
              options={REVISION_STATUS_OPTIONS.map(opt => ({
                value: opt.value,
                label: opt.label
              }))}
              onChange={handleStatusMenuChange}
              chipComponent={RevisionStatusChip}
              sx={{ width: '130px' }}
            />
          </Box>
        );

      case 'kilometrage':
        return (
          <Box sx={{ maxWidth: '10px', textAlign: 'center' }}>
            {value ? `${value.toLocaleString()} km` : '-'}
          </Box>
        );

      case 'copieCT':
        return value ? (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: '120px' }}>
            <FontAwesome icon={faFileAlt} width={16} />
            <span>CT disponible</span>
          </Box>
        ) : (
          <span style={{ color: '#999' }}>Aucun fichier</span>
        );

      case 'observation':
      case 'revisions':
      case 'adresse':
        return value ? (
          <Box
            sx={{
              maxWidth: 150,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
            title={value}
          >
            {value}
          </Box>
        ) : (
          '-'
        );

      default:
        return value || '-';
    }
  };

  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}>
      {columns.map((column: any, index: number) => (
        <TableCell
          onDoubleClick={() => handleDetailsRevision(row)}
          key={column.id}
          align={column.align || 'left'}
          sx={{
            whiteSpace: 'nowrap',
            py: column.id === 'statutCT' ? 0.2 : 'inherit',
            ...(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: getRevisionStatusColor(row.statutCT),
              }}
            />
          </ConditionalComponent>
          {renderCellContent(column.id, row[column.id as keyof IRevision])}
        </TableCell>
      ))}

      {/* Actions column - always show after main columns */}
      <TableCell 
        align="center" 
        sx={{ 
          px: 1, 
          whiteSpace: 'nowrap',
          minWidth: '140px',
          maxWidth: '140px',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.3, justifyContent: 'center' }}>
          <CustomTooltip title="Modifier révision" arrow>
            <IconButton onClick={() => handleEditRevision(row)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faPenToSquare} width={14} />
            </IconButton>
          </CustomTooltip>

          {handleCopyRevision && (
            <CustomTooltip title="Copier révision" arrow>
              <IconButton onClick={() => handleCopyRevision(row)} size="small" sx={ActionsIconButton}>
                <FontAwesome icon={faCopy} width={14} />
              </IconButton>
            </CustomTooltip>
          )}

          <CustomTooltip title="Voir l'historique" arrow>
            <IconButton onClick={handleHistoryClick} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faHistory} width={14} />
            </IconButton>
          </CustomTooltip>

          <CustomTooltip title={row.isActive ? "Archiver" : "Restaurer"} arrow>
            <IconButton 
              onClick={() => onStatusChange?.(row, !row.isActive)} 
              size="small" 
              sx={{
                ...ActionsIconButton,
                color: row.isActive ? '#36B37E' : '#FF3434',
              }}
            >
              <FontAwesome icon={row.isActive ? faToggleOn : faToggleOff} width={14} />
            </IconButton>
          </CustomTooltip>
        </Box>
      </TableCell>
    </ContratStyledRow>
  );
} 