import { useEffect, useState } from 'react';
import { Box, Typography, Button, Stack, Grid, ClickAwayListener } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { faCar, faUser, faIdBadge, faBuilding, faGasPump } from '@fortawesome/free-solid-svg-icons';
import { pxToRem } from '@/shared/theme/typography';
import FontAwesome from '@/shared/components/fontawesome';

import dayjs, { Dayjs } from 'dayjs';
import { StaticDatePicker } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import 'dayjs/locale/fr';
import { useWorkedDayStore } from '@/shared/api/stores/workedDayStore';
import { SubmittedRoadMapDTO } from '@/shared/types/roadMap';
import { WorkedDayDTO } from '@/shared/types/driver-roadmap';

type Props = {
  handleOnClick: () => void;
  activeTabData: SubmittedRoadMapDTO
  setWorkedDay: (workedDay: WorkedDayDTO) => void;
  setSelectedDate: (date: Dayjs) => void;
};




export default function UserInformationCard({ handleOnClick,activeTabData , setWorkedDay,setSelectedDate}: Props) {
  const today = dayjs();
  const startOfMonth = today.startOf('month');
  const endOfMonth = today.endOf('month');
  const [selectedDate, setLocalSelectedDate] = useState<Dayjs | null>(today);

  const { driverInfo, getDriverInfos } = useWorkedDayStore();
  const { getWorkedDay } = useWorkedDayStore();

  useEffect(() => {
    if (selectedDate) {
      setSelectedDate(selectedDate); 
    }
  }, [selectedDate, setSelectedDate]);


  useEffect(() => {
    const fetchData = async () => {
      if (activeTabData?.driverId) {
        const driverId = Number(activeTabData.driverId);
        if (!isNaN(driverId)) {
          try {
            await getDriverInfos(driverId);
          } catch (error) {
            console.error("Error fetching driver details:", error);
          }
        } else {
          console.warn("Invalid DriverId:", activeTabData.driverId);
        }
      } else {
        console.warn("No ID found in searchParams");
      }
    };
  
    fetchData();
  }, [activeTabData?.driverId]);

  const mockData = {
    departement: 'Département Soleil',
    adresse: '75. Agence Soleil Avenue de la somme',
    prenom: 'Anna',
    nom: 'Leblanc',
    carteCarburant: 'XX07905968',
    immatriculation: 'GA 689479',
    licence: '689479',
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="fr">
      <Box
        sx={{
          borderRadius: 5,
          display: 'flex',
          flexDirection: 'row',
        }}
      >
        <Box
          sx={{
            p: 1,
            borderRadius: 5,
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            flex: 2,
          }}
        >
          <Box sx={{ bgcolor: 'white', p: 3, borderRadius: 2, boxShadow: 1 , height: '100%'}}>
            <Typography
              sx={{
                textAlign: 'center',
                fontSize: pxToRem(30),
                color: 'primary.main',
                fontWeight: (theme) => theme.typography.fontWeightBold,
                mb: 2,
              }}
            >
              {driverInfo?.departmentName || 'Département'}
            </Typography>

            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faUser} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>Prénom :&nbsp;{driverInfo?.firstName}</Typography>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faCar} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>Immatriculation : {driverInfo?.vehiculeRegistration}</Typography>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faUser} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>Nom :&nbsp;{driverInfo?.lastName}</Typography>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faGasPump} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>Carte carburant :&nbsp;{driverInfo?.fuelCardNumber}</Typography>
                  </Grid>
                </Grid>
              </Grid>

              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faIdBadge} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>
                      Num copie de conforme de la licence : {driverInfo?.drivingLicenseName}
                    </Typography>
                  </Grid>
                </Grid>
              </Grid>
              <Grid item xs={12}>
                <Grid container direction="row" alignItems="center" spacing={1}>
                  <Grid item>
                    <FontAwesome icon={faBuilding} color="primary.main" width={16} />
                  </Grid>
                  <Grid item>
                    <Typography>Adresse :&nbsp;{driverInfo?.addresses?.[0]?.street}</Typography>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>
          </Box>
        </Box>

        <Box
          sx={{
            flex: 1,
            bgcolor: 'white',
            pt: 3,
            pb: 3,
            m: 1,
            borderRadius: 2,
            boxShadow: 1,
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            gap: 0,
            position: 'relative',
          }}
        >
          <Grid container gap={0} spacing={0}>
            <Grid item xs={12} sm={12} md={6}>
              <Box sx={{ position: 'relative' }}>
                <Typography variant="body1" color="primary.main" sx={{ mb: 1, pl: 2, pt: 1 }}>
                  Choisir une date
                </Typography>
              </Box>
            </Grid>
            <Grid item xs={12} sm={12} md={6}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'end',
                  justifyContent: 'space-around',
                  cursor: 'pointer',
                  ml: 2,
                }}
                onClick={() => handleOnClick()}
              >
                <Button variant="contained" color="primary">
                  Liste des trajets
                </Button>
              </Box>
            </Grid>
          </Grid>
          <StaticDatePicker
            value={selectedDate}
            onChange={(newDate) => setLocalSelectedDate(newDate)}
            minDate={startOfMonth}
            maxDate={endOfMonth}
            displayStaticWrapperAs="desktop"
            showDaysOutsideCurrentMonth={false}
            views={['day']}
            openTo="day"
            shouldDisableDate={(date) =>
              date.isBefore(startOfMonth, 'day') || date.isAfter(endOfMonth, 'day')
            }
            sx={{
              '& .MuiPickersArrowSwitcher-root': {
                display: 'none',
              },
              '& .MuiDateCalendar-root': {
                maxHeight: '280px',
              },
              '& .MuiPickersCalendarHeader-root ': {
                marginTop: '-10px',
              },
            }}
          />
          <Box display="flex" justifyContent="space-between" alignItems="center">
            <ConditionalComponent isValid={!!selectedDate}>
              <Typography
                variant="h6"
                sx={{
                  color: 'primary.main',
                  fontWeight: (theme) => theme.typography.fontWeightBold,
                  textTransform: 'capitalize',
                  pl: 2,
                  mb: 2,
                }}
                gutterBottom
              >
                {selectedDate?.locale('fr').format('dddd D MMMM YYYY')}
              </Typography>
            </ConditionalComponent>
          </Box>

          <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ pr: 2 }}>
            <Button variant="outlined" color="primary">
              Annuler
            </Button>
            <Button
                variant="contained"
                color="primary"
                onClick={async () => {
                  if (!selectedDate || !activeTabData?.id) return;

                  const formattedDate = selectedDate.format('YYYY-MM-DD');
                  try {
                    const id = Number(activeTabData.id);
                    const res = await getWorkedDay(id, formattedDate);
                    setWorkedDay(res);
                    setSelectedDate(selectedDate); 
                  } catch (err) {
                    console.error("Erreur récupération WorkedDay :", err);
                  }
                }}
              >
                Valider
              </Button>

          </Stack>
        </Box>
      </Box>
    </LocalizationProvider>
  );
}
