import React, { useEffect, useState } from 'react'
import FrontLayout from '../../Layouts/FrontLayout'
import { mintNFT } from '../../init';
import ReactHtmlParser from 'react-html-parser';
import { usePage } from '@inertiajs/inertia-react';
import Gallery from './Gallery';
import { Card, Container, Input, Spacer, Text, Button, Grid, Image } from '@nextui-org/react';
import { useDispatch, useSelector } from 'react-redux';
import { toast } from 'react-toastify';
import axios from 'axios';
import { setPromo } from '../../redux/reducer';
import Loader from '../../components/Loader';


const NftDetails = ({ nft }) => {
    const {auth} = usePage().props
    const {account, promo} = useSelector(state => state.root);
    const dispatch = useDispatch();
    
    const [promoText, setpromoText] = useState('Apply Promo');
    const [disabled, setdisabled] = useState(false);
    const [promo_code, setPromoCode] = useState('')
    const [isActive, setIsActive] = useState(false);
    const [content, setContent] = useState('');

    const applyPromo = async () => {
        if(promo_code != ''){
            setpromoText('Applying');
            await axios.post(route('promo.apply'), {promo_code: promo_code}).then((res)=> {
                if(res.data.error == 400){
                    toast.error(res.data.msg)
                    setPromoCode('')
                    setpromoText('Apply Promo')
                }else if(res.data.success == 200){
                    dispatch(setPromo(promo_code));
                    setdisabled(true);
                    setpromoText('Promo Applied');
                    toast.success(res.data.msg);
                }
            })
        }else{
            toast.error('Enter Promo Code to Apply')
        }
    }

    const clearPromo = () => {
        setPromoCode(''); 
        setpromoText('Apply Promo'); 
        setdisabled(false);
        dispatch(setPromo(null))
    }

    const mint = async (account, prices, nftData) => {
        try {
            setIsActive(true);
            setContent('Minting NFT')
            await mintNFT(account, prices, nftData).then((data)=>{
                let mintedData = {
                    token_id: data.events.Transfer.returnValues.tokenId,
                    collection_address: nft.contract_address,
                    collection_name: nft.title,
                    wallet_address: account,
                    transaction_hash: data.transactionHash
                }
                if(promo != null){
                    mintedData.promo_code = promo
                    setContent('Minting is Done Validating Promo Code to Reward Points');
                }
                axios.post(route('nft.minted'), mintedData).then((res)=>{
                    if(res.data.error == 400){
                        toast.error(res.data.msg);
                        setIsActive(false)
                    }else if(res.data.success == 200){
                        toast.success(res.data.msg);
                        setIsActive(false)
                    }
                })
                clearPromo()
            });   
        } catch (error) {
            setIsActive(false)
            clearPromo()
        }
    }

    useEffect(()=>{
        if(promo != null){
            setPromoCode(promo)
            setdisabled(true);
            setpromoText('Promo Applied');
        }
    },[promo])


  return (
    <div>
        { isActive && <Loader content={content} isActive={isActive} /> }
        <Image src={nft.banner} alt={nft.title} height='400px' objectFit='fill' />
        <Container>
            <Card css={{ p: '$10', my: '$10' }} >
                <Card.Body css={{ justifyContent: 'center', textAlign: 'center' }} >
                    <Image src={nft.logo} alt={nft.title} height='120px' objectFit='cover' />
                    <Text h1 color='warning' > {nft.title} </Text>
                    <Text> {ReactHtmlParser(nft.summary)} </Text>
                    <Spacer y={2} />
                    <Text b>Have a Promo Code? Mint using a promo code and get one extra product for free from PhygitalDAONFT</Text>
                    <Spacer y={2} />
                   {
                    auth.user && account ? (
                    <>
                    <Container css={{ maxWidth: '350px' }} >
                        <Input 
                            underlined 
                            width='100%'
                            labelPlaceholder='Promo Code' 
                            value={promo_code} 
                            color='warning'
                            onChange={(e)=>setPromoCode(e.target.value)} 
                            disabled = {disabled ? disabled : ''} 
                            style={{ border: 'none' }} 
                        />
                        <Grid.Container css={{ mt: '$5' }} justify='space-around' >
                            <Grid sm={6} md={6}>
                                <Button color='primary' auto onPress={applyPromo} disabled = {disabled ? disabled : ''}  > {promoText} </Button>
                            </Grid>
                            <Grid sm={6} md={6}>
                                <Button color='warning' auto onPress={clearPromo} > Clear Promo </Button>
                            </Grid>
                        </Grid.Container>
                    </Container>
                    <Spacer y={2} />
                    <Button color='gradient' auto onClick={()=>mint(account, JSON.parse(nft.prices), nft)} > Mint {nft.title} </Button>
                    </>
                    ) : (
                    <>
                    {
                    !auth.user ? (
                        <Text h3> Login And Connect Wallet to Mint an NFT </Text>
                        ) : (
                        <Text h3> Connect Wallet to Mint an NFT </Text>
                        )
                    }
                    </>
                    )
                   }
                <Gallery gallery={nft.gallery} />
                </Card.Body>
            </Card>
        </Container>

    </div>
  )
}

NftDetails.layout = page => <FrontLayout children={page} title="NftDetails" />

export default NftDetails