"use client"

import { useEffect, useMemo, useState } from "react"
import { Grid, Stack, IconButton } 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, Option } from "../../utils/form-fields-circuit"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import type { Circuit, ICircuitContract } from "@/shared/types/circuit"
import type { FormFieldType } from "@/shared/types/common"
import ActionButtons from "@/shared/components/form/buttons-action"

import { type FormikProps, useFormik, useFormikContext } from "formik"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useEstablishmentStore } from "@/shared/api/stores/admin-service/establishmentStore"
import { useDriverStore } from "@/shared/api/stores/driverStore"
import { ModeType } from "@/shared/types/common"
import { useContractStore } from "@/shared/api/stores/admin-service/contractStore"

interface CircuitTabContentProps {
  renderField: (field: FormFieldType<Circuit>) => React.ReactNode;
  mode: ModeType;
  circuit: Circuit
  onEdit: (updatedContract: Circuit) => void
  onClose: (isSaved: boolean) => void
}

export default function CircuitTabForm({
  renderField,
  mode,
  circuit,
  onEdit,
  onClose,
}: CircuitTabContentProps) {
  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';

  const formik = useFormikContext<Circuit>();
  const { establishmentNamesAndIds, getAllEstablishmentNamesAndIds } = useEstablishmentStore();
  const { contracts, fetchContractsPage } = useContractStore();

  const { getActiveDrivers } = useDriverStore();
  const [establishmentOptions, setEstablishmentOptions] = useState<Option[]>([]);
  const [driverOptions, setDriverOptions] = useState<Option[]>([]);
  const [contractOptions, setContractOptions] = useState<Option[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      await getAllEstablishmentNamesAndIds();
      if (isEditMode) {
        await fetchContractsPage();
      }
      const drivers = await getActiveDrivers();
      setDriverOptions(drivers.map((driver) => ({
        value: driver.id.toString(),
        label: driver.name
      })));
    };
    
    fetchData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEditMode]);

  useEffect(() => {
    if (establishmentNamesAndIds.length > 0) {
      setEstablishmentOptions(establishmentNamesAndIds.map((establishment) => ({
        value: establishment.id.toString(),
        label: establishment.name
      })));
    }
  }, [establishmentNamesAndIds]);

  useEffect(() => {
    if (contracts.length > 0 && isEditMode) {
      setContractOptions(contracts.map((contract) => ({
        value: contract.contractCode,
        label: contract.contractCode
      })));
    }
  }, [contracts, isEditMode]);

  useEffect(() => {
    const selectedContractCode = formik.values.contractCode;
    if (selectedContractCode && contracts.length > 0) {
      const selectedContract = contracts.find(contract => contract.contractCode === selectedContractCode);
      if (selectedContract) {
        formik.setFieldValue('lotNumber', selectedContract.lotNumber);
      }
    }
  }, [formik.values.contractCode, contracts]);

  const formFields = getFormFieldsCircuit(establishmentOptions, driverOptions, contractOptions)
  
  const memoizedFormFields = useMemo(() => {
    return (
      <>
        {formFields.map((field) => {
          if ((field.name === 'lotNumber' || field.name === 'contractCode') && !isEditMode) {
            return null;
          }

          return (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          );
        })}
      </>
    )
  }, [formFields, renderField, isEditMode])

  return (
    <form onSubmit={formik.handleSubmit}>
      <ConditionalComponent isValid={isReadOnly}>
        <Stack flexGrow={0} direction="row" justifyContent="flex-end">
          <CustomTooltip title="edit Circuit" arrow>
            <IconButton onClick={() => onEdit(circuit)} 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={() => {
                formik.validateForm().then((errors) => {
                    formik.submitForm()
                })
              }}
              onCancel={() => onClose(false)}
              mode={isEditMode ? "edit" : ""}
            />
          </Grid>
        </ConditionalComponent>
      </Grid>
    </form>
  )
}
