/* eslint-disable react/prop-types */
/* eslint-disable react/display-name */
import { Dropdown } from "@fluentui/react";
import { Keys, t } from "Localization";
import React, { useEffect } from "react";
import { Subscription } from "../../../../../../Contracts/DataModels";
import { useSubscriptions } from "../../../../../../hooks/useSubscriptions";
import { userContext } from "../../../../../../UserContext";
import { useCopyJobContext } from "../../../../Context/CopyJobContext";
import FieldRow from "../../Components/FieldRow";

interface SubscriptionDropdownProps {}

export const SubscriptionDropdown: React.FC<SubscriptionDropdownProps> = React.memo(() => {
  const { copyJobState, setCopyJobState } = useCopyJobContext();
  const subscriptions: Subscription[] = useSubscriptions();

  const updateCopyJobState = (newSubscription: Subscription) => {
    setCopyJobState((prevState) => {
      if (prevState.target?.subscription?.subscriptionId !== newSubscription.subscriptionId) {
        return {
          ...prevState,
          target: {
            ...prevState.target,
            subscription: newSubscription,
            account: null,
          },
        };
      }
      return prevState;
    });
  };

  useEffect(() => {
    if (subscriptions && subscriptions.length > 0) {
      const currentSubscriptionId = copyJobState?.target?.subscription?.subscriptionId;
      const predefinedSubscriptionId = userContext.subscriptionId;
      const selectedSubscriptionId = currentSubscriptionId || predefinedSubscriptionId;

      const targetSubscription: Subscription | null =
        subscriptions.find((sub) => sub.subscriptionId === selectedSubscriptionId) || null;

      if (targetSubscription) {
        updateCopyJobState(targetSubscription);
      }
    }
  }, [subscriptions?.length]);

  const subscriptionOptions =
    subscriptions?.map((sub) => ({
      key: sub.subscriptionId,
      text: sub.displayName,
      data: sub,
    })) || [];

  const handleSubscriptionChange = (_ev?: React.FormEvent, option?: (typeof subscriptionOptions)[0]) => {
    const selectedSubscription = option?.data as Subscription;

    if (selectedSubscription) {
      updateCopyJobState(selectedSubscription);
    }
  };

  const selectedSubscriptionId = copyJobState?.target?.subscription?.subscriptionId;

  return (
    <FieldRow label={t(Keys.containerCopy.selectAccount.subscriptionDropdownLabel)}>
      <Dropdown
        placeholder={t(Keys.containerCopy.selectAccount.subscriptionDropdownPlaceholder)}
        ariaLabel={t(Keys.containerCopy.selectAccount.subscriptionDropdownLabel)}
        data-test="subscription-dropdown"
        options={subscriptionOptions}
        required
        selectedKey={selectedSubscriptionId}
        onChange={handleSubscriptionChange}
      />
    </FieldRow>
  );
});
