import { usePage } from '@inertiajs/inertia-react'
import { Card, Container, Grid, Input, Text, CssBaseline, Image, Button } from '@nextui-org/react'
import React, { useState } from 'react'
import FrontLayout from '../../Layouts/FrontLayout'
import { useSelector, useDispatch } from 'react-redux'
import { toast } from 'react-toastify'
import axios from 'axios'
import { setSelectedNFT } from '../../redux/reducer'
import { clearCart } from '../../init'
import Loader from '../../components/Loader'
import { Inertia } from '@inertiajs/inertia'

const Checkout = ({cart}) => {
    const {auth, settings} = usePage().props
    const {account, selectedNFT} = useSelector(state => state.root);
    const dispatch = useDispatch();

    const [isActive, setIsActive] = useState(false);
    const [content, setContent] = useState('');
    const [values, setValues] = useState({
        first_name: '',
        last_name: '',
        email: auth.user.email || '',
        phone: '',
        country: '',
        province: '',
        city: '',
        address: '',
        post_code: '',
        houseNo: '',
        iossNumber: '',
        cartItems: cart,
        selected: selectedNFT,
    });

    const isOwner = async () => {
        const options = {method: 'GET', headers: {accept: 'application/json'}};
        let owner = fetch(`${settings.alchemy_base_url}/isHolderOfCollection?wallet=${account}&contractAddress=${selectedNFT?.contract_address}`, options)
            .then(response => response.json())
            .catch(err => console.error(err));
        return owner;
    }

    async function handleSubmit(e) {
        e.preventDefault();
        try {
            setIsActive(true)
            setContent('Placing Order, Please Wait!');
            let owner = await isOwner()
            if(owner.isHolderOfCollection == true){
                await axios.post(route('cart.order'), values).then((res)=>{
                    if(res.data.status == 200){
                        toast.success(res.data.msg);
                        dispatch(setSelectedNFT(null));
                        clearCart();
                        Inertia.get(route('collections'));
                    }else if(res.data.status == 400){
                        toast.error(res.data.msg);
                    }
                })
            }else{
                toast('You are not the owner of selected NFT, try another NFT!')
            }
            setIsActive(false)
        } catch (error) {
            setIsActive(false)
            toast(error.message)
        }
    }

    function handleChange(e) {
        const key = e.target.id;
        const value = e.target.value
        setValues(values => ({
            ...values,
            [key]: value,
        }))
    }

  return (
    <div>
        { isActive && <Loader content={content} isActive={isActive} /> }
        <CssBaseline />
        <Container>
            <Grid.Container css={{ py: '$20' }}gap={2} >
                <Grid xs={12} md={8} >
                    <Card css={{ p: '$3' }} >
                        <Card.Header css={{ d: 'block' }} >
                            <Text h3 >Make Your Checkout Here</Text>
                            <Text>Please make sure to check all fields carefully and connect wallet in order to checkout</Text>
                        </Card.Header>
                    <form onSubmit={handleSubmit} method="post" >
                        <Card.Body>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="First Name" 
                                    value={values.first_name} name='first_name' id='first_name' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                                <Grid md={6} css={{ px: '$6' }}>
                                    <Input size="md" width="100%" underlined labelPlaceholder="Last Name" 
                                    value={values.last_name} name='last_name' id='last_name' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="Email" 
                                    value={values.email} readOnly name='email' id='email' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                                <Grid md={6} css={{ px: '$6' }}>
                                    <Input size="md" width="100%" underlined labelPlaceholder="Phone Number" 
                                    value={values.phone} name='phone' id='phone' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="Country" 
                                    value={values.country} name='country' id='country' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                                <Grid md={6} css={{ px: '$6' }}>
                                    <Input size="md" width="100%" underlined labelPlaceholder="Province" 
                                    value={values.province} name='province' id='province' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="City" 
                                    value={values.city} name='city' id='city' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                                <Grid md={6} css={{ px: '$6' }}>
                                    <Input size="md" width="100%" underlined labelPlaceholder="Address" 
                                    value={values.address} name='address' id='address' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="Postal Code" 
                                    value={values.post_code} name='post_code' id='post_code' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                                <Grid md={6} css={{ px: '$6' }}>
                                    <Input size="md" width="100%" underlined labelPlaceholder="House Number" 
                                    value={values.houseNo} name='houseNo' id='houseNo' onChange={handleChange} required
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                           <Grid.Container css={{ my: '$10' }} >
                                <Grid md={6} css={{ px: '$6' }} >
                                    <Input size="md" width="100%" underlined labelPlaceholder="Ioss Number" 
                                    value={values.iossNumber} name='iossNumber' id='iossNumber' onChange={handleChange}
                                    color="warning" style={{ border: 'none' }} />
                                </Grid>
                           </Grid.Container>
                        </Card.Body>
                        <Card.Footer>
                            {
                            cart.length != 0 && (
                                <Button type='submit' color='gradient' css={{ w: '100%' }} >Confirm Order</Button>
                            )
                            }
                        </Card.Footer>
                    </form>
                    </Card>
                </Grid>
                
                <Grid xs={12} md={4} justify='center'>
                    <Card css={{ p: '$3' }} >
                        <Card.Header>
                            <Text h3>Cart Items</Text>
                        </Card.Header>
                        <Container css={{ overflowY: 'scroll', maxHeight: '600px' }} >
                        <Card.Body>
                            { cart.length == 0 && <Text> No products in the Cart </Text> }
                            {
                                cart && cart.map((item, index)=>{
                                    return (
                                    <>
                                    <Card variant="bordered" key={index} css={{ my: '$5' }} >
                                    <Card.Body>
                                        <Grid.Container>
                                        <Grid md={6}>
                                            <Image src={item.photo} alt={item.name} height="100px" />
                                        </Grid>
                                        <Grid md={6} direction="column" justify='center' css={{ pl: "$5" }} >
                                            <Text h5> {item.name} </Text>
                                            <Text> Color: {item.selectedColor} </Text>
                                            <Text> Size: {item.selectedSize} </Text>
                                        </Grid>
                                        </Grid.Container>
                                    </Card.Body>
                                    </Card>
                                    </>
                                    )
                                })
                            }
                        </Card.Body>
                        </Container>
                    </Card>
                </Grid>
            </Grid.Container>
        </Container>
    </div>
  )
}

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

export default Checkout