import { gql, useApolloClient } from '@apollo/client';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { useStore } from 'stores/hooks';
// prettier-ignore
import type { GetCurrencySymbol, GetCurrencySymbolVariables } from './__generated__/GetCurrencySymbol';

const QUERY_GET_CURRENCY_SYMBOL = gql`
  query GetCurrencySymbol($currencyid: Uuid!) {
    transactioncurrency(transactioncurrencyid: $currencyid) {
      currencysymbol
    }
  }
`;

const CurrencyAddon = observer(() => {
  const { $calculation } = useStore();

  const currencyid = $calculation.$values.getValue('supplierCurrency');

  const [currencySymbol, setCurrencySymbol] = useState<string | null | undefined>(null);

  const { query } = useApolloClient();

  if (!currencyid) return null;

  query<GetCurrencySymbol, GetCurrencySymbolVariables>({
    query: QUERY_GET_CURRENCY_SYMBOL,
    variables: {
      currencyid,
    },
  })
    .then(({ data }) => {
      setCurrencySymbol(data?.transactioncurrency?.currencysymbol);
    })
    .catch(() => {
      setCurrencySymbol(null);
    });

  return <span>{currencySymbol}</span>;
});

export default <CurrencyAddon />;
