"use client";
import { useRouter } from "next/navigation";
import React, {
  useCallback,
  useEffect,
  useState,
} from "react";
import { useTranslation } from "react-i18next";
import {
  Button,
  Stack,
  Typography,
} from "@mui/material";
import {
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
} from "react-hook-form";
import { Check, Close, RestartAlt } from "@mui/icons-material";
import {
  WarehouseInputs,
  createWarehouse,
} from "@/app/api/warehouse/actions";
import WarehouseDetail from "./WarehouseDetail";

const CreateWarehouse: React.FC = () => {
  const { t } = useTranslation(["warehouse", "common"]);
  const formProps = useForm<WarehouseInputs>();
  const router = useRouter();
  const [serverError, setServerError] = useState("");

  const resetForm = React.useCallback((e?: React.MouseEvent<HTMLButtonElement>) => {
    e?.preventDefault();
    e?.stopPropagation();
    try {
      formProps.reset({
        store_id: "",
        warehouse: "",
        area: "",
        slot: "",
        order: "",
        stockTakeSection: "",
        stockTakeSectionDescription: "",
      });
    } catch (error) {
      console.log(error);
      setServerError(t("An error has occurred. Please try again later."));
    }
  }, [formProps, t]);

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

  const handleCancel = () => {
    router.back();
  };

  const onSubmit = useCallback<SubmitHandler<WarehouseInputs>>(
    async (data) => {
      try {
        // Automatically append "F" to store_id if not already present
        // Remove any existing "F" to avoid duplication, then append it
        const cleanStoreId = (data.store_id || "").replace(/F$/i, "").trim();
        const storeIdWithF = cleanStoreId ? `${cleanStoreId}F` : "";
        
        // Generate code, name, description from the input fields
        // Format: store_idF-warehouse-area-slot (F is automatically appended)
        const code = storeIdWithF 
          ? `${storeIdWithF}-${data.warehouse || ""}-${data.area || ""}-${data.slot || ""}`
          : `${data.warehouse || ""}-${data.area || ""}-${data.slot || ""}`;
        const name = storeIdWithF 
          ? `${storeIdWithF}-${data.warehouse || ""}`
          : `${data.warehouse || ""}`;
        const description = storeIdWithF 
          ? `${storeIdWithF}-${data.warehouse || ""}`
          : `${data.warehouse || ""}`;
        
        const warehouseData: WarehouseInputs = {
          ...data,
          store_id: storeIdWithF, // Save with F (F is automatically appended)
          code: code.trim(),
          name: name.trim(),
          description: description.trim(),
          capacity: 10000, // Default capacity
        };

        await createWarehouse(warehouseData);
        router.replace("/settings/warehouse");
      } catch (e) {
        console.log(e);
        const message = e instanceof Error ? e.message : t("An error has occurred. Please try again later.");
        setServerError(message);
      }
    },
    [router, t],
  );

  const onSubmitError = useCallback<SubmitErrorHandler<WarehouseInputs>>(
    (errors) => {
      console.log(errors);
    },
    [],
  );

  return (
    <>
      {serverError && (
        <Typography variant="body2" color="error" alignSelf="flex-end">
          {serverError}
        </Typography>
      )}
      <FormProvider {...formProps}>
        <Stack
          spacing={2}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
        >
          <WarehouseDetail />
          <Stack direction="row" justifyContent="flex-end" gap={1}>
            <Button
              variant="text"
              startIcon={<RestartAlt />}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                resetForm(e);
              }}
              type="button"
            >
              {t("Reset")}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Close />}
              onClick={handleCancel}
              type="button"
            >
              {t("Cancel")}
            </Button>
            <Button variant="contained" startIcon={<Check />} type="submit">
              {t("Confirm")}
            </Button>
          </Stack>
        </Stack>
      </FormProvider>
    </>
  );
};
export default CreateWarehouse;
