import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Stack, ToggleButton, ToggleButtonGroup, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { Controller, useFormContext, useWatch } from 'react-hook-form';

import ArcBlockMethodForm from './arcblock';
import BitcoinMethodForm from './bitcoin';
import EthereumMethodForm from './ethereum';
import StripeMethodForm from './stripe';
import BaseMethodForm from './base';

export default function PaymentMethodForm({
  action = 'create',
  editableKeys = [],
}: {
  action?: 'create' | 'edit';
  editableKeys?: string[];
}) {
  const { t } = useLocaleContext();
  const { control, setValue } = useFormContext();

  const type = useWatch({ control, name: 'type' });

  const checkDisabled = (key: string) => {
    if (action === 'edit') {
      return !editableKeys?.includes(key);
    }
    return false;
  };

  return (
    <Root direction="column" alignItems="flex-start" spacing={2}>
      <Controller
        name="type"
        control={control}
        render={({ field }) => (
          <ToggleButtonGroup
            {...field}
            disabled={checkDisabled(field.name)}
            onChange={(_, value: string) => {
              if (value !== null) {
                setValue(field.name, value);
              }
            }}
            exclusive>
            <ToggleButton value="arcblock">ArcBlock</ToggleButton>
            <ToggleButton value="stripe">Stripe</ToggleButton>
            <ToggleButton value="ethereum">Ethereum</ToggleButton>
            <ToggleButton value="base">Base</ToggleButton>
            <ToggleButton value="bitcoin" disabled>
              Bitcoin
            </ToggleButton>
          </ToggleButtonGroup>
        )}
      />
      <Typography variant="h6" sx={{ mb: 3, fontWeight: 600 }}>
        {t('admin.paymentMethod.settings')}
      </Typography>
      {type === 'stripe' && <StripeMethodForm checkDisabled={checkDisabled} />}
      {type === 'arcblock' && <ArcBlockMethodForm checkDisabled={checkDisabled} />}
      {type === 'ethereum' && <EthereumMethodForm checkDisabled={checkDisabled} />}
      {type === 'base' && <BaseMethodForm checkDisabled={checkDisabled} />}
      {type === 'bitcoin' && <BitcoinMethodForm checkDisabled={checkDisabled} />}
    </Root>
  );
}

const Root = styled(Stack)`
  select {
    border: none;
    &:active,
    &:focus {
      border: none;
    }
  }
`;
