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 { _CONTRACT_CIRCUITS } from '@/shared/_mock/_contractCircuits';
import { CircuitStyledRow } from '@/shared/sections/contract/styles';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';
import { _DRIVER_CIRCUIT } from '@/shared/_mock/_drivers';

type TransformedCircuit = {
  numero: string;
  driverName: string;
  code: string;
  circuitName: string;
  departureTrip: string;
  returnTrip: string;
};

const SALARIE_CIRCUIT_HEAD_CELLS: {
  id: keyof TransformedCircuit;
  label: string;
  align?: 'left' | 'center';
}[] = [
  { id: 'numero', label: 'N°', align: 'center' },
  { id: 'driverName', label: 'Nom du chauffeur', align: 'left' },
  { id: 'code', label: 'Code Circuit', align: 'center' },
  { id: 'circuitName', label: 'Nom', align: 'left' },
  { id: 'departureTrip', label: 'Trajet Aller', align: 'left' },
  { id: 'returnTrip', label: 'Trajet Retour', align: 'left' },
];
const transformedData = _CONTRACT_CIRCUITS.map((circuit) => {
  const driver = _DRIVER_CIRCUIT.find((driver) => driver.circuitCode === circuit.code);

  return {
    numero: circuit.id,
    driverName: driver ? driver.fullName : 'Non attribue',
    code: circuit.code,
    circuitName: `${circuit.school}|${circuit.session}`,
    departureTrip: `${circuit.time1}|${circuit.route1}`,
    returnTrip: `${circuit.time2}|${circuit.route2}`,
  };
});
type Props = {
  condensed?: boolean;
};

export default function RoadMapHistoryTable({ condensed = false }: Props) {
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<keyof TransformedCircuit | ''>('numero');

  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={{ bgcolor: 'white', marginTop: '50px' }}></Box>
      <Typography
        variant="h4"
        sx={{
          bgcolor: 'white',
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      ></Typography>
      <Typography
        variant="h5"
        sx={{
          textAlign: 'center',
          my: 2,
          mb: 3,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Trajets assignés
      </Typography>
      <TableContainer>
        <Table sx={{ minWidth: 400, 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: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 0 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                  }}
                >
                  {contrat.numero}
                </TableCell>
                <TableCell
                  align="center"
                  sx={{
                    py: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 1 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                  }}
                >
                  {contrat.driverName}
                </TableCell>
                <TableCell
                  align="center"
                  sx={{
                    py: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 1 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                  }}
                >
                  {contrat.code}
                </TableCell>
                <TableCell
                  align="center"
                  sx={{
                    py: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 1 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {renderCellContent(contrat.circuitName, 'school')}
                </TableCell>
                <TableCell
                  sx={{
                    py: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 1 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                  }}
                >
                  {renderCellContent(contrat.departureTrip, 'time')}
                </TableCell>
                <TableCell
                  sx={{
                    py: condensed ? 0.5 : 1.5,
                    px: { xs: 0.5, xl: condensed ? 1 : 2 },
                    fontSize: condensed ? '0.75rem' : '0.875rem',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {renderCellContent(contrat.returnTrip, 'route')}
                </TableCell>
              </CircuitStyledRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );
}
