"use client"

import Navigation from "@/components/Navigation";
import { CalendarIcon } from "@heroicons/react/24/outline"
import axios from "axios";
import { addDays, format, isWithinInterval, setDate, toDate } from "date-fns"
import Link from "next/link";
import { useEffect, useState } from "react";
import type { Event } from "@/lib/types";
import placeholder from "@/public/placeholder.svg"
import { useAppStore } from "@/lib/store";
import { redirect, useRouter } from "next/navigation"
import { EVENT_GET, USER_INFO_ROUTE } from "@/routes/routes";

export default function Tickets(){
    const [searchQuery, setSearchQuery] = useState("")

    const router = useRouter()

    const { user, events, setUser } = useAppStore()

    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 filteredEvents = events.filter(event => {
        const search = event.title.toLowerCase().includes(searchQuery.toLowerCase())
        const isInInterval = isWithinInterval(event.date, {
                start: new Date(),
                end: addDays(new Date(), 5)
            })

        return search && isInInterval
    })
    

    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">
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-2 mb-6">
                    <h1 className="text-3xl font-bold tracking-tight">Scan</h1>
                    <input type="search" className="w-full md:w-[300px] px-3 py-2 outline-none border border-neutral-200 rounded-md" placeholder="Search events..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)}/>
                </div>
                {filteredEvents.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                        {filteredEvents.map((e) => (
                            <Link key={e.id} href={`scan/${e.id}`} className="rounded-xl border border-neutral-200 shadow-sm overflow-hidden">
                                <div className="hidden sm:block sm:h-48 bg-cover bg-center" style={{backgroundImage: `url(${e.image || placeholder})`}}/>
                                <div className="p-4 sm:p-6">
                                    <h1 className="text-xl sm:text-2xl font-semibold leading-none tracking-tight mb-2">{e.title}</h1>
                                    <div className="flex items-center text-sm text-neutral-500">
                                        <CalendarIcon className="size-4 mr-2"/>
                                        <span>{format(new Date(e.date), 'dd.MM.yyyy HH:mm')}</span> 
                                    </div>
                                </div>
                            </Link>
                        ))}
                    </div>
                ): (
                    <div className="text-center py-12">
                        <h1 className="text-xl font-semibold mb-2">No events Found</h1>
                        <p className="text-neutral-500">{searchQuery ? `No events matching "${searchQuery}"` : "There are no upcoming events at the moment."}</p>
                    </div>
                )}
            </div>
        </div>
    )
}