import React, { useState, useEffect } from 'react'
import { Link, usePage } from '@inertiajs/inertia-react'
import { Button, Image, Loading, Navbar, Text, Dropdown, Badge, User } from '@nextui-org/react';
import { FaShoppingCart } from "react-icons/fa";
import { useDispatch, useSelector } from 'react-redux';
import { setAccount, setChain, setSelectedNFT } from '../redux/reducer';
import { toast } from 'react-toastify';
import { Inertia } from '@inertiajs/inertia';
import { clearCart } from '../init';


const Header = ({setStatus}) => {
    const {auth, settings, cartCount} = usePage().props;
    const { account, chain } = useSelector(state => state.root)
    const dispatch = useDispatch();
    
    const [loading, setLoading] = useState(false)

    const connectWallet = async () => {
        setLoading(true)  
        if (window.ethereum !== undefined) {
            await window.ethereum.request({ method: "eth_requestAccounts" }).then((accounts) => {
                dispatch(setAccount(accounts[0]));
            }).catch((err) => {
                console.log(err);
                return;
            })
        }
        setLoading(false)
    };

    const checkAccountChanges = () => {
        if(window.ethereum){
            window.ethereum?.on('accountsChanged', function (accounts) {
                dispatch(setAccount(accounts[0]));
                dispatch(setSelectedNFT(null));
                clearCart()
            })
        }
    }

    const checkConnection = () => {
        if (window.ethereum) {
            if(window.ethereum?.isConnected()){
                dispatch(setAccount(window.ethereum.selectedAddress));
            }
        }
    }

    const checkChainId = () => {
        if (window.ethereum) {
            dispatch(setChain(Number(window.ethereum?.chainId)))
            if(Number(window.ethereum?.chainId) != settings.chainId){
                toast.warning(`Connect to ${settings.chainName} Network`);
            }
            window.ethereum?.on('chainChanged', function (newChain) {
                dispatch(setChain(Number(newChain)))
                dispatch(setSelectedNFT(null));
                clearCart()
            })
        }
    }

    const handleLogout = () => {
        dispatch(setSelectedNFT(null));
        clearCart();
        Inertia.get(route('user.logout'));
    }

    useEffect(()=>{
        auth.user && checkChainId();
    },[chain]);

    useEffect(()=>{
        auth.user && checkConnection();
    },[account]);

    useEffect(()=>{
        auth.user && checkAccountChanges();
    },[account]);
  
    return (
    <div>
        <Navbar variant={'static'}>
            <Navbar.Brand>
                <Image src={settings.logo} width="100%" height="60px" />
                <Text b color="inherit" hideIn="xs">
                    {settings.appName}
                </Text>
            </Navbar.Brand>

            <Navbar.Content hideIn="xs">
                <Link href={route('home')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Home </Link>
                <Link href={route('collections')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Product Collections </Link>
                <Link href={route('nfts')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > NFT Collections </Link>
                <Link href={route('verify')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Verify NFT </Link>
                <Link href={route('points')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Promotion Code </Link>
            </Navbar.Content>

            <Navbar.Content>
            {
                auth.user ? (
                <>
                <Navbar.Link onClick={()=>setStatus(true)}>
                <Badge
                    color="warning"
                    content={cartCount}
                    shape="circle"
                    >
                    <FaShoppingCart fill="currentColor" size={25} />
                </Badge>
                </Navbar.Link>
                <Navbar.Item>
                    <Button bordered color="gradient" auto onPress={connectWallet} disabled={loading} >
                        { loading && <Loading type="points" size="sm" /> }
                        { account ? account.substring(0,5) + "..." + account.substring(account.length -4 , account.length) : "Connect Wallet" }
                    </Button> 
                </Navbar.Item>
                <Navbar.Item>
                    <Dropdown placement="bottom-left">
                        <Dropdown.Trigger>
                            <User
                            bordered
                            as="button"
                            size="lg"
                            color="primary"
                            name={auth.user.name}
                            description={auth.user.email}
                            src={auth.user.photo || `https://ui-avatars.com/api/?name=${auth.user.name}`} 
                            />
                        </Dropdown.Trigger>
                        <Dropdown.Menu color="primary" aria-label="User Actions">
                            <Dropdown.Item key="email" css={{ height: "$18" }}>
                            <Text b color="inherit" css={{ d: "flex" }}>
                                Signed in as
                            </Text>
                            <Text b color="inherit" css={{ d: "flex" }}>
                                {auth.user.email}
                            </Text>
                            </Dropdown.Item>
                            <Dropdown.Item key="profile" withDivider>
                                <Link href={route('user-profile')} >Profile</Link>
                            </Dropdown.Item>
                            <Dropdown.Item key="points" withDivider>
                                <Link href={route('points')} >My Points</Link>
                            </Dropdown.Item>
                            <Dropdown.Item key="logout" color="error" withDivider>
                            <Text onClick={handleLogout}> Logout </Text>
                            </Dropdown.Item>
                        </Dropdown.Menu>
                    </Dropdown>
                </Navbar.Item>
                </>
                ) : (
                <>
                <Link href={route('login.form')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Login </Link>
                <Link href={route('register.form')} style={{ padding: '0 10px', color: '#000', fontSize: '15px', fontWeight: '600' }} > Register </Link>
                </>
                )
            }
            </Navbar.Content>
      </Navbar>
    </div>
  )
}

export default Header