'use client';

import React, { useEffect, useState } from 'react';
import { Typography, Grid, Chip, Alert, Box, CircularProgress, Button, Stack, IconButton, Popover, Autocomplete, TextField } from '@mui/material';
import { Check, Calendar } from 'lucide-react';
import { centerFlexColumn } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import { TypeTrajet } from '@/shared/types/trajet';
import { TripCircuitDetails } from '@/shared/types/circuit';
import { getPlanningTrajetFormFields } from './form-fields-planning-trajet';
import FormContainer from '@/layouts/form/form-container';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import AddPointModal from '@/shared/sections/trajet/components/add-point-modal';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import TransportScheduleField from '@/shared/components/form/transport-schedule-field';
import { useJsApiLoader } from "@react-google-maps/api";
import { Driver } from '../../types';
import { CurrentTimeSlot } from '@/shared/sections/planning/types/planning-types';
import { transformFromWeekSchedule, transformToWeekSchedule } from '@/shared/sections/circuit/utils/schedule-converters';
import DetailsPlanningTrajet from './details-planning-trajet';

interface TrajetFormProps {
  trajet: TripCircuitDetails;
  mode: ModeType;
  onSave?: (updatedTrajet: TripCircuitDetails) => void;
  onEdit?: (updatedTrajet: TripCircuitDetails) => void;
  onClose: () => void;
  isDrawerElement?: boolean
  hasBorder?: boolean;
  tableHead: TableColumn[];
  handleView: (item: TripCircuitDetails) => void;
  isPlanning?: boolean
  drivers?: Driver[]
  currentTimeSlot?: CurrentTimeSlot;
  setDrawerMode: React.Dispatch<React.SetStateAction<ModeType>>;
  defaultSelectedType?: 'personnalisé' | 'dupliqué' | 'view';
}


const GOOGLE_MAPS_LIBRARIES: ("places" | "geometry")[] = ["places", "geometry"]

function DetailsPlanningTrajetWithGoogleLoader(props: any) {
  const { isLoaded, loadError } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || "",
    libraries: GOOGLE_MAPS_LIBRARIES,
  })
  if (loadError) {
    return (<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
      <Alert severity="error"> Erreur de chargement Google Maps: {loadError.message}</Alert>
    </Box>);
  }

  if (!isLoaded) {
    return (<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
      <CircularProgress />
    </Box>);
  }
  return <DetailsPlanningTrajet {...props} isGoogleLoaded={isLoaded} />
}
const formatDate = (dateStr: string) => {
  const [year, month, day] = dateStr.split("-");
  return `${day}-${month}-${year}`;
};


