"use client"

import { useEffect, useState, useCallback, useRef, useMemo } from "react"
import { Grid, Box, Typography, IconButton, useTheme, FormHelperText } from "@mui/material"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import FontAwesome from "@/shared/components/fontawesome"
import { DepartmentList, LotList, LotRequest, mapDepartmentToDepartmentRequest, type DepartmentRequest, type Lot, type LotChildren } from "@/shared/types/infrastructure";
import FormField from "@/shared/components/form/form-field"
import { TableType, type FormFieldType, type ModeType, type TableColumn } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import { FormikTouched, useFormik } from "formik"
import { mainDepartmentFormFields } from "../utils/department-form-fields"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import TabbedForm from "@/shared/components/tabs/tabbed-form"
import { PopupForm } from "../../pop-up"
import LotForm from "../../lot/view/lot-form"
import { useSnackbar } from "notistack"
import { useInfrastructureStore } from "@/shared/api/stores/admin-service/infrastructureStore"
import { getFormatedAddress } from "../../utils/address-utils"
import ActionButtons from "@/shared/components/form/buttons-action"
import { departmentSchema } from "../utils/department-validation"
import dayjs from "dayjs"
import { TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { INITIAL_LOT_DATA } from "../../lot/view/lot-list-view"
import ColorPickerInput from '../components/ColorPickerInput';
import { useZoneStore } from "@/shared/api/stores/admin-service/zoneStore"
import { DEPARTMENT_COLOR_OPTIONS } from "../utils/department-color-options"

interface DepartmentFormProps {
  department: DepartmentList
  mode: ModeType
  onEdit: (department: DepartmentList) => void
  onClose: (forceClose: boolean) => void
  tableHead?: TableColumn[]
  updateTabContent: (tabId: string, content: any) => void
  tabId: string
  markTabAsSaved?: (tabId: string, content: any) => void
  tabContent?: DepartmentList
}

export default function DepartmentForm({
  department,
  mode,
  onEdit,
  onClose,
  tableHead = [],
  updateTabContent,
  tabId,
  markTabAsSaved,
  tabContent
}: DepartmentFormProps) {

  const isReadOnly = mode === "view"
  const [isPopUpOpen, setIsPopUpOpen] = useState(false)

  const { enqueueSnackbar } = useSnackbar();

  const [departmentFormData, setDepartmentFormData] = useState<DepartmentRequest>({} as DepartmentRequest);
  const [lots, setLots] = useState<LotChildren[]>([]);
  const [selectedLot, setSelectedLot] = useState<LotChildren | null>(null);
  const [agencyOptions, setAgencyOptions] = useState<{ value: string, label: string }[]>([]);
  const [zoneOptions, setZoneOptions] = useState<{ value: string, label: string }[]>([]);
  const [nameAvailability, setNameAvailability] = useState<{ message: string, isAvailable: boolean } | null>(null);
  const [codeAvailability, setCodeAvailability] = useState<{ message: string, isAvailable: boolean } | null>(null);
  const [hexColorAvailability, setHexColorAvailability] = useState<{ message: string, isAvailable: boolean } | null>(null);
  const [allDepartmentColors, setAllDepartmentColors] = useState<string[]>([]);
  const previousFormDataRef = useRef<DepartmentRequest | null>(null);

  const {
    error,
    clearError,
    getDepartmentById,
    createDepartment,
    updateDepartment,
    agencyNames,
    fetchAgencyNames,
    existsDepartmentByCodeLoading,
    existsDepartmentByName,
    existsDepartmentByNameLoading,
    existsDepartmentByCode,
    existsDepartmentByHexColorLoading,
    existsDepartmentByHexColor,
    getAllDepartmentColors
  } = useInfrastructureStore();

  const {
    zoneNames,
    fetchZoneNames
  } = useZoneStore();

  useEffect(() => {
    fetchAgencyNames();
    fetchZoneNames();
    const fetchAllColors = async () => {
      const allColors = await getAllDepartmentColors();
      setAllDepartmentColors(allColors);
    }
    fetchAllColors();
  }, []);

  const getInitialValues = async () => {
    if (department.id && mode !== 'add') {
      const departmentData = await getDepartmentById(department.id);
      if (departmentData) {
        const mappedData = mapDepartmentToDepartmentRequest(departmentData);
        setDepartmentFormData(mappedData);
        setLots(departmentData?.lots || []);
      }
    }
  }

  useEffect(() => {
    if (tabContent && typeof tabContent === 'object') {
      const hasAgencyId = 'agencyId' in tabContent;
      const hasZoneId = 'zoneId' in tabContent;
      const hasMapAddresse = 'mapAddresse' in tabContent;
      
      if (hasAgencyId && hasZoneId && hasMapAddresse) {
        setDepartmentFormData(tabContent as DepartmentRequest);
        if (tabContent.id) {
          getDepartmentById(tabContent.id).then((departmentData) => {
            if (departmentData) {
              setLots(departmentData?.lots || []);
            }
          });
        }
      } else {
        const mappedData: DepartmentRequest = {
          id: tabContent.id,
          name: tabContent.name,
          code: tabContent.code,
          description: tabContent.description,
          hexColor: tabContent.hexColor,
          agencyId: '',
          zoneId: '',
          mapAddresse: undefined
        };
        setDepartmentFormData(mappedData);
        if (tabContent.id) {
          getDepartmentById(tabContent.id).then((departmentData) => {
            if (departmentData) {
              setLots(departmentData?.lots || []);
              const fullData = mapDepartmentToDepartmentRequest(departmentData);
              setDepartmentFormData(fullData);
            }
          });
        }
      }
      previousFormDataRef.current = null;
    } else if (mode === 'add' || (department.id && Object.keys(departmentFormData).length === 0)) {
      getInitialValues();
      previousFormDataRef.current = null;
    }
  }, [department.id, mode, tabContent]);

  useEffect(() => {
    if (agencyNames) {
      setAgencyOptions(agencyNames.map((agency) => ({ value: agency.id.toString(), label: agency.name })));
    }
  }, [agencyNames]);

  useEffect(() => {
    if (zoneNames) {
      setZoneOptions(zoneNames.map((zone) => ({ value: zone.id.toString(), label: zone.name })));
    }
  }, [zoneNames]);

  const handleFormSubmit = (values: DepartmentRequest) => {
    if (nameAvailability != null && !nameAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer un nom valide !', { variant: 'error' });
      return;
    }
    if (codeAvailability != null && !codeAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer un code valide !', { variant: 'error' });
      return;
    }
    if (hexColorAvailability != null && !hexColorAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer une couleur valide !', { variant: 'error' });
      return;
    }
    const request = {
      ...values,
      address: values.mapAddresse ? getFormatedAddress(values.mapAddresse) : undefined
    };
    if (mode === 'add' || mode === 'copy') {
      try {
        createDepartment(request).then(() => {
          enqueueSnackbar('Département créé avec succès', { variant: 'success' });
          onClose(true);
        });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        clearError();
        return;
      }
    } else if (mode === 'edit') {
      if (!department?.id) {
        enqueueSnackbar('Erreur: ID du département manquant', { variant: 'error' });
        return;
      }
      try {
        updateDepartment(department.id, request).then(async () => {
          enqueueSnackbar('Département modifié avec succès', { variant: 'success' });
          if (markTabAsSaved) {
            const fullDepartmentData = await getDepartmentById(department.id);
            if (fullDepartmentData) {
              markTabAsSaved(tabId, fullDepartmentData);
            } else {
              onClose(true);
            }
          } else {
            onClose(true);
          }
        });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        clearError();
        return;
      }
    }
  };

  const initialValues = useMemo(() => {
    if (tabContent && typeof tabContent === 'object') {
      if ('agencyId' in tabContent && 'zoneId' in tabContent && 'mapAddresse' in tabContent) {
        return tabContent as DepartmentRequest;
      }
    }
    return departmentFormData;
  }, [tabContent, departmentFormData]);

  const formik = useFormik<DepartmentRequest>({
    initialValues: initialValues,
    validationSchema: departmentSchema,
    onSubmit: handleFormSubmit,
    enableReinitialize: true,
  })

  useEffect(() => {
    if (mode === 'add') {
      setDepartmentFormData({} as DepartmentRequest);
      formik.resetForm();
    }
  }, [mode]);

  const resolveRequired = (
    required: boolean | ((values: DepartmentRequest) => boolean) | undefined,
    formData?: DepartmentRequest
  ): boolean => {
    if (typeof required === 'function' && formData) {
      return required(formData);
    }
    return !!required;
  };

  const nameTimeoutRef = useRef<NodeJS.Timeout>();
  const codeTimeoutRef = useRef<NodeJS.Timeout>();
  const hexColorTimeoutRef = useRef<NodeJS.Timeout>();

  const checkName = useCallback((name: string) => {
    if (nameTimeoutRef.current) {
      clearTimeout(nameTimeoutRef.current);
    }

    if (!name) {
      setNameAvailability(null);
      return;
    }

    const trimmedName = name.trim();
    if (trimmedName === '') {
      setNameAvailability(null);
      return;
    }

    nameTimeoutRef.current = setTimeout(() => {
      const verifyName = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsDepartmentByName(trimmedName, Number(department.id))
            : await existsDepartmentByName(trimmedName);

          setNameAvailability({
            message: exists ? 'Le nom existe déjà' : 'Le nom est disponible',
            isAvailable: !exists
          });
        } catch (error) {
          setNameAvailability(null);
        }
      };

      verifyName();
    }, 500);
  }, [mode, department.id, existsDepartmentByName]);

  const checkCode = useCallback((code: string) => {
    if (codeTimeoutRef.current) {
      clearTimeout(codeTimeoutRef.current);
    }

    if (!code) {
      setCodeAvailability(null);
      return;
    }

    const trimmedCode = code.trim();
    if (trimmedCode === '') {
      setCodeAvailability(null);
      return;
    }

    codeTimeoutRef.current = setTimeout(() => {
      const verifyCode = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsDepartmentByCode(trimmedCode, Number(department.id))
            : await existsDepartmentByCode(trimmedCode);

          setCodeAvailability({
            message: exists ? 'Le code existe déjà' : 'Le code est disponible',
            isAvailable: !exists
          });
        } catch (error) {
          setCodeAvailability(null);
        }
      };

      verifyCode();
    }, 500);
  }, [mode, department.id, existsDepartmentByCode]);

  const checkHexColor = useCallback((hexColor: string) => {
    if (hexColorTimeoutRef.current) {
      clearTimeout(hexColorTimeoutRef.current);
    }

    if (!hexColor) {
      setHexColorAvailability(null);
      return;
    }

    const trimmedHexColor = hexColor.trim();
    if (trimmedHexColor === '') {
      setHexColorAvailability(null);
      return;
    }

    hexColorTimeoutRef.current = setTimeout(() => {
      const verifyHexColor = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsDepartmentByHexColor(trimmedHexColor, Number(department.id))
            : await existsDepartmentByHexColor(trimmedHexColor);

          setHexColorAvailability({
            message: exists ? 'Cette couleur est déjà utilisée par un autre département' : 'La couleur est disponible',
            isAvailable: !exists
          });
        } catch (error) {
          setHexColorAvailability(null);
        }
      };

      verifyHexColor();
    }, 500);
  }, [mode, department.id, existsDepartmentByHexColor]);

  const getAvailableDepartmentColors = () => {
    const used = new Set(allDepartmentColors.map(h => h.trim().toLowerCase()));
    return DEPARTMENT_COLOR_OPTIONS.filter(
      option => !used.has(option.hex.trim().toLowerCase())
    );
  };

  useEffect(() => {
    if (error) {
      enqueueSnackbar(error, { variant: 'error' })
      clearError()
    }
  }, [error, enqueueSnackbar, clearError])

 
  const [originalColor, setOriginalColor] = useState<string>('');

 
  useEffect(() => {
    if (mode === 'add') {
      setOriginalColor('');
      return;
    }
    
 
    setOriginalColor('');
  }, [department.id, mode]);

 
  useEffect(() => {
    if (mode === 'add') {
      return; // No original color in add mode
    }
    
    let colorToSet = '';
    
 
    if (departmentFormData.hexColor) {
      colorToSet = departmentFormData.hexColor;
    } 
 
    else if (tabContent && typeof tabContent === 'object' && 'hexColor' in tabContent && tabContent.hexColor) {
      colorToSet = tabContent.hexColor;
    }
    
    if (colorToSet) {
      setOriginalColor(colorToSet);
    }
  }, [departmentFormData.hexColor, tabContent, department.id, mode]);

  useEffect(() => {
    if (formik.values.hexColor && checkHexColor) {
      if (mode === 'edit' && !originalColor && !departmentFormData.hexColor) {
        return; 
      }
      
      const isDifferentFromOriginal = originalColor && 
        formik.values.hexColor.trim().toLowerCase() !== originalColor.trim().toLowerCase();
      
      if (mode === 'add' || (mode === 'edit' && isDifferentFromOriginal)) {
        checkHexColor(formik.values.hexColor);
      } else if (mode === 'edit' && !isDifferentFromOriginal && originalColor) {
        setHexColorAvailability(null);
      }
    }
  }, [formik.values.hexColor, checkHexColor, mode, originalColor, departmentFormData.hexColor])

  const renderField = (field: FormFieldType<DepartmentRequest>) => {
    const handleChangeHexColor = (value: any) => {
      formik.setFieldValue('hexColor', value);
      if (field.name === 'hexColor') {
        checkHexColor(value);
      }
    };
    if (field.name === 'hexColor') {
      const originalColorFromTabContent = tabContent && typeof tabContent === 'object' && 'hexColor' in tabContent 
        ? (tabContent as any).hexColor 
        : '';
      const currentOriginalColor = originalColor || departmentFormData.hexColor || originalColorFromTabContent;
      const normalizedOriginalColor = currentOriginalColor ? currentOriginalColor.trim().toLowerCase() : '';
      
      const normalizedAllColors = allDepartmentColors
        .map(color => color.trim().toLowerCase())
        .filter(color => color !== '');
      
      const usedColors = mode === 'edit' && normalizedOriginalColor
        ? normalizedAllColors.filter(color => color !== normalizedOriginalColor)
        : normalizedAllColors;

      return (
        <>
          <ColorPickerInput
            key={field.name}
            options={DEPARTMENT_COLOR_OPTIONS}
            usedColors={usedColors}
            value={formik.values.hexColor}
            onChange={handleChangeHexColor}
            disabled={isReadOnly}
            label={field.label}
            required={resolveRequired(field.required, formik.values)}
            error={formik.touched.hexColor ? (formik.errors.hexColor as string) : undefined}
            touched={formik.touched.hexColor}
          />
          <FormHelperText
            sx={{
              color: existsDepartmentByHexColorLoading ? 'text.secondary' : (hexColorAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsDepartmentByHexColorLoading}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Box
                  sx={{
                    width: '16px',
                    height: '16px',
                    border: '2px solid #f3f3f3',
                    borderTop: '2px solid #746CD4',
                    borderRadius: '50%',
                    animation: 'spin 1s linear infinite',
                    marginRight: '8px',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' }
                    }
                  }}
                />
                <Typography sx={{ color: '#746CD4' }}>
                  Vérification en cours...
                </Typography>
              </Box>
            </ConditionalComponent>
            <ConditionalComponent isValid={!existsDepartmentByHexColorLoading}>
              {hexColorAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </>
      );
    }
    return (
      <>
        <FormField
          field={field}
          value={formik.values[field.name as keyof DepartmentRequest]}
          onChange={(name, value) => {
            formik.setFieldValue(name, value);
            if (field.name === 'name') {
              checkName(value);
            }
            if (field.name === 'code') {
              checkCode(value);
            }
          }}
          error={
            formik.touched[field.name as keyof DepartmentRequest]
              ? (formik.errors[field.name as keyof DepartmentRequest] as string)
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={field.name === 'agencyId' ? (mode === 'view' || mode === 'edit') : isReadOnly}
        />
        <ConditionalComponent isValid={field.name === 'name'}>
          <FormHelperText
            sx={{
              color: existsDepartmentByNameLoading ? 'text.secondary' : (nameAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsDepartmentByNameLoading}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Box
                  sx={{
                    width: '16px',
                    height: '16px',
                    border: '2px solid #f3f3f3',
                    borderTop: '2px solid #746CD4',
                    borderRadius: '50%',
                    animation: 'spin 1s linear infinite',
                    marginRight: '8px',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' }
                    }
                  }}
                />
                <Typography sx={{ color: '#746CD4' }}>
                  Vérification en cours...
                </Typography>
              </Box>
            </ConditionalComponent>
            <ConditionalComponent isValid={!existsDepartmentByNameLoading}>
              {nameAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>

        <ConditionalComponent isValid={field.name === 'code'}>
          <FormHelperText
            sx={{
              color: existsDepartmentByCodeLoading ? 'text.secondary' : (codeAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsDepartmentByCodeLoading}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Box
                  sx={{
                    width: '16px',
                    height: '16px',
                    border: '2px solid #f3f3f3',
                    borderTop: '2px solid #746CD4',
                    borderRadius: '50%',
                    animation: 'spin 1s linear infinite',
                    marginRight: '8px',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' }
                    }
                  }}
                />
                <Typography sx={{ color: '#746CD4' }}>
                  Vérification en cours...
                </Typography>
              </Box>
            </ConditionalComponent>
            <ConditionalComponent isValid={!existsDepartmentByCodeLoading}>
              {codeAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>
      </>
    );
  };

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])

  useEffect(() => {
    return () => {
      if (nameTimeoutRef.current) {
        clearTimeout(nameTimeoutRef.current);
      }
      if (codeTimeoutRef.current) {
        clearTimeout(codeTimeoutRef.current);
      }
    };
  }, []);

  const handleAddLot = (newLot: Lot) => {
    const updatedLots = [...(lots || []), newLot]
    formik.setFieldValue("lots", updatedLots)
    setIsPopUpOpen(false)
  }


  const lotTabsConfig: TabConfig<LotList> = {
    type: TableType.Lot,
    listTitle: "Liste lots",
    newItemTitle: "Nouveau lot",
    initialData: INITIAL_LOT_DATA,
    getItemCode: (lot) => lot.id,
  }

  const {
    handleEdit,
  } = useTabsManager<LotList>(lotTabsConfig)

  const tabs = [
    {
      label: "Lot",
      content: (
        <Box
          sx={{
            borderRadius: "8px",
            width: "100%",
            marginTop: "20px",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Box
            sx={{
              display: "flex",
              justifyContent: "flex-end",
              width: "60%",
              margin: "0 auto 10px auto",
            }}
          >
            <ConditionalComponent isValid={!isReadOnly}>
              <IconButton
                color="inherit"
                sx={{
                  p: "4px",
                  backgroundColor: "#746CD4",
                  color: "white",
                  "&:hover": { backgroundColor: "#F0F0FA", color: "#746CD4" },
                }}
                aria-label="add"
                onClick={() => setIsPopUpOpen(true)}
              >
                <FontAwesome icon={faPlus} width={16} />
              </IconButton>
            </ConditionalComponent>
          </Box>

          <Box
            sx={{
              borderRadius: "8px",
              width: "100%",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            <Box
              sx={{
                display: "flex",
                backgroundColor: "#f0f0fa",
                padding: "16px",
                borderRadius: "8px",
                width: "60%",
              }}
            >
              <Typography
                variant="subtitle2"
                sx={{
                  width: "30%",
                  fontWeight: 500,
                  color: "#6b7280",
                }}
              >
                Numero Lot
              </Typography>
              <Typography
                variant="subtitle2"
                sx={{
                  width: "30%",
                  fontWeight: 500,
                  color: "#6b7280",
                }}
              >
                Date de création
              </Typography>
              <Typography
                variant="subtitle2"
                sx={{
                  width: "40%",
                  fontWeight: 500,
                  color: "#6b7280",
                }}
              >
                Description
              </Typography>
            </Box>

            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                width: "100%",
                padding: "3px",
              }}
            >
              {lots?.map((lot) => (
                <Box
                  key={lot.id}
                  sx={{
                    cursor: "pointer",
                    color: "black",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    padding: "12px",
                    borderRadius: "8px",
                    backgroundColor: "#f0f0fa",
                    border: selectedLot?.id === lot.id ? "1px solid #746CD4" : "none",
                    marginBottom: "8px",
                    width: "60%",
                  }}
                  onClick={() => setSelectedLot(lot)}
                >
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      width: "100%",
                    }}
                  >
                    <Typography variant="body1" sx={{ width: "20%" }}>
                      {lot.number}
                    </Typography>
                    <Typography variant="body1" sx={{ width: "20%" }}>
                      {dayjs(lot.createdAt || '').format('DD-MM-YYYY HH:mm')}
                    </Typography>
                    <Typography variant="body1" sx={{ width: "40%", marginLeft: "5px" }}>
                      {lot.description}
                    </Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          </Box>
        </Box>
      ),
    },
  ]

  return (
    <FormContainer>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(department)}
          tooltipTitle="Département"
          dataRow={formik.values}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid
          container
          spacing={2}
          direction="row"
          sx={{ minHeight: "100%", margin: "auto" }}
        >
          {mainDepartmentFormFields(agencyOptions, zoneOptions).map((field) => (
            <Grid item xs={12} sm={4} key={field.name} sx={{ width: "100%" }}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>

        <ConditionalComponent isValid={mode !== "add"}>
          <TabbedForm
            tabs={tabs}
            isTransparent
            sx={{
              fontWeight: "bold",
              color: "#F1F0FB",
              marginTop: "20px",
            }}
          />
        </ConditionalComponent>

        <ConditionalComponent isValid={!isReadOnly}>
          <Grid container spacing={2} justifyContent="flex-end" sx={{ mt: 3 }}>
            <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 DepartmentRequest] = true;
                        return acc;
                      }, {} as FormikTouched<DepartmentRequest>)
                    );
                  }
                });
              }}
              onCancel={() => onClose(false)}
              mode={mode} />
          </Grid>
        </ConditionalComponent>
      </form>

      <ConditionalComponent isValid={isPopUpOpen}>
        <PopupForm
          onOpen={isPopUpOpen}
          onCloseCallback={() => setIsPopUpOpen(false)}
          formContent={
            <LotForm
              lot={{} as LotList}
              onEdit={handleEdit}
              onClose={() => setIsPopUpOpen(false)}
              mode={"add"}
            />
          }
        />
      </ConditionalComponent>
    </FormContainer>
  )
}
