import { Alert, Box, Button, chakra, Flex, Link, Radio, RadioGroup } from '@chakra-ui/react';
import { useWeb3Modal } from '@web3modal/react';
import React from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { useSignMessage, useAccount } from 'wagmi';

import type {
  AddressVerificationFormSecondStepFields,
  AddressCheckStatusSuccess,
  AddressVerificationFormFirstStepFields,
  RootFields,
  AddressVerificationResponseError,
  AddressValidationResponseSuccess,
} from '../types';
import type { VerifiedAddress } from 'types/api/account';

import appConfig from 'configs/app/config';
import useApiFetch from 'lib/api/useApiFetch';
import shortenString from 'lib/shortenString';
import CopyToClipboard from 'ui/shared/CopyToClipboard';

import AddressVerificationFieldMessage from '../fields/AddressVerificationFieldMessage';
import AddressVerificationFieldSignature from '../fields/AddressVerificationFieldSignature';

type Fields = RootFields & AddressVerificationFormSecondStepFields;

interface Props extends AddressVerificationFormFirstStepFields, AddressCheckStatusSuccess{
  onContinue: (newItem: VerifiedAddress) => void;
}

const AddressVerificationStepSignature = ({ address, signingMessage, contractCreator, contractOwner, onContinue }: Props) => {
  const [ signMethod, setSignMethod ] = React.useState<'wallet' | 'manually'>('wallet');

  const { open: openWeb3Modal } = useWeb3Modal();
  const { isConnected } = useAccount();

  const formApi = useForm<Fields>({
    mode: 'onBlur',
    defaultValues: {
      message: signingMessage,
    },
  });
  const { handleSubmit, formState, control, setValue, getValues, setError, clearErrors, watch } = formApi;

  const apiFetch = useApiFetch();

  const signature = watch('signature');
  React.useEffect(() => {
    clearErrors('root');
  }, [ clearErrors, signature ]);

  const onFormSubmit: SubmitHandler<Fields> = React.useCallback(async(data) => {
    try {
      const body = {
        contractAddress: address,
        message: data.message,
        signature: data.signature,
      };

      const response = await apiFetch<'address_verification', AddressValidationResponseSuccess, AddressVerificationResponseError>('address_verification', {
        fetchParams: { method: 'POST', body },
        pathParams: { chainId: appConfig.network.id, type: ':verify' },
      });

      if (response.status !== 'SUCCESS') {
        const type = typeof response.status === 'number' ? 'UNKNOWN_STATUS' : response.status;
        return setError('root', { type, message: response.status === 'INVALID_SIGNER_ERROR' ? response.invalidSigner.signer : undefined });
      }

      onContinue(response.result.verifiedAddress);
    } catch (error) {
      setError('root', { type: 'UNKNOWN_STATUS' });
    }
  }, [ address, apiFetch, onContinue, setError ]);

  const onSubmit = handleSubmit(onFormSubmit);

  const { signMessage, isLoading: isSigning } = useSignMessage({
    onSuccess: (data) => {
      setValue('signature', data);
      onSubmit();
    },
    onError: (error) => {
      return setError('root', { type: 'SIGNING_FAIL', message: (error as Error)?.message || 'Oops! Something went wrong' });
    },
  });

  const handleSignMethodChange = React.useCallback((value: typeof signMethod) => {
    setSignMethod(value);
    clearErrors('root');
  }, [ clearErrors ]);

  const handleOpenWeb3Modal = React.useCallback(() => {
    openWeb3Modal();
  }, [ openWeb3Modal ]);

  const handleWeb3SignClick = React.useCallback(() => {
    if (!isConnected) {
      return setError('root', { type: 'manual', message: 'Please connect to your Web3 wallet first' });
    }
    const message = getValues('message');
    signMessage({ message });
  }, [ getValues, signMessage, isConnected, setError ]);

  const handleManualSignClick = React.useCallback(() => {
    onSubmit();
  }, [ onSubmit ]);

  const button = (() => {
    if (signMethod === 'manually') {
      return (
        <Button
          size="lg"
          onClick={ handleManualSignClick }
          isLoading={ formState.isSubmitting }
          loadingText="Verifying"
        >
          Verify
        </Button>
      );
    }

    return (
      <Button
        size="lg"
        onClick={ isConnected ? handleWeb3SignClick : handleOpenWeb3Modal }
        isLoading={ formState.isSubmitting || isSigning }
        loadingText={ isSigning ? 'Signing' : 'Verifying' }
      >
        { isConnected ? 'Sign and verify' : 'Connect wallet' }
      </Button>
    );
  })();

  const contactUsLink = <span>contact us <Link href="mailto:help@blockscout.com">help@blockscout.com</Link></span>;

  const rootError = (() => {
    switch (formState.errors.root?.type) {
      case 'INVALID_SIGNATURE_ERROR': {
        return <span>The signature could not be processed.</span>;
      }
      case 'VALIDITY_EXPIRED_ERROR': {
        return <span>This verification message has expired. Add the contract address to restart the process.</span>;
      }
      case 'SIGNING_FAIL': {
        return <span>{ formState.errors.root.message }</span>;
      }
      case 'INVALID_SIGNER_ERROR': {
        const signer = shortenString(formState.errors.root.message || '');
        const expectedSigners = [ contractCreator, contractOwner ].filter(Boolean).map(shortenString).join(', ');
        return (
          <Box>
            <span>This address </span>
            <span>{ signer }</span>
            <span> is not a creator/owner of the requested contract and cannot claim ownership. Only </span>
            <span>{ expectedSigners }2</span>
            <span> can verify ownership of this contract.</span>
          </Box>
        );
      }
      case 'UNKNOWN_STATUS': {
        return (
          <Box>
            <span>We are not able to process the verify account ownership for this contract address. Kindly </span>
            { contactUsLink }
            <span> for further assistance.</span>
          </Box>
        );
      }
      case undefined: {
        return null;
      }
    }
  })();

  return (
    <form noValidate onSubmit={ onSubmit }>
      { rootError && <Alert status="warning" mb={ 6 }>{ rootError }</Alert> }
      <Box mb={ 8 }>
        <span>Please select the address to sign and copy the message and sign it using the Blockscout message provider of your choice. </span>
        <Link href="https://docs.blockscout.com/for-users/my-account/verified-addresses/copy-and-sign-message" target="_blank">
          Additional instructions
        </Link>
        <span>. If you do not see your address here but are sure that you are the owner of the contract, kindly </span>
        { contactUsLink }
        <span> for further assistance.</span>
      </Box>
      { (contractOwner || contractCreator) && (
        <Flex flexDir="column" rowGap={ 4 } mb={ 4 }>
          { contractCreator && (
            <Box>
              <chakra.span fontWeight={ 600 }>Contract creator: </chakra.span>
              <chakra.span>{ contractCreator }</chakra.span>
            </Box>
          ) }
          { contractOwner && (
            <Box>
              <chakra.span fontWeight={ 600 }>Contract owner: </chakra.span>
              <chakra.span>{ contractOwner }</chakra.span>
            </Box>
          ) }
        </Flex>
      ) }
      <Flex rowGap={ 5 } flexDir="column">
        <div>
          <CopyToClipboard text={ signingMessage } ml="auto" display="block"/>
          <AddressVerificationFieldMessage formState={ formState } control={ control }/>
        </div>
        <RadioGroup onChange={ handleSignMethodChange } value={ signMethod } display="flex" flexDir="column" rowGap={ 4 }>
          <Radio value="wallet">Sign via Web3 wallet</Radio>
          <Radio value="manually">Sign manually</Radio>
        </RadioGroup>
        { signMethod === 'manually' && <AddressVerificationFieldSignature formState={ formState } control={ control }/> }
      </Flex>
      <Flex alignItems="center" mt={ 8 } columnGap={ 5 }>
        { button }
        <Box>
          <span>Contact </span>
          <Link href="mailto:help@blockscout.com">help@blockscout.com</Link>
        </Box>
      </Flex>
    </form>
  );
};

export default React.memo(AddressVerificationStepSignature);
