  "use client"

  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 { 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 { FormikContextType, FormikTouched } from 'formik'
  import type { EstablishmentRequest } from '@/shared/types/establishment'
  import ConditionalComponent from '@/shared/components/table/ConditionalComponent'
  import dayjs from "dayjs"

  interface EtablissementHoursFormProps {
    mode: ModeType
    onClose: (isSaved: boolean) => void
    onEdit: () => void
    formik: FormikContextType<EstablishmentRequest>
  }

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

  const morningHours = ["mondayMorningOpeningTime", "tuesdayMorningOpeningTime", "wednesdayMorningOpeningTime", "thursdayMorningOpeningTime", "fridayMorningOpeningTime", "saturdayMorningOpeningTime", "sundayMorningOpeningTime"]
  const eveningHours = ["mondayEveningClosingTime", "tuesdayEveningClosingTime", "wednesdayEveningClosingTime", "thursdayEveningClosingTime", "fridayEveningClosingTime", "saturdayEveningClosingTime", "sundayEveningClosingTime"]

  export default function EstablishmentHoursForm({
    mode,
    onClose,
    onEdit,
    formik
  }: EtablissementHoursFormProps) {
    const isReadOnly = mode === "view"
    const scheduleTypes = ["matin", "soir"] as const

    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>
                      {(scheduleType === "matin" ? morningHours : eveningHours).map((field) => {
                        const day = DAYS[morningHours.indexOf(field)];
                        return (
                          <Box key={field} sx={{ mb: 2 }}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                              <StyledTimePicker
                                label={day}
                                disabled={isReadOnly}
                                slots={{ openPickerIcon: CustomTimeIcon }}
                                value={
                                  formik.values[field as keyof EstablishmentRequest]
                                    ? dayjs(formik.values[field as keyof EstablishmentRequest] as string, "HH:mm")
                                    : null
                                }
                                onChange={(newValue) => {
                                  if (!newValue) {
                                    formik.setFieldValue(field, "");
                                    return;
                                  }
                                
                                  if ("format" in newValue) {
                                    formik.setFieldValue(field, newValue.format("HH:mm"));
                                  } else {
                                    const hours = newValue.getHours().toString().padStart(2, "0");
                                    const minutes = newValue.getMinutes().toString().padStart(2, "0");
                                    formik.setFieldValue(field, `${hours}:${minutes}`);
                                  }
                                }}                              
                                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={() => {
                    formik.validateForm().then((errors) => {
                      const hasErrors = Object.keys(errors).length > 0;
                      if (!hasErrors) {
                        formik.submitForm();
                      } else {
                        formik.setTouched(
                          Object.keys(errors).reduce((acc, key) => {
                            acc[key as keyof EstablishmentRequest] = true;
                            return acc;
                          }, {} as FormikTouched<EstablishmentRequest>)
                        );
                        console.log(errors);
                      }
                    });
                  }}
                  onCancel={() => {
                    onClose(false);
                  }}
                  mode={mode}
                />
              </Grid>
            </ConditionalComponent>
          </Grid>
        </form>
      </>
    )
  }