"use client"

import React, { useCallback } from "react"
import { Box, Grid, Typography, Button, ToggleButtonGroup, ToggleButton, Stack, Divider, Chip, Slider } from "@mui/material"
import { faRobot, faSave, faTimes, faUsers, faRoute, faUserSlash, faFileSignature, faLocationDot, faRotateLeft } from "@fortawesome/free-solid-svg-icons"
import { tabsBorder } from "@/shared/theme/css"
import FontAwesome from "@/shared/components/fontawesome"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import type { ITripDriverAssignment } from "@/shared/types/circuit"
import { DriverFilterType } from "@/shared/types/circuit"
import TransportScheduleField from "@/shared/components/form/transport-schedule-field"
import { transformFromWeekSchedule, transformToWeekSchedule } from "../../../utils/schedule-converters"
import { StyledCircularProgress } from "@/shared/components/form/style"
import { useChauffeurStepperLogic, type DriverFilter } from "./hooks/use-chauffeur-stepper"
import { primary } from "@/shared/theme/palette"
import DriverMap from "@/shared/components/google-maps/driver-maps"

interface ChauffeurStepperFormProps {
  chauffeur: ITripDriverAssignment
  mode: ModeType
  onEdit: (updatedTrajet: ITripDriverAssignment) => void
  onClose: (isSaved: boolean) => void
  setHasUnsavedChanges: (value: boolean) => void
  updateTabContent: (tabId: string, content: ITripDriverAssignment) => void
  tabId: string
  markTabAsSaved: (tabId: string, content: ITripDriverAssignment) => void
  hasUnsavedChanges?: boolean
  circuitId?: string
  circuitStartDate?: string
  circuitEndDate?: string
}

const step1FieldNames = ["assignmentStartDate", "assignmentEndDate", "weeklyAssignmentSchedule", "tripId"]
const step2FieldNames = ["driverId"]

const marks = [
  { value: 10, label: '10' },
  { value: 50, label: '50' },
  { value: 100, label: '100' },
  { value: 150, label: '150' },
]

