import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'

import Head from 'next/head'
import Card from '@/components/DashboardCard'
import PopupForm from '@/components/DashboardCreateEntity'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'

export const getServerSideProps = (async ctx => {
    const { req } = ctx
    const cookie = req.cookies.user_auth
    if (!cookie) {
        return { redirect: {
            destination: '/login',
            permanent: false
        } }
    } else {
        const cookie_key = req.cookies.user_apiKey
        if (!cookie_key) {
            return { redirect: {
                destination: '/logout',
                permanent: false
            } }
        }
        const response = await fetch(`${process.env.API_URL}/user/find?id=${req.cookies.user_id}`, {
            method: 'GET',
            headers: {
                'authorization': process.env.AUTH,
            },
        })
        const data_json = await response.json()
        if (!response.ok) {
            console.error(response, data_json)
            return { redirect: {
                destination: '/logout',
                permanent: false
            } }
        }
        return { props: { data: data_json } }
    }
})

const Dashboard = ({ data }) => {
    const router = useRouter()
    const [isPopupVisible, setPopupVisibility] = useState(false)

    const handleCreateButtonClick = () => {
        setPopupVisibility(true)
    }

    const handleClosePopup = () => {
        setPopupVisibility(false)
    }
    
useEffect(() => {
    const handleMousemove = (e) => {
      const rect = e.currentTarget.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      e.currentTarget.style.setProperty("--mouse-x", `${x}px`);
      e.currentTarget.style.setProperty("--mouse-y", `${y}px`);
    };
    document.querySelectorAll(".dashboard_entity_card").forEach((card) => {
      card.addEventListener("mousemove", handleMousemove);
      return () => {
        card.removeEventListener("mousemove", handleMousemove);
      };
    });
  }, []);


    return (
        <>
            <Head>
                <title>Dashboard - Assistify</title>
            </Head>
            <Navbar user={data}/>
             {Object.keys(data).length !== 0 ? (
                <>
                    <main className="dashboard_div">
                        <div className="dashboard_headings">
                            <h1 className="heading_color">Welcome, {data.name} 👋</h1>
                            {/* <button className="cta">
                <span>Create</span>
                <svg viewBox="0 0 13 10" height="10px" width="15px">
                    <path d="M1,5 L11,5"></path>
                    <polyline points="8 1 12 5 8 9"></polyline>
                </svg>
                </button> */}
                            <div className="showcase_buttons">
                                <button className="btn" onClick={handleCreateButtonClick}>
                                    <svg
                                        height="24"
                                        width="24"
                                        fill="#FFFFFF"
                                        viewBox="0 0 24 24"
                                        data-name="Layer 1"
                                        id="Layer_1"
                                        className="sparkle"
                                    >
                                        <path d="M10,21.236,6.755,14.745.264,11.5,6.755,8.255,10,1.764l3.245,6.491L19.736,11.5l-6.491,3.245ZM18,21l1.5,3L21,21l3-1.5L21,18l-1.5-3L18,18l-3,1.5ZM19.333,4.667,20.5,7l1.167-2.333L24,3.5,21.667,2.333,20.5,0,19.333,2.333,17,3.5Z"></path>
                                    </svg>

                                    <span className="text">Create</span>
                                </button>
                            </div>
                            {isPopupVisible && <PopupForm onClose={handleClosePopup} router={router}/>}
                        </div>
                        <div className="dashboard_entities">
                            {data.entities.length !== 0 ? (
                                data.entities?.map((entity, index) => {
                                    return (
                                        <Link key={index} href={`/entity/${entity.id}`}>
                                            <Card title={entity.name} key={index} id={entity.id} />
                                        </Link>
                                    )
                                })
                            ) : (
                                <div
                                    style={{
                                        color: '#ddd'
                                    }}
                                >
                                    You haven&apos;t created any entities yet.
                                </div>
                            )}
                        </div>
                    </main>
                </>
            ) : (
                /* Work on this, show a error */
                Error
            )}
            <Footer />
        </>
    )
}

export default Dashboard