import { Formik, Form } from "formik";
import BearerTypeCard from "./BearerTypeCard";
import ChannelCard from "./ChannelCard";
import type { BearerTypeFields, FormTypes, OptionalBOF2Constants } from "../../../types/types";
import { usePostBearerConfig } from "../hooks/useBearer";
import { useDispatcherConfig } from "../hooks/useDispatcherConfig";

const OutputForms = () => {
  const { bearerMutation } = usePostBearerConfig();
  const { dispatcherQuery, dispatcherMutation } = useDispatcherConfig();

  const format = dispatcherQuery?.data?.propFormat?.value;

  const inititalValues: FormTypes = {
    format: format ?? "JSON",
    enabled: true,
    backOfficeURL: "",
    username: "",
    password: "",
    connectTimeoutSeconds: Number(5),
    readTimeoutSeconds: Number(15),
    overviewQuality: "HIGH",
    cropSizeFactor: "3/4",

    // Bof2 -optional constants
    FFID: "",
    SCID: "",
    timestampSource: "UTC",
    GPSFormat: "Minutes",

    //BOF2 - optional Lane IDs
    laneId: "",
    LID1: "",
    LID2: "",
  };

  const handleSubmit = async (values: FormTypes) => {
    const bearerTypeFields = {
      format: values.format,
      enabled: values.enabled,
    };

    const bearerFields: BearerTypeFields = {
      format: values.format,
      enabled: values.enabled,
      backOfficeURL: values.backOfficeURL,
      username: values.username,
      password: values.password,
      connectTimeoutSeconds: values.connectTimeoutSeconds,
      readTimeoutSeconds: values.readTimeoutSeconds,
      overviewQuality: values.overviewQuality,
      cropSizeFactor: values.cropSizeFactor,
    };

    const result = await dispatcherMutation.mutateAsync(bearerTypeFields);

    if (result?.id) {
      await bearerMutation.mutateAsync(bearerFields);
      if (values.format === "BOF2") {
        const optionalBOF2Fields: OptionalBOF2Constants = {
          FFID: values.FFID,
          SCID: values.SCID,
          timestampSource: values.timestampSource,
          GPSFormat: values.GPSFormat,
        };
        console.log("Submit BOF2 optional fields:", optionalBOF2Fields);
      }
    }
  };

  return (
    <Formik initialValues={inititalValues} onSubmit={handleSubmit} enableReinitialize>
      <Form className="grid grid-cols-1 md:grid-cols-2">
        <BearerTypeCard />
        <ChannelCard />
      </Form>
    </Formik>
  );
};

export default OutputForms;
