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, HEAD_CELLS } from '../utils/form-fields-contract';
import { _CONTRACT_CIRCUITS } from '@/shared/_mock/_contractCircuits';
import { CircuitStyledRow } from '../styles';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';



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}`,
  tarifAller: circuit.cost1,
  tarifRetour: circuit.cost2,
  tarifTotal: circuit.total,
}));

export default function ContratCircuitsTable() {
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<keyof ContratType | ''>('numero');

  const handleSort = (property: keyof ContratType) => {
    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="h5"
        sx={{
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Contrat circuits
      </Typography>
      <TableContainer>
        <Table sx={{ minWidth: 960, borderRadius: '12px' }}>
          <TableHead sx={{ backgroundColor: 'white' }}>
            <CircuitStyledRow>
              {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>
                <TableCell align="center" sx={{ px: { xs: 1, xl: 2 } }}>{contrat.tarifAller}</TableCell>
                <TableCell align="center" sx={{ px: { xs: 1, xl: 2 } }}>{contrat.tarifRetour}</TableCell>
                <TableCell align="center" sx={{ px: { xs: 1, xl: 2 } }}>{contrat.tarifTotal}</TableCell>
              </CircuitStyledRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
}

