import { useFormikContext, type FormikTouched } from "formik";
import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader";
import ChannelFields from "./ChannelFields";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { useCameraBackOfficeOutput } from "../../../hooks/useBackOfficeConfig";
import { useEffect, useMemo } from "react";

type ChannelCardProps = {
  touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
  isSubmitting: boolean;
  isBof2ConstantsLoading: boolean;
  isDispatcherLoading: boolean;
};

const ChannelCard = ({ touched, isSubmitting, isBof2ConstantsLoading, isDispatcherLoading }: ChannelCardProps) => {
  const { values, setFieldValue } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
  const { backOfficeQuery } = useCameraBackOfficeOutput(values?.format);
  const isBackOfficeQueryLoading = backOfficeQuery?.isFetching;

  const mapped = useMemo(() => {
    const d = backOfficeQuery?.data;
    return {
      backOfficeURL: d?.propBackofficeURL?.value ?? "",
      username: d?.propUsername?.value ?? "",
      password: d?.propPassword?.value ?? "",
      connectTimeoutSeconds: Number(d?.propConnectTimeoutSeconds?.value),
      readTimeoutSeconds: Number(d?.propReadTimeoutSeconds?.value),
    };
  }, [backOfficeQuery?.data]);

  useEffect(() => {
    if (!backOfficeQuery?.isSuccess) return;
    for (const [key, value] of Object.entries(mapped)) {
      setFieldValue(key, value);
    }
  }, [backOfficeQuery.isSuccess, mapped, setFieldValue]);

  return (
    <Card className="p-4 overflow-y-auto ">
      <CardHeader title={`Channel (${values?.format})`} />
      {!isBof2ConstantsLoading && !isDispatcherLoading && !isBackOfficeQueryLoading ? (
        <ChannelFields
          touched={touched}
          isSubmitting={isSubmitting}
          backOfficeData={backOfficeQuery}
          format={values?.format}
        />
      ) : (
        <>Loading...</>
      )}
    </Card>
  );
};

export default ChannelCard;
