"use client"
import { Grid, Box, Typography, FormHelperText } from "@mui/material"
import { FormikTouched, useFormik } from "formik"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType, TableColumn } from "@/shared/types/common"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import ActionButtons from "@/shared/components/form/buttons-action"
import { type SectorList, type Address, type SectorRequest, mapSectorToSectorRequest, AgencyChildren, MapAddresse } from "@/shared/types/infrastructure"
import FormContainer from "@/layouts/form/form-container"
import { mainSectorConsultFormFields } from "../utils/sector-form-fields"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import TabbedForm from "@/shared/components/tabs/tabbed-form"
import { useSnackbar } from "notistack"
import { useInfrastructureStore } from "@/shared/api/stores/admin-service/infrastructureStore"
import { useEffect, useState, useCallback, useRef, useMemo } from "react"
import { sectorSchema } from "../utils/sector-validation"
import { getFormatedAddress } from "../../utils/address-utils"
import dayjs from "dayjs"
interface SectorFormProps {
  sector: SectorList
  mode: ModeType
  onEdit: (sector: SectorList) => void
  onClose: (forceClose: boolean) => void
  tableHead?: TableColumn[]
  updateTabContent: (tabId: string, content: any) => void
  tabId: string
  markTabAsSaved?: (tabId: string, content: any) => void
  tabContent?: SectorList
}

