import React, { useEffect, useState } from 'react'
import Title from './Title'
import { Text, Spacer } from '@nextui-org/react'
import Summary from './Summary'
import Options from './Options'
import { useSelector } from 'react-redux'
import { Link, usePage } from '@inertiajs/inertia-react'
import {upper} from '../../init'
import Btn from './Btn'
import { Inertia } from '@inertiajs/inertia'
import { toast } from 'react-toastify'

const ProductData = ({ProductDetails, collection, colors, sizes}) => {
    const {auth, cartCount} = usePage().props
    const {selectedNFT} = useSelector(state => state.root)
    const [colorValue, setColor] = useState('');
    const [sizeValue, setSize] = useState('');
    
    const addToCart = () => {
        const productData = {
            slug: ProductDetails.slug,
            selected: selectedNFT,
            color: colorValue,
            size: sizeValue,
        }
        if(colorValue == '' || sizeValue == ''){
            toast.error('Select Color and Size'); return;
        }else if(cartCount == selectedNFT?.limit){
            toast.error(`You have ${selectedNFT?.type} NFT, you can add upto ${selectedNFT?.limit} products`);
            return;
        }else{
            Inertia.post(route('add-to-cart'), productData)
        }
    }

  return (
    <>
    <Text css={{ pb: '1rem' }} h3> {upper(ProductDetails.title)} </Text>
    
    <Title preTitle='Collection' title={collection.title} />
    <Title preTitle='Type' title={ProductDetails.type} />
    <Title preTitle='Model' title={ProductDetails.model} />
    <Summary summary={ProductDetails.summary} />

    <Options value={colorValue} setValue={setColor} options={colors} title='Colors' />
    <Options value={sizeValue} setValue={setSize} options={sizes} title='Sizes' />
    <Spacer y={1} />
    {
        auth.user ? (
        <>
        {
            selectedNFT != null && selectedNFT?.contract_address.toUpperCase() == collection.contract_address.toUpperCase() && ProductDetails.type == selectedNFT?.type ? (
                <Btn  onpress={addToCart} > Add to Cart </Btn>
            ) : (
            selectedNFT == null ? <Link href={route('verify')} > Verify NFT First </Link> : 
            <Text color='error' b> 
                You have Verified {selectedNFT.contract_name} {selectedNFT.type} NFT, you can Select Products from {selectedNFT.contract_name} {selectedNFT.type} Collection only 
            </Text>
            )
        }
        </>
        ) : <Btn link={route('login.form')}> You need to login first </Btn>
    }
    </>
  )
}

export default ProductData