"use client"

import type React from "react"
import { useEffect, useMemo, useCallback, useState } from "react"
import { Grid, Stack, IconButton, Box, CircularProgress } from "@mui/material"
import FontAwesome from "@/shared/components/fontawesome"
import { faPenToSquare } from "@fortawesome/free-solid-svg-icons"
import { iconButtonStyles } from "@/shared/theme/css"
import { getFormFieldsCircuit } from "../../utils/form-fields-circuit"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import type { Circuit } from "@/shared/types/circuit"
import type { FormFieldType } from "@/shared/types/common"
import ActionButtons from "@/shared/components/form/buttons-action"
import { useFormikContext } from "formik"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import type { ModeType } from "@/shared/types/common"
import { useCircuitFormOptions } from "../../hooks/use-circuit-form-options"
import { useEstablishmentSearch } from "@/shared/sections/usager/hooks/use-establishment-search"
import { useEstablishmentStore } from "@/shared/api/stores/admin-service/establishmentStore"
import { Button } from "@mui/material";
import { ContractList } from "@/shared/types/contract"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { RenderFieldOptions } from "../../view/circuit-new-view"
import CreateContractModal from "@/shared/components/dialog/create-contract-modal"
import CreateEtablissementModal from "@/shared/components/dialog/create-etablissement-modal"

interface CircuitTabContentProps {
  renderField: (field: FormFieldType<Circuit>, options?: RenderFieldOptions) => React.ReactNode
  mode: ModeType
  onEdit: (updatedContract: Circuit) => void
  onClose: (isSaved: boolean) => void
  fieldsToShow?: string[]
}

export default function CircuitTabForm({ renderField, mode, onEdit, onClose, fieldsToShow }: CircuitTabContentProps) {
  const isReadOnly = mode === "view"
  const isEditMode = mode === "edit"
  const formik = useFormikContext<Circuit>()

  const { searchEstablishments } = useEstablishmentSearch();
  const { establishmentNamesAndIds } = useEstablishmentStore();
  const {
    driverOptions,
    contractOptions,
    lotOptions,
    searchContracts,
    isLoading,
    updateLotOptions,
  } = useCircuitFormOptions()

  const [establishmentOptions, setEstablishmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [openContractModal, setOpenContractModal] = useState(false);
  const [openMainEstablishmentModal, setOpenMainEstablishmentModal] = useState(false);
  const handleAddContract = () => setOpenContractModal(true);
  const handleCloseContractModal = () => setOpenContractModal(false);
  const handleAddMainEstablishment = () => setOpenMainEstablishmentModal(true);
  const handleCloseMainEstablishmentModal = () => setOpenMainEstablishmentModal(false);
  useEffect(() => {
    if (establishmentNamesAndIds.length > 0) {
      setEstablishmentOptions(establishmentNamesAndIds.map((establishment) => ({
        value: establishment.id.toString(),
        label: establishment.name
      })));
    }
  }, [establishmentNamesAndIds]);

  useEffect(() => {
    const mainEstablishmentId = formik.values.mainEstablishment;
    searchEstablishments(mainEstablishmentId ? mainEstablishmentId.toString() : undefined);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const selectedContractId = formik.values.contractId
    if (selectedContractId) {
      const contractData = updateLotOptions(selectedContractId)
      if (contractData) {
        formik.setFieldValue("colorCode", contractData.colorCode)
        formik.setFieldValue("lotIds", contractData.lotNumber)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formik.values.contractId, updateLotOptions, formik.setFieldValue])

  const formFields = useMemo(
    () => getFormFieldsCircuit(establishmentOptions, driverOptions, contractOptions, lotOptions, searchContracts, searchEstablishments),
    [establishmentOptions, driverOptions, contractOptions, lotOptions, searchContracts, searchEstablishments],
  )

  const filteredFormFields = useMemo(
    () => (fieldsToShow ? formFields.filter((field) => fieldsToShow.includes(field.name)) : formFields),
    [formFields, fieldsToShow],
  )

  const memoizedFormFields = useMemo(
    () => (
      <>
        {filteredFormFields.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field, { onAddContract: handleAddContract , onAddMainEstablishment : handleAddMainEstablishment })}
          </Grid>

        ))}
      </>
    ),
    [filteredFormFields, renderField],
  )

  const handleSave = useCallback(async () => {
    formik.submitForm()
  }, [formik])

  const handleEdit = useCallback(() => {
    onEdit(formik.values)
  }, [onEdit, formik.values])

  const handleCancel = useCallback(() => {
    onClose(false)
  }, [onClose])


  return (
    <>
      <form onSubmit={formik.handleSubmit}>
        <ConditionalComponent isValid={isReadOnly}>
          <Stack flexGrow={0} direction="row" justifyContent="flex-end">
            <CustomTooltip title="edit Circuit" arrow>
              <IconButton onClick={handleEdit} size="small" sx={iconButtonStyles}>
                <FontAwesome icon={faPenToSquare} width={16} />
              </IconButton>
            </CustomTooltip>
          </Stack>
        </ConditionalComponent>

        <Grid container spacing={6} sx={{ pt: 2 }}>
          {memoizedFormFields}
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons onSave={handleSave} onCancel={handleCancel} mode={isEditMode ? "edit" : ""} loading={isLoading} />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
      <CreateContractModal
        open={openContractModal}
        onClose={handleCloseContractModal}
        contrat={{} as ContractList}
        mode="add"
        PaperProps={{
          style: {
            height: '90vh',
            width: '80%',
            maxWidth: 'none',
          },
        }}
      />
       <CreateEtablissementModal
        open={openMainEstablishmentModal}
        onClose={handleCloseMainEstablishmentModal}
        PaperProps={{
          style: {
            height: '90vh',
            width: '80%',
            maxWidth: 'none',
          },
        }}
      />

    </>

  )
}