export default function ChauffeurStepperForm({
  chauffeur,
  mode,
  onClose,
  onEdit,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
  markTabAsSaved,
  hasUnsavedChanges,
  circuitId,
  circuitStartDate,
  circuitEndDate,
}: ChauffeurStepperFormProps) {
  const isReadOnly = mode === "view"

  const {
    LoadingDrivers,
    formik,
    formFields,
    handleSave,
    driverScores,
    driverFilters,
    setDriverFilters,
    fetchBestDrivers,
    loadingMap,
    searchRadius,
    setSearchRadius,
    isAIMode,
    resetFilters,
    switchToFilterMode,
  } = useChauffeurStepperLogic({
    chauffeur,
    mode,
    onClose,
    updateTabContent,
    tabId,
    markTabAsSaved,
    hasUnsavedChanges,
    circuitId,
    circuitStartDate,
    circuitEndDate,
  })

  const renderField = useCallback(
    (field: FormFieldType<ITripDriverAssignment>) => {
      const error = formik.touched[field.name] && formik.errors[field.name]
      const isDateField = field.name === 'assignmentStartDate' || field.name === 'assignmentEndDate'
      const showDateHelper = isDateField && !formik.values[field.name] && !isReadOnly
      
      return (
        <>
          <FormField
            field={field}
            value={formik.values[field.name]}
            onChange={(name, value) => {
              formik.setFieldValue(name, value)
              if (name === 'assignmentStartDate' || name === 'assignmentEndDate') {
                setTimeout(() => {
                  formik.setFieldTouched(name, true, true)
                }, 0)
              }
            }}
            error={error ? String(formik.errors[field.name]) : undefined}
            isReadOnly={isReadOnly}
            onBlur={formik.handleBlur}
          />
          <ConditionalComponent isValid={showDateHelper}>
            <Typography variant="caption" sx={{ color: 'success.main', mt: 0.5, display: 'block' }}>
              Veuillez remplir la date
            </Typography>
          </ConditionalComponent>
        </>
      )
    },
    [formik, isReadOnly],
  )

  const step1Fields = formFields.filter((field) => step1FieldNames.includes(field.name))
  const step2Fields = formFields.filter((field) => step2FieldNames.includes(field.name))
  const observationsField = formFields.find((field) => field.name === "observations")

  const handleRadiusChange = (event: Event, newValue: number | number[]) => {
    setSearchRadius(newValue as number)
  }

  const handleFilterChange = (event: React.MouseEvent<HTMLElement>, newFilters: DriverFilterType[]) => {
    if (newFilters.length === 0) {
      setDriverFilters([DriverFilterType.ALL])
      return
    }

    const justClickedAll = newFilters.includes(DriverFilterType.ALL) && !driverFilters.includes(DriverFilterType.ALL)

    if (justClickedAll) {
      setDriverFilters([DriverFilterType.ALL])
      return
    }

    if (driverFilters.includes(DriverFilterType.ALL) && newFilters.includes(DriverFilterType.ALL) && newFilters.length > 1) {
      const filtersWithoutAll = newFilters.filter(f => f !== DriverFilterType.ALL)
      setDriverFilters(filtersWithoutAll)
      return
    }

    const filtersWithoutAll = newFilters.filter(f => f !== DriverFilterType.ALL)
    setDriverFilters(filtersWithoutAll.length > 0 ? filtersWithoutAll : [DriverFilterType.ALL])
  }

  return (
    <Box pt={4} sx={tabsBorder}>
      <form onSubmit={formik.handleSubmit}>
        <Box mb={4}>
          <Stack direction="row" justifyContent="space-between" alignItems="center" mb={3}>
            <Stack direction="row" spacing={2} alignItems="center">
              <Typography
                variant="h6"
                sx={{
                  color: (theme) => theme.palette.primary.main,
                  fontWeight: (theme) => theme.typography.fontWeightBold,
                }}
              >
                Critères de recherche
              </Typography>
              <ConditionalComponent isValid={isAIMode}>
                <Chip
                  label="Mode IA activé"
                  color="secondary"
                  size="small"
                  icon={<FontAwesome icon={faRobot} />}
                />
              </ConditionalComponent>
            </Stack>

            <ConditionalComponent isValid={!isAIMode}>
              <Button
                variant="outlined"
                size="small"
                startIcon={<FontAwesome icon={faRotateLeft} />}
                onClick={resetFilters}
                disabled={driverFilters.length === 1 && driverFilters[0] === DriverFilterType.ALL && searchRadius === 50}
              >
                Réinitialiser
              </Button>
            </ConditionalComponent>
          </Stack>

          <ConditionalComponent isValid={!isAIMode}>
            <Box mb={3}>
              <Typography
                variant="subtitle2"
                sx={{
                  color: (theme) => theme.palette.text.secondary,
                  mb: 2,
                  fontWeight: (theme) => theme.typography.fontWeightMedium,
                }}
              >
                Filtrer les chauffeurs
              </Typography>
              <ToggleButtonGroup
                value={driverFilters}
                onChange={handleFilterChange}
                size="small"
                sx={{
                  flexWrap: "wrap",
                  gap: 1.5,
                  '& .MuiToggleButton-root': {
                    px: 2.5,
                    py: 1,
                    border: '1px solid',
                    borderColor: 'divider',
                    borderRadius: 2,
                    textTransform: 'none',
                    fontWeight: 500,
                    '&.Mui-selected': {
                      backgroundColor: 'primary.main',
                      color: 'white',
                      '&:hover': {
                        backgroundColor: 'primary.dark',
                      },
                    },
                  },
                }}
              >
                <ToggleButton value={DriverFilterType.ALL}>
                  <FontAwesome icon={faUsers} style={{ marginRight: 8 }} />
                  Tous
                </ToggleButton>
                <ToggleButton value={DriverFilterType.WITH_CIRCUIT}>
                  <FontAwesome icon={faRoute} style={{ marginRight: 8 }} />
                  Avec circuit
                </ToggleButton>
                <ToggleButton value={DriverFilterType.WITHOUT_CIRCUIT}>
                  <FontAwesome icon={faUserSlash} style={{ marginRight: 8 }} />
                  Sans circuit
                </ToggleButton>
                <ToggleButton value={DriverFilterType.WITH_APPLICATION}>
                  <FontAwesome icon={faFileSignature} style={{ marginRight: 8 }} />
                  Avec candidature
                </ToggleButton>
              </ToggleButtonGroup>
            </Box>
          </ConditionalComponent>

          <Box mb={3}>
            <Stack
              direction="row"
              spacing={2}
              alignItems="center"
              sx={{
                backgroundColor: (theme) => theme.palette.background.neutral,
                p: 2,
                borderRadius: 2,
                border: '1px solid',
                borderColor: 'divider',
              }}
            >
              <Stack direction="row" spacing={1} alignItems="center" sx={{ minWidth: 200 }}>
                <FontAwesome icon={faLocationDot} style={{ color: primary.main, fontSize: 16 }} />
                <Typography
                  variant="body2"
                  sx={{
                    color: (theme) => theme.palette.text.secondary,
                    fontWeight: 500,
                  }}
                >
                  Rayon :
                </Typography>
                <Chip
                  label={`${searchRadius} km`}
                  size="small"
                  color="primary"
                  sx={{ fontWeight: 600 }}
                />
              </Stack>

              <Box sx={{ flex: 1, px: 2 }}>
                <Slider
                  value={searchRadius}
                  onChange={handleRadiusChange}
                  aria-labelledby="search-radius-slider"
                  valueLabelDisplay="auto"
                  valueLabelFormat={(value) => `${value} km`}
                  step={5}
                  marks={marks}
                  min={10}
                  max={150}
                  sx={{
                    '& .MuiSlider-thumb': {
                      width: 16,
                      height: 16,
                    },
                    '& .MuiSlider-markLabel': {
                      fontSize: 11,
                    },
                    '& .MuiSlider-valueLabel': {
                      fontSize: 11,
                      fontWeight: 'normal',
                      top: -6,
                      backgroundColor: 'unset',
                      color: (theme) => theme.palette.text.primary,
                      '&:before': {
                        display: 'none',
                      },
                      '& *': {
                        background: 'transparent',
                        color: (theme) => theme.palette.mode === 'dark' ? '#fff' : '#000',
                      },
                    },
                  }}
                />
              </Box>
            </Stack>
          </Box>

          <ConditionalComponent isValid={isAIMode}>
            <Box
              sx={{
                p: 3,
                backgroundColor: 'action.hover',
                borderRadius: 2,
                border: '1px dashed',
                borderColor: 'primary.main'
              }}
            >
              <Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
                <Stack direction="row" spacing={2} alignItems="center">
                  <FontAwesome icon={faRobot} style={{ fontSize: 24, color: primary.main }} />
                  <Box>
                    <Typography variant="subtitle1" fontWeight={600}>
                      Optimisation IA activée
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Les chauffeurs affichés sont triés par l&apos;algorithme d&apos;optimisation
                    </Typography>
                  </Box>
                </Stack>

                <Button
                  variant="outlined"
                  size="small"
                  onClick={switchToFilterMode}
                  startIcon={<FontAwesome icon={faUsers} />}
                >
                  Revenir aux filtres
                </Button>
              </Stack>
            </Box>
          </ConditionalComponent>
        </Box>

        <Divider sx={{ my: 4 }} />

        <Box mb={4}>
          <Typography
            variant="h6"
            sx={{
              color: (theme) => theme.palette.primary.main,
              mb: 3,
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Informations générales
          </Typography>

          <Grid container spacing={3}>
            {step1Fields.map((field) => (
              <ConditionalComponent
                key={field.name}
                isValid={field.name === "weeklyAssignmentSchedule"}
                defaultComponent={
                  <Grid
                    sx={{
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                    }}
                    item
                    xs={12}
                    sm={6}
                  >
                    {renderField(field)}
                  </Grid>
                }
              >
                <React.Fragment>
                  <Grid item sm={12} md={8}>
                    <Typography sx={{ color: (theme) => theme.palette.primary.main, mb: 2 }}>
                      {field.label}
                    </Typography>
                    <TransportScheduleField
                      initialSchedules={transformToWeekSchedule(
                        Array.isArray(formik.values[field.name])
                          ? (formik.values[field.name] as any[])
                          : []
                      )}
                      onChange={(updatedSchedules) =>
                        formik.setFieldValue(field.name, transformFromWeekSchedule(updatedSchedules))
                      }
                      isReadOnly={isReadOnly}
                    />
                    <ConditionalComponent isValid={!!formik.touched[field.name] && !!formik.errors[field.name]}>
                      <Typography color="error" variant="caption">
                        {String(formik.errors[field.name])}
                      </Typography>
                    </ConditionalComponent>
                  </Grid>
                  <Grid item xs={12} sm={4} sx={{ display: { xs: "none", sm: "block" } }} />
                </React.Fragment>
              </ConditionalComponent>
            ))}
          </Grid>
        </Box>

        <Divider sx={{ my: 4 }} />

        <Box mb={4}>
          <Stack direction="row" justifyContent="space-between" alignItems="center" mb={3}>
            <Typography
              variant="h6"
              sx={{
                color: (theme) => theme.palette.primary.main,
                fontWeight: (theme) => theme.typography.fontWeightBold,
              }}
            >
              Carte des chauffeurs
            </Typography>

            <ConditionalComponent isValid={!isAIMode}>
              <Button
                variant="contained"
                color="primary"
                startIcon={<FontAwesome icon={faRobot} />}
                onClick={fetchBestDrivers}
                disabled={loadingMap}
              >
                {loadingMap ? "Recherche..." : "Optimiser avec IA"}
              </Button>
            </ConditionalComponent>
          </Stack>

          <ConditionalComponent
            isValid={!loadingMap}
            defaultComponent={
              <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", py: 8 }}>
                <StyledCircularProgress size={40} color="primary" />
                <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
                  Chargement des chauffeurs...
                </Typography>
              </Box>
            }
          >
            <Box mb={3}>
              <Typography
                variant="subtitle2"
                sx={{
                  color: (theme) => theme.palette.text.secondary,
                  mb: 2,
                  fontWeight: (theme) => theme.typography.fontWeightMedium,
                }}
              >
                Chauffeurs disponibles ({driverScores.length})
              </Typography>
              <DriverMap
                drivers={driverScores}
                selectedDriverId={String(formik.values.driverId)}
                onDriverSelect={(driverId) => formik.setFieldValue("driverId", driverId)}
                height="450px"
              />
            </Box>

            <Grid container spacing={3}>
              {step2Fields.map((field) => (
                <Grid
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "center",
                  }}
                  item
                  xs={12}
                  sm={8}
                  key={field.name}
                >
                  {renderField(field)}
                </Grid>
              ))}
            </Grid>
          </ConditionalComponent>
        </Box>

        <Divider sx={{ my: 4 }} />

        <ConditionalComponent isValid={!!observationsField}>
          <Box mb={4}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                {renderField(observationsField!)}
              </Grid>
            </Grid>
          </Box>
        </ConditionalComponent>

        <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2, pt: 3 }}>
          <Button
            variant="outlined"
            color="inherit"
            startIcon={<FontAwesome icon={faTimes} />}
            onClick={() => onClose(false)}
          >
            Annuler
          </Button>
          <Button
            variant="contained"
            color="primary"
            startIcon={<FontAwesome icon={faSave} />}
            onClick={handleSave}
            disabled={LoadingDrivers || loadingMap}
          >
            Enregistrer
          </Button>
        </Box>
      </form>
    </Box>
  )
}