// Copyright 2017-2025 @pezkuwi/app-democracy authors & contributors
// SPDX-License-Identifier: Apache-2.0

import type { Compact, Option } from '@pezkuwi/types';
import type { ProposalIndex, TreasuryProposal } from '@pezkuwi/types/interfaces';
import type { TypeDef } from '@pezkuwi/types/types';

import React, { useEffect, useState } from 'react';

import { InputAddress, InputBalance } from '@pezkuwi/react-components';
import { useApi, useCall } from '@pezkuwi/react-hooks';
import Params from '@pezkuwi/react-params';
import { getTypeDef } from '@pezkuwi/types/create';

import { useTranslation } from '../translate.js';

interface Props {
  className?: string;
  value: Compact<ProposalIndex>;
}

interface Param {
  name: string;
  type: TypeDef;
}

interface Value {
  isValid: boolean;
  value: TreasuryProposal;
}

interface ParamState {
  params: Param[];
  values: Value[];
}

const DEFAULT_PARAMS: ParamState = { params: [], values: [] };

const OPT_PROP = {
  transform: (optProp: Option<TreasuryProposal>) => optProp.unwrapOr(null)
};

function TreasuryCell ({ className = '', value }: Props): React.ReactElement<Props> | null {
  const { t } = useTranslation();
  const { api } = useApi();
  const [proposalId] = useState(() => value.unwrap());
  const proposal = useCall<TreasuryProposal | null>(api.query.treasury.proposals, [proposalId], OPT_PROP);
  const [{ params, values }, setExtracted] = useState<ParamState>(DEFAULT_PARAMS);

  useEffect((): void => {
    proposal && setExtracted({
      params: [{
        name: 'proposal',
        type: getTypeDef('TreasuryProposal')
      }],
      values: [{
        isValid: true,
        value: proposal
      }]
    });
  }, [proposal]);

  if (!proposal) {
    return null;
  }

  return (
    <div className={className}>
      <Params
        isDisabled
        params={params}
        values={values}
      >
        <InputAddress
          defaultValue={proposal.beneficiary}
          isDisabled
          label={t('beneficiary')}
        />
        <InputBalance
          defaultValue={proposal.value}
          isDisabled
          label={t('payout')}
        />
      </Params>
    </div>
  );
}

export default React.memo(TreasuryCell);
