import React, { useState, useMemo } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  Typography,
  Box,
} from '@mui/material';
import { faSun, faMoon } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import SvgColor from '@/shared/components/svg-color';
import { ContratType } from '@/shared/sections/contract/utils/form-fields-contract';
import { _CONTRACT_CIRCUITS } from '@/shared/_mock/_contractCircuits';
import { CircuitStyledRow } from '@/shared/sections/contract/styles';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';

// Add this type definition for our transformed data
type TransformedCircuit = {
  numero: string;
  code: string;
  nom: string;
  trajetAller: string;
  trajetRetour: string;
};

// Update the head cells type
const SALARIE_CIRCUIT_HEAD_CELLS: { id: keyof TransformedCircuit; label: string; align?: 'left' | 'center' }[] = [
  { id: 'numero', label: 'N°', align: 'center' },
  { id: 'code', label: 'Code', align: 'center' },
  { id: 'nom', label: 'Nom', align: 'left' },
  { id: 'trajetAller', label: 'Trajet Aller', align: 'left' },
  { id: 'trajetRetour', label: 'Trajet Retour', align: 'left' },
];

const transformedData = _CONTRACT_CIRCUITS.map((circuit) => ({
  numero: circuit.id,
  code: circuit.code,
  nom: `${circuit.school}|${circuit.session}`,
  trajetAller: `${circuit.time1}|${circuit.route1}`,
  trajetRetour: `${circuit.time2}|${circuit.route2}`,
}));

export default function SalarieCircuitsTable() {
  // Update the orderBy type to use TransformedCircuit
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<keyof TransformedCircuit | ''>('numero');

  // Update the handleSort function
  const handleSort = (property: keyof TransformedCircuit) => {
    setOrder((prev) => (orderBy === property && prev === 'asc' ? 'desc' : 'asc'));
    setOrderBy(property);
  };

  const sortedData = useMemo(() => 
    [...transformedData].sort((a, b) => {
      if (orderBy) {
        const aValue = a[orderBy];
        const bValue = b[orderBy];
        return (aValue < bValue ? -1 : 1) * (order === 'asc' ? 1 : -1);
      }
      return 0;
    }),
    [order, orderBy]
  );

  const renderCellContent = (content: string, iconType: 'school' | 'time' | 'route') => (
    <Box sx={{ display: 'flex', flexDirection: 'column', whiteSpace: 'nowrap' }}>
      {content.split('|').map((part, index) => (
        <Box key={index} sx={{ display: 'flex', alignItems: 'center' }}>
          {iconType === 'school' && index === 0 ? (
            <SvgColor
              src="/assets/icons/menu/ic_exploitation.svg"
              sx={{ width: 15, color: 'primary.main', mr: 1 }}
            />
          ):<></>}
          {iconType === 'school' && index === 1 ? (
            <FontAwesome
              icon={part === 'Matin' ? faSun : faMoon}
              color="primary.main"
              width={15}
              sx={{ mr: 1 }}
            />
          ):<></>}
          {(iconType === 'time' || iconType === 'route') ? (
            <SvgColor
              src={`/assets/icons/${index === 0 ? 'ic_clock' : 'menu/ic_exploitation'}.svg`}
              sx={{ width: 15, color: 'primary.main', mr: 1 }}
            />
          ):<></>}
          {part}
        </Box>
      ))}
    </Box>
  );

  return (
    <Box sx={{ width: '100%', mb: '20px' }}>
      <Typography
        variant="h6"
        sx={{
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Circuits assignés
      </Typography>
      <TableContainer>
        <Table sx={{ minWidth: 960, borderRadius: '12px' }}>
          <TableHead sx={{ backgroundColor: 'white' }}>
            <CircuitStyledRow>
              {SALARIE_CIRCUIT_HEAD_CELLS.map((headCell) => (
                <TableCell
                  sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}
                  key={headCell.id}
                  align={headCell.align}
                  sortDirection={orderBy === headCell.id ? order : false}
                >
                  <CustomTableSortLabel
                    active={orderBy === headCell.id}
                    direction={orderBy === headCell.id ? order : 'asc'}
                    orderBy={orderBy}
                    order={order}
                    onSort={() => handleSort(headCell.id)}
                  >
                    {headCell.label}
                  </CustomTableSortLabel>
                </TableCell>
              ))}
            </CircuitStyledRow>
          </TableHead>
          <TableBody>
            {sortedData.map((contrat) => (
              <CircuitStyledRow key={contrat.numero}>
                <TableCell align="center" sx={{ py: 0, px: { xs: 1, xl: 2 } }}>{contrat.numero}</TableCell>
                <TableCell align="center" sx={{ py: 0, px: { xs: 1, xl: 2 } }}>{contrat.code}</TableCell>
                <TableCell align="center" sx={{ py: 0, px: { xs: 1, xl: 2 }, whiteSpace: 'nowrap' }}>
                  {renderCellContent(contrat.nom, 'school')}
                </TableCell>
                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 }, ligne: 'none' }}>
                  {renderCellContent(contrat.trajetAller, 'time')}
                </TableCell>
                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 }, whiteSpace: 'nowrap' }}>
                  {renderCellContent(contrat.trajetRetour, 'route')}
                </TableCell>
              </CircuitStyledRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
} 