"use client"

import { useState } from "react"
import { Grid, Typography } from "@mui/material"
import { Box } from "@mui/system"
import { faCalendar, faClock } from "@fortawesome/free-solid-svg-icons"
import { LocalizationProvider } from "@mui/x-date-pickers"
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"
import { TimeValue } from "@/shared/types/usager"
import { ModeType } from "@/shared/types/common"
import FontAwesome from "@/shared/components/fontawesome"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { DAYS } from "@/shared/_mock/_usagers"
import { StyledTimePicker } from "@/shared/theme/css"
import ActionButtons from "@/shared/components/form/buttons-action"
import { useFormikContext } from 'formik'
import type { EstablishmentRequest } from '@/shared/types/establishment'
import ConditionalComponent from '@/shared/components/table/ConditionalComponent'

interface EtablissementHoursFormProps {
  mode: ModeType
  onClose: () => void
  onEdit: () => void
}

interface HorairesType {
  [key: string]: { matin: TimeValue; soir: TimeValue }
}

const CustomTimeIcon = () => <FontAwesome icon={faClock} sx={{ color: "primary.main" }} />

export default function EstablishmentHoursForm({
  mode,
  onClose,
  onEdit,
}: EtablissementHoursFormProps) {
  const { handleSubmit } = useFormikContext<EstablishmentRequest>()
  const isReadOnly = mode === "view"
  const scheduleTypes = ["matin", "soir"] as const
  const [selectedHoraires, setSelectedHoraires] = useState<HorairesType>({})

  const onChange = (day: string, scheduleType: "matin" | "soir", newValue: TimeValue | null) => {
    setSelectedHoraires((prev) => ({
      ...prev,
      [day]: {
        ...prev[day],
        [scheduleType]: newValue,
      },
    }))
  }

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons onEdit={onEdit} onExport={() => void 0} tooltipTitle="les horaires" />
      </ConditionalComponent>
      <form>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <Grid spacing={6} sx={{ mx: "10%", mt: 4 }}>
              <Grid container spacing={"10%"}>
                {scheduleTypes.map((scheduleType) => (
                  <Grid item xs={12} md={6} key={scheduleType}>
                    <Box sx={{ display: "flex", gap: 1 }}>
                      <FontAwesome color={"primary.main"} sx={{ mt: 1 }} icon={faCalendar} width={20} />
                      <Typography
                        variant="h5"
                        sx={{
                          mb: 2,
                          color: "primary.main",
                          fontWeight: (theme) => theme.typography.fontWeightBold,
                        }}
                      >
                        Horaires {' du '}{scheduleType}
                      </Typography>
                    </Box>
                    {DAYS.map((day) => (
                      <Box key={`${day}-${scheduleType}`} sx={{ mb: 2 }}>
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                          <StyledTimePicker
                            label={day}
                            disabled={isReadOnly}
                            slots={{ openPickerIcon: CustomTimeIcon }}
                            value={selectedHoraires[day.toLowerCase()]?.[scheduleType] || null}
                            onChange={(newValue) => {
                              onChange(day.toLowerCase(), scheduleType, newValue)
                            }}
                            slotProps={{
                              textField: {
                                fullWidth: true,
                                placeholder: "Sélectionner l'heure",
                              },
                            }}
                            views={["hours", "minutes"]}
                            format="HH:mm"
                          />
                        </LocalizationProvider>
                      </Box>
                    ))}
                  </Grid>
                ))}
              </Grid>
            </Grid>
          </Grid>
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons onSave={handleSubmit} onCancel={onClose} mode={mode} />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </>
  )
}