export default function SectorForm({
  sector,
  mode,
  onEdit,
  onClose,
  tableHead = [],
  updateTabContent,
  tabId,
  markTabAsSaved,
  tabContent
}: SectorFormProps) {
  const isReadOnly = mode === "view"

  const { enqueueSnackbar } = useSnackbar();

  const [sectorFormData, setSectorFormData] = useState<SectorRequest>({} as SectorRequest);
  const [agencies, setAgencies] = useState<AgencyChildren[]>([]);
  const [nameAvailability, setNameAvailability] = useState<{ message: string, isAvailable: boolean } | null>(null);
  const previousFormDataRef = useRef<SectorRequest | null>(null);

  const {
    error,
    clearError,
    sectorById,
    getSectorById,
    createSector,
    updateSector,
    existsSectorByNameLoading,
    existsSectorByName
  } = useInfrastructureStore();

  const handleFormSubmit = async (values: SectorRequest) => {
    if (nameAvailability != null && !nameAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer un nom valide !', { variant: 'error' });
      return;
    }
    const request = {
      ...values,
      address: values.mapAddresse ? getFormatedAddress(values.mapAddresse) : undefined
    };
    if (mode === 'add' || mode === 'copy') {
      try {
        await createSector(request);
        enqueueSnackbar('Secteur créé avec succès', { variant: 'success' });
        // Pour le mode création, on retourne à la liste car on ne peut pas rester sans ID
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        clearError();
        return;
      }
    } else if (mode === 'edit') {
      if (!sector?.id) {
        enqueueSnackbar('Erreur: ID du secteur manquant', { variant: 'error' });
        return;
      }
      try {
        await updateSector(sector.id, request);
        enqueueSnackbar('Secteur modifié avec succès', { variant: 'success' });
        // Rester dans le formulaire en mode "view" au lieu de retourner à la liste
        if (markTabAsSaved) {
          // Recharger les données complètes pour avoir le bon format
          const fullSectorData = await getSectorById(sector.id);
          if (fullSectorData) {
            markTabAsSaved(tabId, fullSectorData);
          } else {
            onClose(true);
          }
        } else {
          onClose(true);
        }
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        clearError();
        return;
      }
    }
  };

  // Use tab content directly if available, otherwise use form data
  const initialValues = useMemo(() => {
    if (tabContent && typeof tabContent === 'object' && (tabContent as any).description) {
      // Use form values from tab content (stored during editing)
      return {
        id: (tabContent as any).id || '',
        name: (tabContent as any).name || '',
        description: (tabContent as any).description || '',
        mapAddresse: (tabContent as any).mapAddresse
      } as SectorRequest;
    }
    return sectorFormData;
  }, [tabContent, sectorFormData]);

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

  const getInitialValues = async () => {
    if (sector.id && mode !== 'add') {
      const sectorData = await getSectorById(sector.id);
      if (sectorData) {
        const mappedData = mapSectorToSectorRequest(sectorData);
        setSectorFormData(mappedData);
        setAgencies(sectorData?.agencies || []);
      }
    }
  }

  // Load data from API when needed
  useEffect(() => {
    if (!tabContent && mode !== 'add' && sector.id) {
      getInitialValues();
    }
  }, [sector.id, mode, tabContent]);

  // Use tab content if available, otherwise use form data
  useEffect(() => {
    if (tabContent && typeof tabContent === 'object') {
      // Only load from API if tabContent doesn't have form values (description)
      // If tabContent has description, it means it contains form values saved during editing
      if (tabContent.id && mode !== 'add' && !(tabContent as any).description) {
        getSectorById(tabContent.id).then((sectorData) => {
          if (sectorData) {
            const mappedData = mapSectorToSectorRequest(sectorData);
            setSectorFormData(mappedData);
            setAgencies(sectorData?.agencies || []);
          }
        });
      }
      previousFormDataRef.current = null; // Reset the ref
    } else if (mode === 'add' || (sector.id && Object.keys(sectorFormData).length === 0)) {
      getInitialValues();
      previousFormDataRef.current = null; // Reset the ref
    }
  }, [sector.id, mode, tabContent]);





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

  // Update formik when sectorFormData is loaded from API or when tabContent changes
  useEffect(() => {
    if (tabContent && typeof tabContent === 'object' && (tabContent as any).description) {
      // Tab content has form values, use them directly
      const formValues = {
        id: (tabContent as any).id || '',
        name: (tabContent as any).name || '',
        description: (tabContent as any).description || '',
        mapAddresse: (tabContent as any).mapAddresse
      } as SectorRequest;
      formik.setValues(formValues);
    } else if (sectorFormData && Object.keys(sectorFormData).length > 0 && mode !== 'add') {
      formik.setValues(sectorFormData);
    }
  }, [sectorFormData, tabContent]);

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

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

  const nameTimeoutRef = 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 existsSectorByName(trimmedName, Number(sector.id))
            : await existsSectorByName(trimmedName);

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

      verifyName();
    }, 500);
  }, [mode, sector.id, existsSectorByName]);

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

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

  const renderField = (field: FormFieldType<SectorRequest>) => (
    <>
      <FormField
        field={field}
        value={formik.values[field.name as keyof SectorRequest]}
        onChange={(name, value) => {
          formik.setFieldValue(name, value);
          if (field.name === 'name') {
            checkName(value);
          }
        }}
        error={
          formik.touched[field.name as keyof SectorRequest]
            ? (formik.errors[field.name as keyof SectorRequest] as string | undefined)
            : undefined
        }
        onBlur={formik.handleBlur}
        isReadOnly={isReadOnly}
      />
      <ConditionalComponent isValid={field.name === 'name'}>
        <FormHelperText
          sx={{
            color: existsSectorByNameLoading ? 'text.secondary' : (nameAvailability?.isAvailable ? 'success.main' : 'error.main'),
            marginTop: '4px',
            display: 'flex',
            alignItems: 'center'
          }}
        >
          <ConditionalComponent isValid={existsSectorByNameLoading}>
            <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={!existsSectorByNameLoading}>
            {nameAvailability?.message}
          </ConditionalComponent>
        </FormHelperText>
      </ConditionalComponent>
    </>
  )

  const tabs = [
    {
      label: "Agences",
      content: (
        <Box
          sx={{
            borderRadius: "8px",
            width: "100%",
            marginTop: "20px",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Box
            sx={{
              display: "flex",
              backgroundColor: "#f0f0fa",
              padding: "16px",
              borderRadius: "8px",
              width: "100%",
            }}
          >
            <Typography
              variant="subtitle2"
              sx={{
                width: "20%",
                fontWeight: 500,
                color: "#6b7280",
              }}
            >
              {"Nom de l'agence"}
            </Typography>
            <Typography
              variant="subtitle2"
              sx={{
                width: "20%",
                fontWeight: 500,
                color: "#6b7280",
              }}
            >
              Adresse
            </Typography>
            <Typography
              variant="subtitle2"
              sx={{
                width: "20%",
                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",
            }}
          >
            {agencies?.map((agency) => (
              <Box
                key={agency.id}
                sx={{
                  color: "black",
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  padding: "12px",
                  borderRadius: "8px",
                  backgroundColor: "#f0f0fa",
                  marginBottom: "8px",
                  width: "100%",
                }}
              >
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    width: "100%",
                  }}
                >
                  <Typography variant="body1" sx={{ width: "20%" }}>
                    {agency.name}
                  </Typography>
                  <Typography variant="body1" sx={{ width: "20%" }}>
                    {agency.address?.street + " " + agency.address?.zipCode + " " + agency.address?.city + " " + agency.address?.country}
                  </Typography>
                  <Typography variant="body1" sx={{ width: "20%" }}>
                    {dayjs(agency.createdAt || '').format('DD-MM-YYYY HH:mm')}
                  </Typography>
                  <Typography variant="body2" sx={{ width: "40%", marginLeft: "5px" }}>
                    {agency.description}
                  </Typography>
                </Box>
              </Box>
            ))}
          </Box>
        </Box>
      ),
    },
  ]

  return (
    <FormContainer titre="Fiche Secteur">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(sector)}
          tooltipTitle="Secteur"
          dataRow={formik.values}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={3}>
          {mainSectorConsultFormFields.map((field) => (
            <Grid item xs={12} sm={6} key={field.name}>
              {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 SectorRequest] = true;
                        return acc;
                      }, {} as FormikTouched<SectorRequest>)
                    );
                  }
                });
              }}
              onCancel={() => onClose(false)}
              mode={mode} />
          </Grid>
        </ConditionalComponent>
      </form>
    </FormContainer>
  )
}
