"use client"

import { CheckCircleIcon, XCircleIcon } from "@heroicons/react/24/outline"
// import { EVENT_GET } from "@/routes/routes";
import { Html5Qrcode } from "html5-qrcode"
import { format, toDate } from "date-fns"
import React, { useState, useEffect } from "react"
import type { Events } from "@prisma/client";
import { redirect, useRouter } from "next/navigation";
import placeholder from "@/public/placeholder.svg"
import Link from "next/link";
import { useAppStore } from "@/lib/store";
import axios from "axios"
import { ETICKET_GET, TICKET_GET, TICKET_UPDATE, USER_INFO_ROUTE } from "@/routes/routes"
import Navigation from "@/components/Navigation"

export default function event({ params }: { params: Promise<{ id: string }> }){
    const [ticketNr, setTicketNr] = useState("")
    const [event, setEvent] = useState<Events | null>(null)

    const [successPop, setSuccessPop] = useState(false)
    const [errorPop, setErrorPop] = useState(false)

    const [lastScaned, setLastScaned] = useState<string | null>(null)

    const [scanResult, setScanResult] = useState<string | null>(null);
    const [scanner, setScanner] = useState(null);

    const router = useRouter()
    const { events, tickets, user, setTickets, setUser } = useAppStore()
    
    const { id } = React.use(params);

    useEffect(() => {
        const fun = async() => {
            if(!user){
                await axios.get(USER_INFO_ROUTE, { withCredentials: true })
                .then((res) => {
                    setUser(res.data)
                    if(res.data.role === 0){
                        router.replace("/events")
                    }
                })
                .catch((err) => {
                    router.replace("/")
                })
            }
        }
        fun();
    },[user, setUser, router])

    const eventTickets = tickets.filter(ticket => ticket.eventId === id)
    const scanedTickets = eventTickets.filter(ticket => ticket.scandate !== null)
    
    useEffect(() => {
        console.log("Tickets: ", tickets)
        const idCheck = events.find(event => event.id === id)

        if(idCheck){
            setEvent(idCheck)
        }
    })
    
    const ticketCheck = async() => {
        setLastScaned(ticketNr)
        await axios.post(ETICKET_GET, { ticketId: ticketNr, eventId: id }, { withCredentials: true })
        .then(() => {
            setSuccessPop(true)
            axios.post(TICKET_UPDATE, {ticketId: ticketNr, eventId: id}, {withCredentials: true})
            .then(() => {
                setTicketNr("")
                axios.get(TICKET_GET, { withCredentials: true })
                .then((res) => {
                    setTickets(res.data)
                })
            })            
        })
        .catch(() => {
            setErrorPop(true)
        })
    }

    const startScanner = () => { // skenera palaišana
        setSuccessPop(false)
        setErrorPop(false)

        const qrScanner = new Html5Qrcode("reader")

        qrScanner.start(
            { facingMode: "environment" },
            {
                fps: 5,
                qrbox: { width: 250, height: 250 },
            },(decodedText) => {
                qrScanner.stop().then(() => {
                    setScanner(null)
                    setLastScaned(decodedText)
                    axios.post(ETICKET_GET, { ticketId: decodedText, eventId: id }, { withCredentials: true })
                    .then(() => {
                        axios.post(TICKET_UPDATE, {ticketId: decodedText, eventId: id}, {withCredentials: true})
                        .then(() => {
                            axios.get(TICKET_GET, { withCredentials: true })
                            .then((res) => {
                                setTickets(res.data)
                                setSuccessPop(true)
                            })
                        })
                    })
                    .catch(() => {
                        setErrorPop(true)
                    })
                })
            },
            (error) => console.log(error)
        )
    }

    if(!event){
        return(
            <div className="h-screen px-5 flex flex-col items-center justify-center">
                <h1 className="text-2xl font-bold mb-2">Event not Found</h1>
                <p className="text-neutral-500 text-center mb-6">The event you're looking for doesn't exist or has been removed.</p>
                <Link href={'/events'} className="h-10 px-4 flex items-center justify-center rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 transition-colors cursor-pointer">Back to events</Link>
            </div>
        )
    }

    return(
        <div className="min-h-screen flex flex-col">
            <Navigation />
            <div className="w-full grow px-5 sm:px-10 py-8 sm:py-4">
                <h1 className="text-2xl sm:text-3xl font-bold tracking-tight mb-4">{event.title}</h1>
                <div className="flex flex-col px-3 py-4 sm:p-6 mb-6 border border-neutral-200 rounded-md">
                    <h1 className="text-xl sm:text-2xl font-semibold tracking-tight mb-1.5">Scanning progress</h1>
                    <p className="font-semibold mb-6 text-neutral-500">{scanedTickets.length} of {eventTickets.length} tickets scanned</p>
                    <div className="flex relative">
                        <div className="w-full h-2 flex rounded-xl bg-neutral-300"/>
                        <div className={`max-w-full h-2 flex rounded-xl absolute bg-blue-600`} style={{ width: `${(scanedTickets.length/eventTickets.length)*100}%`}}/>
                    </div>
                </div>
                <div className="flex flex-col px-3 py-4 sm:p-6 mb-6 border border-neutral-200 rounded-md">
                    <h1 className="text-xl sm:text-2xl font-semibold tracking-tight mb-6">Manual entry</h1>
                    <div className="flex gap-4 items-center">
                        <input type="text" placeholder="Ticket id" className="w-full px-3 py-2 outline-none border border-neutral-200 rounded-md" value={ticketNr} onChange={(e) => setTicketNr(e.target.value)}/>
                        <input type="button" value="Check" className="h-10 px-4 rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 transition-colors cursor-pointer" onClick={() => ticketCheck()}/>
                    </div>
                </div>
                <input type="button" value="Scan" className="w-full font-semibold py-2 text-white bg-blue-600 sm:hover:bg-blue-700 rounded-lg transition-colors cursor-pointer mb-4" onClick={() => startScanner()}/>
                <div id="reader"/>
            </div>
            <div id="successPop" className={`h-screen w-screen p-4 flex flex-col items-center justify-center fixed left-0 top-0 bg-white transition-all duration-300 ${successPop ? "translate-x-0" : "translate-x-full"} z-60`}>
                <CheckCircleIcon className="size-32 mb-5 stroke-[#4BB543]"/>
                <h1 className="text-3xl font-bold tracking-tight mb-4">Ticket Valid</h1>
                <p className="text-sm font-semibold tracking-tight mb-4">Ticket id: {lastScaned}</p>
                <input type="button" value="Scan Next" className="w-full font-semibold py-2 text-white bg-blue-600 sm:hover:bg-blue-700 rounded-lg transition-colors cursor-pointer mb-4" onClick={() => startScanner()}/>
                <input type="button" value="Close" className="w-full font-semibold py-2 border border-neutral-200 hover:bg-neutral-200 rounded-lg transition-colors cursor-pointer" onClick={() => setSuccessPop(false)}/>
            </div>
            <div id="errorPop" className={`h-screen w-screen p-4 flex flex-col items-center justify-center fixed left-0 top-0 bg-white transition-all duration-300 ${errorPop ? "translate-x-0" : "translate-x-full"} z-60`}>
                <XCircleIcon className="size-32 mb-5 stroke-[#FF0033]"/>
                <h1 className="text-3xl font-bold tracking-tight mb-4">Ticket Invalid</h1>
                <p className="text-sm font-semibold tracking-tight mb-4">Ticket id: {lastScaned}</p>
                <p className="text-sm font-semibold tracking-tight text-neutral-500 mb-4">This ticket is already scaned or does not exsist</p>
                <input type="button" value="Scan Next" className="w-full font-semibold py-2 text-white bg-blue-600 sm:hover:bg-blue-700 rounded-lg transition-colors cursor-pointer mb-4" onClick={() => startScanner()}/>
                <input type="button" value="Close" className="w-full font-semibold py-2 border border-neutral-200 hover:bg-neutral-200 rounded-lg transition-colors cursor-pointer" onClick={() => setErrorPop(false)}/>
            </div>
        </div>
    )
}