"use client"

import React, { useEffect, useMemo, useState } from 'react';
import { Grid } from '@mui/material';
import { centerFlexColumn } from '@/shared/theme/css';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import { getPassengerFormFields } from '../../utils/form-fields-usager';
import ScheduleTable from '@/shared/components/form/schedule-table';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import AvatarUploader from '@/shared/components/form/avatar-uploader';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { IPassengerList } from '@/shared/types/passenger';
import { useEstablishmentStore } from '@/shared/api/stores/admin-service/establishmentStore';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import EtablissementJoursField, { type EstablishmentSchedule } from "@/shared/components/form/etablissement-jours-field"
import { useFormikContext } from 'formik';
import { StyledCircularProgress } from "@/shared/components/form/style"
import { apiToComponentStructure, componentToApiStructure } from "../../utils/schedule-converters"
import { mockWeekScheduleData } from '@/shared/_mock/_usagers';


interface UsagerTabContentProps {
  renderField: (field: FormFieldType<IPassengerList>) => React.ReactNode;
  usager: IPassengerList;
  onEdit: (updatedContract: IPassengerList) => void;
  handleSave: () => void;
  onClose: () => void;
  mode: ModeType;
  tableHead: TableColumn[];
  loading: boolean;
}

export default function UsagerTabForm({
  renderField,
  usager,
  onEdit,
  handleSave,
  onClose,
  mode,
  tableHead,
  loading
}: UsagerTabContentProps) {
  const isReadOnly = mode === 'view';
  const { establishmentNamesAndIds, getAllEstablishmentNamesAndIds } = useEstablishmentStore();
  const { departmentNames, fetchDepartmentNames } = useInfrastructureStore();
  const formik = useFormikContext<IPassengerList>();

  const [establishmentOptions, setEstablishmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [frontendSchedules, setFrontendSchedules] = useState<EstablishmentSchedule[]>([]);
  const [isSchedulesLoaded, setIsSchedulesLoaded] = useState(false);

  useEffect(() => {
    setIsSchedulesLoaded(false)
      const convertedSchedules = apiToComponentStructure(formik.values.establishmentTransportSchedules)
      setFrontendSchedules(convertedSchedules)
      setIsSchedulesLoaded(true)
  }, [formik.values.establishmentTransportSchedules])

  useEffect(() => {
    const fetchData = async () => {
      await getAllEstablishmentNamesAndIds();
      await fetchDepartmentNames();
    };
    
    fetchData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => {
    if (establishmentNamesAndIds.length > 0) {
      setEstablishmentOptions(establishmentNamesAndIds.map((establishment) => ({
        value: establishment.id.toString(),
        label: establishment.name
      })));
    }
  }, [establishmentNamesAndIds]);

  useEffect(() => {
    if (departmentNames.length > 0) {
      setDepartmentOptions(departmentNames.map((department) => ({
        value: department.id.toString(),
        label: department.name
      })));
    }
  }, [departmentNames]);



  const isDataReady = isSchedulesLoaded

  const memoizedFormFields = useMemo(() => {
    const fields = getPassengerFormFields(establishmentOptions, departmentOptions);
    const handleScheduleChange = (newSchedules: EstablishmentSchedule[]) => {
      setFrontendSchedules(newSchedules)
      formik.setFieldValue("establishmentTransportSchedules", componentToApiStructure(newSchedules))
    }
    const getEstablishmentError = (index: number): string | undefined => {
      const errors = formik.errors?.establishmentTransportSchedules && formik.touched?.establishmentTransportSchedules
      if(errors) {  
        if ( typeof formik.errors.establishmentTransportSchedules === "string") {
            return formik.errors.establishmentTransportSchedules
        }

        if (Array.isArray(formik.errors.establishmentTransportSchedules)) {
          const error = formik.errors.establishmentTransportSchedules[index];
          if (error && typeof error !== 'string' && error.idEstablishment) {
            return error.idEstablishment;
          }
        }
    }
      return undefined
  }
  const handleFieldBlur = (index: number) => {
    formik.handleBlur(`establishmentTransportSchedules[${index}].idEstablishment`)    
  }
  
    return (
      <>
        <Grid item xs={12}>
          <AvatarUploader onUpload={() => void 0} isReadOnly={isReadOnly || loading} />
        </Grid>
        {fields.map((field) => {
          if (field.name === "establishmentTransportSchedules") {
            if (!isDataReady) {
              return (
                <Grid item xs={12} key="etablissements-jours-loading">
                  <StyledCircularProgress size={15} color="inherit"/>
                </Grid>
              )
            }

            return (
              <React.Fragment key="etablissements-jours">
                <EtablissementJoursField
                  field={{
                    ...field,
                    name: 'etablissements',
                    label: 'Établissement'
                  }}
                  values={{
                    establishmentTransportSchedules: frontendSchedules,
                  }}
                  errors={getEstablishmentError}
                  isReadOnly={mode === 'edit' || isReadOnly}
                  etablissementsOptions={establishmentOptions}
                  onFieldChange={(name, value) => {
                    if (name === "establishmentTransportSchedules") {
                      handleScheduleChange(value)
                    }
                  }}
                  handleFieldBlur={handleFieldBlur}
                />
              </React.Fragment>
            );
          }
          
          return (
            <Grid sx={centerFlexColumn} item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          );
        })}
      </>
    )
  }, [establishmentOptions, departmentOptions, isReadOnly, loading, formik, renderField, isDataReady, frontendSchedules])

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(usager)}
          onExport={() => void 0}
          tooltipTitle={TableType.Usager}
          dataRow={usager}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <Grid container spacing={4} sx={{ pt: 2 }}>
        {memoizedFormFields}
      </Grid>
      <ConditionalComponent defaultComponent={<ScheduleTable title="Emploi du temps" mode="time" scheduleData={mockWeekScheduleData} />} isValid={!isReadOnly} >
        <Grid item xs={12} sx={{ mt: 2 }}>
          <ActionButtons onSave={handleSave} onCancel={onClose} mode={mode} loading={loading} />
        </Grid>
      </ConditionalComponent>
    </>
  );
}