"use client";

import {
  M18ImportTestingForm,
  testM18ImportPo,
  M18ImportPoForm,
  testM18ImportPq,
  testM18ImportMasterData,
  testM18ImportDo,
} from "@/app/api/settings/m18ImportTesting/actions";
import { Card, CardContent, Grid, Stack, Typography, Button } from "@mui/material";
import React, {
  BaseSyntheticEvent,
  FormEvent,
  useCallback,
  useState,
} from "react";
import { FormProvider, SubmitErrorHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import M18ImportPo from "./M18ImportPo";
import M18ImportPq from "./M18ImportPq";
import { dateTimeStringToDayjs } from "@/app/utils/formatUtil";
import M18ImportMasterData from "./M18ImportMasterData";
import M18ImportDo from "./M18ImportDo";
import { PlayArrow, Refresh as RefreshIcon } from "@mui/icons-material";
import { triggerScheduler, refreshCronSchedules } from "@/app/api/settings/m18ImportTesting/actions";

interface Props {}

const M18ImportTesting: React.FC<Props> = ({}) => {
  const { t } = useTranslation("m18ImportTesting");
  const [isLoading, setIsLoading] = useState(false);
  const [loadingType, setLoadingType] = useState<string | null>(null);
  const formProps = useForm<M18ImportTestingForm>();

  const onSubmit = useCallback(
    async (data: M18ImportTestingForm, event?: BaseSyntheticEvent) => {
      console.log(isLoading);

      if (isLoading) {
        return;
      }

      const buttonId = (event?.nativeEvent as SubmitEvent).submitter?.id;
      console.log(data);
      console.log(buttonId);

      switch (buttonId) {
        case "m18ImportMasterData":
          const mdDateFrom = data.masterData.modifiedDateFrom;
          const mdDateTo = data.masterData.modifiedDateTo;
          if (!(!mdDateFrom || dateTimeStringToDayjs(mdDateFrom).isValid())) {
            formProps.setError("masterData.modifiedDateFrom", {
              message: "Invalid DateTime Format",
            });
          }

          if (!(!mdDateTo || dateTimeStringToDayjs(mdDateTo).isValid())) {
            formProps.setError("masterData.modifiedDateTo", {
              message: "Invalid DateTime Format",
            });
          }

          if (formProps.formState.errors.masterData) {
            return;
          }

          setIsLoading(() => true);
          setLoadingType(() => "Master Data");
          const mdResponse = await testM18ImportMasterData(data.masterData);
          console.log(mdResponse);
          if (mdResponse) {
            setIsLoading(() => false);
          }
          break;
        case "m18ImportPo":
          const poDateFrom = data.po.modifiedDateFrom;
          const poDateTo = data.po.modifiedDateTo;
          if (!(poDateFrom && dateTimeStringToDayjs(poDateFrom).isValid())) {
            formProps.setError("po.modifiedDateFrom", {
              message: "Invalid DateTime Format",
            });
          }

          if (!(poDateTo && dateTimeStringToDayjs(poDateTo).isValid())) {
            formProps.setError("po.modifiedDateTo", {
              message: "Invalid DateTime Format",
            });
          }

          if (formProps.formState.errors.po) {
            return;
          }

          setIsLoading(() => true);
          setLoadingType(() => "Purchase Order");
          const poResponse = await testM18ImportPo(data.po);
          console.log(poResponse);
          if (poResponse) {
            setIsLoading(() => false);
          }
          break;
        case "m18ImportDo":
          const doDateFrom = data.do.modifiedDateFrom;
          const doDateTo = data.do.modifiedDateTo;
          if (!(doDateFrom && dateTimeStringToDayjs(doDateFrom).isValid())) {
            formProps.setError("do.modifiedDateFrom", {
              message: "Invalid DateTime Format",
            });
          }

          if (!(doDateTo && dateTimeStringToDayjs(doDateTo).isValid())) {
            formProps.setError("do.modifiedDateTo", {
              message: "Invalid DateTime Format",
            });
          }

          if (formProps.formState.errors.do) {
            return;
          }

          setIsLoading(() => true);
          setLoadingType(() => "Delivery Order");
          const doResponse = await testM18ImportDo(data.do);
          console.log(doResponse);
          if (doResponse) {
            setIsLoading(() => false);
          }
          break;
        case "m18ImportPq":
          const pqDateFrom = data.pq.modifiedDateFrom;
          const pqDateTo = data.pq.modifiedDateTo;
          if (!(pqDateFrom || dateTimeStringToDayjs(pqDateFrom).isValid())) {
            formProps.setError("pq.modifiedDateFrom", {
              message: "Invalid DateTime Format",
            });
          }

          if (!(pqDateTo || dateTimeStringToDayjs(pqDateTo).isValid())) {
            formProps.setError("pq.modifiedDateTo", {
              message: "Invalid DateTime Format",
            });
          }

          if (formProps.formState.errors.pq) {
            return;
          }

          setIsLoading(() => true);
          setLoadingType(() => "Purchase Quotation");
          const pqResponse = await testM18ImportPq(data.pq);
          console.log(pqResponse);
          if (pqResponse) {
            setIsLoading(() => false);
          }
          break;
        default:
          break;
      }
    },
    [],
  );

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

  const handleManualTrigger = async (type: any) => {
      setIsLoading(true);
      setLoadingType(`Manual ${type}`);
      try {
          const result = await triggerScheduler(type);
          if (result) alert(result);
      } catch (error) {
          console.error(error);
          alert("Trigger failed. Check server logs.");
      } finally {
          setIsLoading(false);
      }
  };

  const handleRefreshSchedules = async () => {
      // Re-use the manual trigger logic which we know works
      await handleManualTrigger('refresh-cron');
  };

  return (
    <Card>
      <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
        <Typography variant="h6">{t("Manual Scheduler Triggers")}</Typography>
        <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
            <Button 
                variant="outlined" 
                startIcon={<PlayArrow />} 
                onClick={() => handleManualTrigger('po')}
                disabled={isLoading}
            >
                Trigger PO
            </Button>
            <Button 
                variant="outlined" 
                startIcon={<PlayArrow />} 
                onClick={() => handleManualTrigger('do1')}
                disabled={isLoading}
            >
                Trigger DO1
            </Button>
            <Button 
                variant="outlined" 
                startIcon={<PlayArrow />} 
                onClick={() => handleManualTrigger('do2')}
                disabled={isLoading}
            >
                Trigger DO2
            </Button>
            <Button 
                variant="outlined" 
                startIcon={<PlayArrow />} 
                onClick={() => handleManualTrigger('master-data')}
                disabled={isLoading}
            >
                Trigger Master
            </Button>
            <Button 
              variant="contained" 
              color="secondary"
              startIcon={<RefreshIcon />} 
              onClick={handleRefreshSchedules} // This now uses the logic that works
              disabled={isLoading}
          >
              Reload Cron Settings
          </Button>
        </Stack>

        <hr style={{ opacity: 0.2 }} />

        <Typography variant="overline">
          {t("Status: ")}
          {isLoading ? t(`Processing ${loadingType}...`) : t("Ready")}
        </Typography>

        <Typography variant="overline">
          {t("Status: ")}
          {isLoading ? t(`Importing ${loadingType}...`) : t("Ready to import")}
        </Typography>
        <FormProvider {...formProps}>
          <Stack
            spacing={2}
            component={"form"}
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            <Grid container columnGap={2} rowGap={2}>
              <Grid item xs={12}>
                <M18ImportMasterData />
              </Grid>
              <Grid item xs={12}>
                <M18ImportPo />
              </Grid>
              <Grid item xs={12}>
                <M18ImportDo />
              </Grid>
              <Grid item xs={12}>
                <M18ImportPq />
              </Grid>
            </Grid>
          </Stack>
        </FormProvider>
      </CardContent>
    </Card>
  );
};

export default M18ImportTesting;
