"use client"

import { useEffect, useState } from "react"
import { Button, Grid, Box, Typography, IconButton } from "@mui/material"
import { faPlus } from "@fortawesome/free-solid-svg-icons"
import FontAwesome from "@/shared/components/fontawesome"
import { mapAgencyToAgencyRequest, type AgencyList, type AgencyRequest, type DepartmentChildren } from "@/shared/types/infrastructure"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType, TableColumn } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import { mainAgencyFormFields } from "../utils/form-fields-agency"
import { FormikTouched, useFormik } from "formik"
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 { useInfrastructureStore } from "@/shared/api/stores/admin-service/infrastructureStore"
import { useSnackbar } from "notistack"
import { getFormatedAddress } from "../../utils/address-utils"
import ActionButtons from "@/shared/components/form/buttons-action"
import { agencySchema } from "../utils/agency-validation"
import dayjs from "dayjs"
interface AgencyFormProps {
  agency: AgencyList
  mode: ModeType
  onClose: (forceClose: boolean) => void
  tableHead?: TableColumn[]
  updateTabContent: (tabId: string, content: any) => void
  tabId: string
}

export default function AgencyForm({
  agency,
  mode,
  onClose,
  tableHead = [],
  updateTabContent,
  tabId
}: AgencyFormProps) {
  const isReadOnly = mode === "view"

  const { enqueueSnackbar } = useSnackbar();

  const agencyId = agency.id;

  const [agencyData, setAgencyData] = useState<AgencyRequest>({} as AgencyRequest);
  const [departments, setDepartments] = useState<DepartmentChildren[]>([]);
  const [selectedDepartment, setSelectedDepartment] = useState<DepartmentChildren | null>(null);
  const [sectorOptions, setSectorOptions] = useState<{ value: string, label: string }[]>([]);

  const { agencyById, getAgencyById, createAgency, updateAgency, sectorNames, fetchSectorNames } = useInfrastructureStore();

  useEffect(() => {
    fetchSectorNames();
  }, []);

  useEffect(() => {
    if (agencyId) {
      getAgencyById(agencyId);
    }
  }, [agencyId]);

  useEffect(() => {
    if (sectorNames) {
      setSectorOptions(sectorNames.map((sector) => ({ value: sector.id.toString(), label: sector.name })));
    }
  }, [sectorNames]);

  useEffect(() => {
    if (agencyById) {
      setAgencyData(mapAgencyToAgencyRequest(agencyById));
      setDepartments(agencyById.departments);
    }
  }, [agencyById]);

  const handleFormSubmit = (values: AgencyRequest) => {
    const request = {
      ...values,
      address: getFormatedAddress(values.mapAddresse)
    };
    if (mode === 'add' || mode === 'copy') {
      try {
        createAgency(request);
        enqueueSnackbar('Agence créée avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'edit') {
      try {
        updateAgency(agencyId, request);
        enqueueSnackbar('Agence modifiée avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

  const formik = useFormik<AgencyRequest>({
    initialValues: agencyData,
    validationSchema: agencySchema,
    onSubmit: handleFormSubmit,
    enableReinitialize: true,
  })

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

  const renderField = (field: FormFieldType<AgencyRequest>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof AgencyRequest]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof AgencyRequest]
          ? (formik.errors[field.name as keyof AgencyRequest] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  )

  const tabs = [
    {
      label: "Departement",
      content: (
        <Box
          sx={{
            borderRadius: "8px",
            width: "100%",
            marginTop: "20px",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Box
            sx={{
              display: "flex",
              justifyContent: "flex-end",
              width: "80%",
              margin: "0 auto 10px auto",
            }}
          >
            <ConditionalComponent isValid={!isReadOnly}>
              <IconButton
                color="inherit"
                sx={{
                  backgroundColor: "#746CD4",
                  color: "white",
                  "&:hover": { backgroundColor: "#F0F0FA", color: "#746CD4" },
                }}
                aria-label="add"
                onClick={() => console.log("Add department")}
              >
                <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: "80%",
              }}
            >
              <Typography
                variant="subtitle2"
                sx={{
                  width: "20%",
                  fontWeight: "500",
                  color: "#6b7280",
                }}
              >
                Nom de Departement
              </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",
              }}
            >
              {departments?.map((department) => (
                <Box
                  key={department.id}
                  sx={{
                    cursor: "pointer",
                    color: "black",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    padding: "12px",
                    borderRadius: "8px",
                    backgroundColor: "#f0f0fa",
                    border: selectedDepartment?.id === department.id ? "1px solid #746CD4" : "none",
                    marginBottom: "8px",
                    width: "80%",
                  }}
                  onClick={() => setSelectedDepartment(department)}
                >
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      width: "100%",
                    }}
                  >
                    <Typography variant="body1" sx={{ width: "20%" }}>
                      {department.name}
                    </Typography>
                    <Typography variant="body1" sx={{ width: "20%" }}>
                      {department.address?.street + " " + department.address?.zipCode + " " + department.address?.city + " " + department.address?.country}
                    </Typography>
                    <Typography variant="body1" sx={{ width: "20%" }}>
                      {dayjs(department.createdAt || '').format('DD-MM-YYYY HH:mm')}
                    </Typography>
                    <Typography variant="body2" sx={{ width: "40%", marginLeft: "5px" }}>
                      {department.description}
                    </Typography>
                  </Box>
                </Box>
              ))}
            </Box>
          </Box>
        </Box>
      ),
    },
  ]

  return (
    <FormContainer >
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => void 0}
          onExport={() => void 0}
          tooltipTitle="Agence"
          dataRow={formik.values}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form
        onSubmit={formik.handleSubmit}
        style={{
          width: "100%",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          marginBottom: isReadOnly ? "0" : "11rem",
        }}
      >
        <Grid
          container
          spacing={2}
          direction="row"
        >
          {mainAgencyFormFields(sectorOptions).map((field) => (
            <Grid item xs={12} sm={4} key={field.name} sx={{ width: "100%" }}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>

        <ConditionalComponent isValid={mode === "view"}>
          <TabbedForm
            tabs={tabs}
            isTransparent
            sx={{
              fontWeight: "bold",
              color: "#F1F0FB",
              marginTop: "20px",
              width: "100%",
            }}
          />
        </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 AgencyRequest] = true;
                        return acc;
                      }, {} as FormikTouched<AgencyRequest>)
                    );
                  }
                });
              }}
              onCancel={() => onClose(false)}
              mode={mode} />
          </Grid>
        </ConditionalComponent>
      </form>
    </FormContainer>
  )
}