export default function TrajetPlanningForm({ trajet, mode, onSave, onClose, onEdit, isDrawerElement, hasBorder, tableHead, handleView, isPlanning, drivers, currentTimeSlot, setDrawerMode ,defaultSelectedType }: TrajetFormProps) {
  const [formData, setFormData] = useState<TripCircuitDetails>(trajet!);
  const [selectedType, setSelectedType] = useState<'personnalisé' | 'dupliqué' | 'view'>(defaultSelectedType || 'view');
  const [calendarAnchor, setCalendarAnchor] = useState<HTMLElement | null>(null);
  const [selectedDates, setSelectedDates] = useState<Date[]>([]);
  const [selectedDriver, setSelectedDriver] = useState<Driver | null>(null);
  const [sortableTrajetRowEditable, setSortableTrajetRowEditable] = useState<boolean>(false)
  const trajetformFields = getPlanningTrajetFormFields(drivers);

  const handleCalendarClick = (event: React.MouseEvent<HTMLElement>) => {
    setCalendarAnchor(event.currentTarget);
  };

  const handleCalendarClose = () => {
    setCalendarAnchor(null);
  };

  const handleDateToggle = (date: Date) => {
    setSelectedDates(prev => {
      const dateString = date.toISOString().split('T')[0];
      const exists = prev.some(d => d.toISOString().split('T')[0] === dateString);
      if (exists) {
        return prev.filter(d => d.toISOString().split('T')[0] !== dateString);
      } else {
        return [...prev, date];
      }
    });
  };

  const isDateSelected = (date: Date) => {
    const dateString = date.toISOString().split('T')[0];
    return selectedDates.some(d => d.toISOString().split('T')[0] === dateString);
  };

  const renderCalendar = () => {
    const today = new Date();
    const currentMonth = today.getMonth();
    const currentYear = today.getFullYear();
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const firstDay = new Date(currentYear, currentMonth, 1).getDay();

    const days = [];
    for (let i = 0; i < firstDay; i++) {
      days.push(<Box key={`empty-${i}`} sx={{ width: 40, height: 40 }} />);
    }

    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(currentYear, currentMonth, day);
      const isSelected = isDateSelected(date);

      days.push(
        <Box
          key={day}
          onClick={() => handleDateToggle(date)}
          sx={{
            width: 40,
            height: 40,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            borderRadius: 1,
            backgroundColor: isSelected ? 'primary.main' : 'transparent',
            color: isSelected ? 'white' : 'text.primary',
            '&:hover': {
              backgroundColor: isSelected ? 'primary.dark' : 'action.hover',
            },
          }}
        >
          {day}
        </Box>
      );
    }

    return (
      <Box sx={{ p: 2, width: 320 }}>
        <Typography variant="subtitle1" sx={{ mb: 2, textAlign: 'center' }}>
          {new Date(currentYear, currentMonth).toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })}
        </Typography>
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0.5, mb: 1 }}>
          {['D', 'L', 'M', 'M', 'J', 'V', 'S'].map((day, i) => (
            <Box key={i} sx={{ width: 40, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', fontSize: '0.875rem' }}>
              {day}
            </Box>
          ))}
        </Box>
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0.5 }}>
          {days}
        </Box>
      </Box>
    );
  };


  const handleSave = () => {
    if (onSave) {
      onSave(formData);
    }
    onClose();
  };

  const isReadOnly = mode === 'view';
  const isPlanningMode = isPlanning;

  const isFieldDisabledInCopyMode = (fieldName: string) => {
    if (mode !== "copy") return false
    if (fieldName === "tripObservation") return false
    return !formData.tripObservation
  }

  const isFieldDisabledInPlanningMode = (fieldName: string) => {
    if (!isPlanningMode) return false
    return !["tripObservation", "driver"].includes(fieldName)
  }
  const isAlwaysDisable = (fieldName: string) => {
    return !['tripObservation', 'routeSheetNote', 'driver'].includes(fieldName)
  }
  useEffect(() => {
    if (formData.tripObservation && formData.tripObservation.trim() !== "") {
      setSortableTrajetRowEditable(true);

    } else {
      setSortableTrajetRowEditable(false);
    }
  }, [formData.tripObservation]);
  const renderField = (field: FormFieldType<TripCircuitDetails>) => {
    let fieldValue = formData[field.name as keyof TripCircuitDetails];
    if (fieldValue === undefined || fieldValue === null) {
      switch (field.name) {

        case 'customizedDate':
          if (selectedType !== 'view') {
            fieldValue = new Date().toISOString().split('T')[0];
            setFormData((prev) => ({ ...prev, customizedDate: fieldValue }));
          }
          break;

        case 'tripType':
          if (selectedType !== 'view') {
            fieldValue = TypeTrajet.personnalise;
            setFormData((prev) => ({ ...prev, tripType: fieldValue }));
          }
          break;

        default:
          switch (field.type) {
            case 'text':
              fieldValue = '';
              break;
            case 'number':
              fieldValue = 0;
              break;
            case 'select':
              fieldValue = '';
              break;
            case 'date':
              fieldValue = '';
              break;
            default:
              fieldValue = '';
          }
      }
    }

    const isFieldDisabled =
      isReadOnly ||
      isFieldDisabledInCopyMode(field.name) ||
      isFieldDisabledInPlanningMode(field.name) ||
      isAlwaysDisable(field.name);

    return (
      <FormField
        field={field}
        value={fieldValue}
        onChange={(name, value) => {
          setFormData((prev) => ({ ...prev, [name]: value }));
        }}
        isReadOnly={isFieldDisabled}
        isDrawerElement={isDrawerElement}
      />
    );
  };
  useEffect(() => {
    if (selectedType !== 'view') {
      setFormData((prev) => ({
        ...prev,
        tripType: TypeTrajet.personnalise,
        customizedDate: prev.customizedDate ?? new Date().toISOString().split('T')[0],
      }));
    }
  }, [selectedType]);

  return (
    <>
      <FormContainer titre={
        <Stack direction="row" alignItems="center" spacing={1}>
          <Typography variant="h5" sx={{ fontWeight: 800 }}>
            {isPlanning || selectedType != 'view' ? "Fiche Trajet Personnalisé" : "Fiche Trajet"}
          </Typography>
          <ConditionalComponent isValid={!!(currentTimeSlot?.date)}>
            <Chip
              label={`${formatDate(currentTimeSlot?.date ?? '')} • ${currentTimeSlot?.startHour ?? ''}:${currentTimeSlot?.startMinute ?? ''}`}
              color="info"
              size="small"
              sx={{
                fontWeight: 500,
                backgroundColor: "info.lighter",
                color: "info.dark",
                borderRadius: 2,
              }}
            />
          </ConditionalComponent>

        </Stack>
      } isSousElemnt={isDrawerElement || hasBorder} hasBorder={hasBorder}>

        <ConditionalComponent isValid={!isPlanning}>
          <ConditionalComponent isValid={selectedType === 'view'}>
            <Stack
              direction="row"
              spacing={1}
              sx={{
                position: "absolute",
                top: 20,
                right: 20,
              }}
            >
              <Button
                variant="outlined"
                size="small"
                sx={{ textTransform: 'none' }}
                onClick={() => {
                  setSelectedType('personnalisé');
                  setDrawerMode('copy');
                }}
              >
                Personnalisé
              </Button>

              <Button
                variant="outlined"
                size="small"
                sx={{ textTransform: 'none' }}
                onClick={() => {
                  setSelectedType('dupliqué');
                  setDrawerMode('copy');
                }}
              >
                Dupliqué
              </Button>
            </Stack>
          </ConditionalComponent>

          <ConditionalComponent isValid={selectedType === 'dupliqué'}>
            <>
              <IconButton
                size="small"
                onClick={handleCalendarClick}
                sx={{
                  position: "absolute",
                  top: 20,
                  right: 20,
                  border: '1px solid',
                  borderColor: 'divider',
                  borderRadius: 1,
                }}
              >
                <Calendar size={18} />
              </IconButton>

              <Popover
                open={Boolean(calendarAnchor)}
                anchorEl={calendarAnchor}
                onClose={handleCalendarClose}
                anchorOrigin={{
                  vertical: 'bottom',
                  horizontal: 'right',
                }}
                transformOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
              >
                {renderCalendar()}
              </Popover>
            </>
          </ConditionalComponent>

        </ConditionalComponent>


        {isReadOnly && onEdit ? (
          <EditExportButtons
            onEdit={() => onEdit(trajet!)}
            onExport={() => void 0}
            tooltipTitle={TableType.Trajet}
            dataRow={trajet}
            tableHead={tableHead}
          />
        ) : (
          <></>
        )}

        <form>

          <Grid container spacing={isDrawerElement ? 2 : 4}>
            {trajetformFields.map((field) => (
              <ConditionalComponent
                key={field.name}
                isValid={field.name === 'weeklySchedules'}
                defaultComponent={
                  <Grid
                    sx={field.name === "rotation" ? { visibility: 'hidden' } : centerFlexColumn}
                    item
                    xs={12}
                    sm={field.type === "textarea" && isDrawerElement ? 6 : 4}
                  >
                    {renderField(field)}
                  </Grid>
                }
              >
                <React.Fragment key={field.name}>
                  <Grid item sm={12} md={7} xl={isDrawerElement ? 12 : 5}>
                    <Typography sx={{ color: (theme) => theme.palette.primary.main }}>
                      {field.label}
                    </Typography>
                    <TransportScheduleField
                      initialSchedules={transformToWeekSchedule(trajet?.weeklySchedules!)}
                      otherSchedules={[]}
                      onChange={(val) => {
                        setFormData((prev) => ({
                          ...prev,
                          weeklySchedules: transformFromWeekSchedule(val)
                        }));
                      }}
                      isReadOnly={mode === "view" || isPlanningMode! || true}
                    />
                  </Grid>
                  <ConditionalComponent isValid={!isDrawerElement}>
                    <Grid item sm={12} md={1} xl={3} />
                  </ConditionalComponent>
                </React.Fragment>
              </ConditionalComponent>
            ))}


            <Grid item xs={12}>
              <DetailsPlanningTrajetWithGoogleLoader
                mode={mode}
                isDrawerElement={isDrawerElement}
                trajetId={formData.id}
                trajet={formData}
                handleView={handleView}
                onClose={onClose}
                isPlanningMode={isPlanningMode}
                onUpdateTrajet={(updatedTrajet: TripCircuitDetails) => setFormData(updatedTrajet)}
                selectedType={selectedType}
                editable={sortableTrajetRowEditable}
              />
            </Grid>

            <ConditionalComponent isValid={!isReadOnly}>
              <Grid item xs={12}>
                <ActionButtons onSave={handleSave} onCancel={onClose} mode={mode} />
              </Grid>
            </ConditionalComponent>
          </Grid>
        </form>
      </FormContainer>
    </>
  );
}