import { useEffect, useMemo, 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 { PickersDay, PickersDayProps, 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;
  onChoose?: (dateString: string) => void;
  activeTabData: SubmittedRoadMapDTO;
  setWorkedDay: (workedDay: WorkedDayDTO) => void;
  setSelectedDate: (date: Dayjs) => void;
  initialDate?: string | Dayjs;
  workedDaysDates?: string[];
};

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

  const { driverInfo, getDriverInfos } = useWorkedDayStore();
  const { getWorkedDay } = useWorkedDayStore();
  const [isLoading, setIsLoading] = useState(false);
  useEffect(() => {
    const shouldFetch = !!selectedDate && selectedDate.isSame(initialSelectedDate, 'day');

    const fetchWorkedDay = async () => {
      if (!shouldFetch || !activeTabData?.id) return;

      setIsLoading(true);
      const formattedDate = selectedDate.format('YYYY-MM-DD');

      try {
        const id = Number(activeTabData.id);
        const res = await getWorkedDay(id, formattedDate);
        setWorkedDay(res);
      } catch (err) {
        console.error('Erreur récupération automatique du WorkedDay :', err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchWorkedDay();
  }, [selectedDate, initialSelectedDate, activeTabData?.id]);

  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',
  };
  const workedDaysSet = new Set(workedDaysDates);

  const CustomDay = (props: PickersDayProps<Dayjs>) => {
    const { day, ...other } = props;
    const formattedDate = day.format('YYYY-MM-DD');
    const isWorkedDay = workedDaysSet.has(formattedDate);

    return (
      <PickersDay
        {...other}
        day={day}
        sx={{
          ...(isWorkedDay && {
            backgroundColor: '#4caf50',
            color: 'white',
            borderRadius: '50%',
            '&:hover': {
              backgroundColor: '#388e3c',
            },
          }),
        }}
      />
    );
  };

  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={async (newDate) => {
              if (!newDate || !activeTabData?.id) return;

              setLocalSelectedDate(newDate);

              const formattedDate = newDate.format('YYYY-MM-DD');
              try {
                const id = Number(activeTabData.id);
                const res = await getWorkedDay(id, formattedDate);
                if (!res) {
                  setWorkedDay({
                    driverRoadMapId: id,
                    date: formattedDate,
                    fuelAmount: 0,
                    mileageIntervall: { startMileage: 0, endMileage: 0 },
                    observation: '',
                    otherTrips: [],
                    roads: [],
                  });
                } else {
                  setWorkedDay(res);
                }
                setSelectedDate(newDate);
                setInitialSelectedDate(newDate);
                if (onChoose) onChoose(formattedDate);
              } catch (err) {
                console.error('Erreur récupération WorkedDay :', err);
              }
            }}
            minDate={startOfMonth}
            maxDate={endOfMonth}
            displayStaticWrapperAs="desktop"
            showDaysOutsideCurrentMonth={false}
            views={['day']}
            openTo="day"
            shouldDisableDate={(date) =>
              date.isBefore(startOfMonth, 'day') || date.isAfter(endOfMonth, 'day')
            }
            slots={{ day: CustomDay }}
            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>
        </Box>
      </Box>
    </LocalizationProvider>
  );
}
