"use client"

import { useEffect, useState } from "react"
import { Grid, Box, Typography, IconButton } 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 type { FormFieldType, ModeType, 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"

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

export default function DepartmentForm({
  department,
  mode,
  onClose,
  tableHead = [],
  updateTabContent,
  tabId
}: DepartmentFormProps) {
  const isReadOnly = mode === "view"
  const [isPopUpOpen, setIsPopUpOpen] = useState(false)

  const { enqueueSnackbar } = useSnackbar();

  const departmentId = department.id;

  const [departmentData, setDepartmentData] = 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 { departmentById, getDepartmentById, createDepartment, updateDepartment, agencyNames, fetchAgencyNames } = useInfrastructureStore();

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

  useEffect(() => {
    if (departmentId) {
      getDepartmentById(departmentId);
    }
  }, [departmentId]);

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

  useEffect(() => {
    if (departmentById) {
      setDepartmentData(mapDepartmentToDepartmentRequest(departmentById));
      setLots(departmentById.lots);
    }
  }, [departmentById]);

  const handleFormSubmit = (values: DepartmentRequest) => {
    const request = {
      ...values,
      address: getFormatedAddress(values.mapAddresse)
    };
    if (mode === 'add' || mode === 'copy') {
      try {
        createDepartment(request);
        enqueueSnackbar('Département créé avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'edit') {
      try {
        updateDepartment(departmentId, request);
        enqueueSnackbar('Département modifié avec succès', { variant: 'success' });
        onClose(true);
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

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

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

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

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

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

  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={() => { }}
          onExport={() => void 0}
          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).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}
              onClose={() => setIsPopUpOpen(false)}
              mode={"add"}
            />
          }
        />
      </ConditionalComponent>
    </FormContainer>
  )
}
