'use client';

import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  CircularProgress,
  Alert,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import { useTrips } from '../hooks/use-trips';
import type { TripShortDTO } from '@/shared/types/trip';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

const TripsStyledRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  '&:last-child td, &:last-child th': {
    border: 0,
  },
}));

const SALARIE_TRIPS_HEAD_CELLS = [
  { id: 'circuitCode', label: 'Code Circuit', align: 'left' as const },
  { id: 'tripTitled', label: 'Intitulé du trajet', align: 'left' as const },
  { id: 'circuitTitled', label: 'Nom du circuit', align: 'left' as const },
];

interface SalarieTripsTableProps {
  driverId?: number;
}

export default function SalarieTripsTable({ driverId }: SalarieTripsTableProps) {
  const { loading, trips, error, getShortTripsByDriver, clearTrips } = useTrips();
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<string>('circuitCode');

  useEffect(() => {
    if (driverId) {
      getShortTripsByDriver(driverId);
    } else {
      clearTrips();
    }
  }, [driverId, getShortTripsByDriver, clearTrips]);

  const handleSort = (property: string) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const sortedTrips = React.useMemo(() => {
    return [...trips].sort((a, b) => {
      const aValue = (a as any)[orderBy];
      const bValue = (b as any)[orderBy];
      
      if (order === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      } else {
        return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
      }
    });
  }, [trips, order, orderBy]);

  const renderTripTitle = (trip: TripShortDTO) => {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
        {/* Trip Title with schedule */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 8,
              height: 8,
              borderRadius: '50%',
              backgroundColor: 'primary.main',
            }}
          />
          <Typography variant="body2" fontWeight="medium">
            {trip.tripTitled}
          </Typography>
        </Box>

        {/* Period of Day */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 8,
              height: 8,
              borderRadius: '50%',
              backgroundColor: trip.periodOfDay === 'MORNING' ? '#FFD700' : 
                              trip.periodOfDay === 'EVENING' ? '#4A90E2' : 
                              trip.periodOfDay === 'MIDDAY' ? '#FF6B35' : '#6B46C1',
            }}
          />
          <Typography variant="body2">
            {trip.periodOfDay === 'MORNING' ? 'Matin' : 
             trip.periodOfDay === 'EVENING' ? 'Soir' : 
             trip.periodOfDay === 'MIDDAY' ? 'Midi' : 'Soirée'}
          </Typography>
        </Box>

        {/* Trip Direction */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 8,
              height: 8,
              borderRadius: '50%',
              backgroundColor: trip.sensTrip === 'DEPARTURE' ? '#28a745' : '#dc3545',
            }}
          />
          <Typography variant="body2">
            {trip.sensTrip === 'DEPARTURE' ? 'Aller' : 'Retour'}
          </Typography>
        </Box>

        {/* Trip Type */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 8,
              height: 8,
              borderRadius: '50%',
              backgroundColor: '#6c757d',
            }}
          />
          <Typography variant="body2">
            {trip.tripType}
          </Typography>
        </Box>
      </Box>
    );
  };

  return (
    <Box sx={{ width: '100%', mb: '20px' }}>
      <Typography
        variant="h6"
        sx={{
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Trajets assignés
      </Typography>

      <ConditionalComponent isValid={loading}>
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
          <CircularProgress />
        </Box>
      </ConditionalComponent>

      <ConditionalComponent isValid={!!error && !loading}>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      </ConditionalComponent>

      <ConditionalComponent isValid={!driverId && !loading && !error}>
        <Box sx={{ 
          display: 'flex', 
          flexDirection: 'column', 
          alignItems: 'center', 
          justifyContent: 'center', 
          py: 4,
          textAlign: 'center'
        }}>
          <Box sx={{ 
            width: 64, 
            height: 64, 
            borderRadius: '50%', 
            backgroundColor: 'primary.50', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            mb: 2
          }}>
            <Typography variant="h4" color="primary.main">
              👤
            </Typography>
          </Box>
          <Typography variant="h6" color="text.secondary" gutterBottom>
            Sélectionnez un chauffeur
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Sauvegardez le chauffeur pour voir ses trajets assignés
          </Typography>
        </Box>
      </ConditionalComponent>

      <ConditionalComponent isValid={!!driverId && !loading && !error && trips.length === 0}>
        <Box sx={{ 
          display: 'flex', 
          flexDirection: 'column', 
          alignItems: 'center', 
          justifyContent: 'center', 
          py: 4,
          textAlign: 'center'
        }}>
          <Box sx={{ 
            width: 64, 
            height: 64, 
            borderRadius: '50%', 
            backgroundColor: 'grey.100', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            mb: 2
          }}>
            <Typography variant="h4" color="grey.400">
              🚌
            </Typography>
          </Box>
          <Typography variant="h6" color="text.secondary" gutterBottom>
            Aucun trajet assigné
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Ce chauffeur n&apos;a pas encore de trajets assignés
          </Typography>
        </Box>
      </ConditionalComponent>

      <ConditionalComponent isValid={!!driverId && !loading && !error && trips.length > 0}>
        <TableContainer component={Paper} sx={{ borderRadius: '12px' }}>
          <Table sx={{ minWidth: 960 }}>
            <TableHead sx={{ backgroundColor: 'white' }}>
              <TripsStyledRow>
                {SALARIE_TRIPS_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}
                  >
                    <Typography
                      variant="subtitle2"
                      sx={{
                        fontWeight: 'bold',
                        cursor: 'pointer',
                        '&:hover': { color: 'primary.main' },
                      }}
                      onClick={() => handleSort(headCell.id)}
                    >
                      {headCell.label}
                      <ConditionalComponent isValid={orderBy === headCell.id}>
                        <span style={{ marginLeft: 4 }}>
                          {order === 'asc' ? '↑' : '↓'}
                        </span>
                      </ConditionalComponent>
                    </Typography>
                  </TableCell>
                ))}
              </TripsStyledRow>
            </TableHead>
            <TableBody>
              {sortedTrips.map((trip, index) => (
                <TripsStyledRow key={trip.id || index}>
                  <TableCell sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}>
                    <Typography variant="body2" fontWeight="medium">
                      {trip.circuitCode}
                    </Typography>
                  </TableCell>
                  <TableCell sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}>
                    {renderTripTitle(trip)}
                  </TableCell>
                  <TableCell sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}>
                    <Typography variant="body2">
                      {trip.circuitTitled}
                    </Typography>
                  </TableCell>
                </TripsStyledRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </ConditionalComponent>
    </Box>
  );
}
