"use client"
import { Grid, Box, Typography } 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 } from "react"
import { sectorSchema } from "../utils/sector-validation"
import { getFormatedAddress } from "../../utils/address-utils"
import dayjs from "dayjs"
interface SectorFormProps {
  sector: SectorList
  mode: ModeType
  onClose: (forceClose: boolean) => void
  tableHead?: TableColumn[]
  updateTabContent: (tabId: string, content: any) => void
  tabId: string
}

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

  const { enqueueSnackbar } = useSnackbar();

  const sectorId = sector.id;

  const [sectorData, setSectorData] = useState<SectorRequest>();
  const [agencies, setAgencies] = useState<AgencyChildren[]>([]);

  const { sectorById, getSectorById, createSector, updateSector } = useInfrastructureStore();

  useEffect(() => {
    if (sectorId) {
      getSectorById(sectorId);
    }
  }, [sectorId]);

  useEffect(() => {
    if (sectorById) {
      setSectorData(mapSectorToSectorRequest(sectorById));
      setAgencies(sectorById?.agencies || []);
    }
  }, [sectorById]);

  const handleFormSubmit = (values: SectorRequest) => {
    const request = {
      ...values,
      address: getFormatedAddress(values.mapAddresse)
    };
    if (mode === 'add' || mode === 'copy') {
      try {
        createSector(request);
        enqueueSnackbar('Secteur créé avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'edit') {
      try {
        updateSector(sectorId, request);
        enqueueSnackbar('Secteur modifié avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

  const formik = useFormik<SectorRequest>({
    initialValues: sectorData || {
      id: '',
      name: '',
      description: '',
      mapAddresse: {
        address: '',
        lat: 0,
        lng: 0,
        city: '',
        postalCode: '',
        country: '',
        formattedAddress: '',
        placeId: ''
      }
    },
    validationSchema: sectorSchema,
    onSubmit: handleFormSubmit,
    enableReinitialize: true,
  })

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<SectorRequest>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof SectorRequest]}
      onChange={(name, value) => formik.setFieldValue(name, 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}
    />
  )

  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={() => void 0}
          onExport={() => void 0}
          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>
  )
}
