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

interface AccountDropdownProps {}

export const normalizeAccountId = (id: string = "") => {
  if (configContext.platform === Platform.Portal) {
    return id.replace("/Microsoft.DocumentDb/", "/Microsoft.DocumentDB/");
  } else if (configContext.platform === Platform.Hosted) {
    return id.replace("/Microsoft.DocumentDB/", "/Microsoft.DocumentDb/");
  } else {
    return id;
  }
};

export const AccountDropdown: React.FC<AccountDropdownProps> = () => {
  const { copyJobState, setCopyJobState } = useCopyJobContext();

  const selectedSubscriptionId = copyJobState?.target?.subscription?.subscriptionId;
  const allAccounts: DatabaseAccount[] = useDatabaseAccounts(selectedSubscriptionId);
  const sqlApiOnlyAccounts = (allAccounts || [])
    .filter((account) => apiType(account) === "SQL")
    .map((account) => ({
      ...account,
      id: normalizeAccountId(account.id),
    }));

  const updateCopyJobState = (newAccount: DatabaseAccount) => {
    setCopyJobState((prevState) => {
      if (prevState.target?.account?.id !== newAccount.id) {
        return {
          ...prevState,
          target: {
            ...prevState.target,
            account: newAccount,
          },
        };
      }
      return prevState;
    });
  };

  useEffect(() => {
    if (sqlApiOnlyAccounts && sqlApiOnlyAccounts.length > 0 && selectedSubscriptionId) {
      const currentAccountId = copyJobState?.target?.account?.id;
      const predefinedAccountId = normalizeAccountId(userContext.databaseAccount?.id);
      const selectedAccountId = currentAccountId || predefinedAccountId;

      const matchedAccount: DatabaseAccount | null =
        sqlApiOnlyAccounts.find((account) => account.id === selectedAccountId) || null;
      updateCopyJobState(matchedAccount || sqlApiOnlyAccounts[0]);
    }
  }, [sqlApiOnlyAccounts?.length, selectedSubscriptionId]);

  const accountOptions =
    sqlApiOnlyAccounts?.map((account) => ({
      key: account.id,
      text: account.name,
      data: account,
    })) || [];

  const handleAccountChange = (_ev?: React.FormEvent, option?: (typeof accountOptions)[0]) => {
    const selectedAccount = option?.data as DatabaseAccount;

    if (selectedAccount) {
      updateCopyJobState(selectedAccount);
    }
  };

  const isAccountDropdownDisabled = !selectedSubscriptionId || accountOptions.length === 0;
  const selectedAccountId = normalizeAccountId(copyJobState?.target?.account?.id ?? "");

  return (
    <FieldRow label={t(Keys.containerCopy.selectAccount.accountDropdownLabel)}>
      <Dropdown
        placeholder={t(Keys.containerCopy.selectAccount.accountDropdownPlaceholder)}
        ariaLabel={t(Keys.containerCopy.selectAccount.accountDropdownLabel)}
        options={accountOptions}
        disabled={isAccountDropdownDisabled}
        required
        selectedKey={selectedAccountId}
        onChange={handleAccountChange}
        data-test="account-dropdown"
      />
    </FieldRow>
  );
};
