"use client"

import { useMemo } 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 { formFieldsCircuit, formFieldsCircuitContrat } from "../../utils/form-fields-circuit"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import type { ICircuit, ICircuitContract } from "@/shared/types/circuit"
import type { FormFieldType } from "@/shared/types/common"
import ActionButtons from "@/shared/components/form/buttons-action"
import { INITIAL_CONTRACT_CIRCUIT_DATA } from "@/shared/_mock/_circuit"
import FormField from "@/shared/components/form/form-field"
import { type FormikProps, useFormik } from "formik"
import { circuitContractSchema } from "../../utils/circuit-validation"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface CircuitTabContentProps {
  isReadOnly: boolean
  isEditMode: boolean
  circuit: ICircuit
  onEdit: (updatedContract: ICircuit) => void
  onClose: (isSaved: boolean) => void
  formik: FormikProps<ICircuit>
}

const regularFields = formFieldsCircuit.filter((field) => field.name !== "observation")
const specialFields = formFieldsCircuit.filter((field) => field.name === "observation")

export default function CircuitTabForm({
  isReadOnly,
  isEditMode,
  circuit,
  onEdit,
  onClose,
  formik,
}: CircuitTabContentProps) {
  const contractFormik = useFormik<ICircuitContract>({
    initialValues: INITIAL_CONTRACT_CIRCUIT_DATA,
    validationSchema: circuitContractSchema,
    onSubmit: () => {},
    enableReinitialize: true,
  })

  const memoizedFormFields = useMemo(() => {
    const renderField = (field: FormFieldType<ICircuit>) => {
      const error = formik.touched[field.name] && formik.errors[field.name]
      return (
        <FormField
          field={field}
          value={formik.values[field.name]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={
            error
              ? field.name === "adresseEtablissement"
                ? (formik.errors.adresseEtablissement as any)?.address
                : String(formik.errors[field.name])
              : undefined
          }
          isReadOnly={isReadOnly}
          onBlur={formik.handleBlur}
        />
      )
    }

    const renderFieldCircuitContrat = (field: FormFieldType<ICircuitContract>) => {
      const error = contractFormik.touched[field.name] && contractFormik.errors[field.name]
      return (
        <FormField
          field={field}
          value={contractFormik.values[field.name]}
          onChange={(name, value) => contractFormik.setFieldValue(name, value)}
          error={error ? String(contractFormik.errors[field.name]) : undefined}
          isReadOnly={isReadOnly}
          onBlur={contractFormik.handleBlur}
        />
      )
    }

    return (
      <>
        {regularFields.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
        {isEditMode &&
          formFieldsCircuitContrat.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderFieldCircuitContrat(field)}
            </Grid>
          ))}
        {specialFields.map((field) => (
          <Grid item xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </>
    )
  }, [isEditMode, isReadOnly, formik, contractFormik])

  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) => {
                  if (!isEditMode) {
                    formik.submitForm()
                  }
                  if (isEditMode) {
                    contractFormik.validateForm().then((errors) => {
                      formik.submitForm()
                      contractFormik.submitForm()
                    })
                  }
                })
              }}
              onCancel={() => onClose(false)}
              mode={isEditMode ? "edit" : ""}
            />
          </Grid>
        </ConditionalComponent>
      </Grid>
    </form>
  )
}
