"use client"

import Navigation from "@/components/Navigation";
import { PlusIcon, CalendarIcon, MapPinIcon, TrashIcon } from "@heroicons/react/24/outline"
import { CREATE_EVENT, CREATE_TTYPE, EVENT_GET, USER_INFO_ROUTE } from "@/routes/routes";
import axios from "axios";
import { format, toDate } from "date-fns"
import Link from "next/link";
import { useEffect, useState } from "react";
import placeholder from "@/public/placeholder.svg"
import { useAppStore } from "@/lib/store";
import { redirect, useRouter } from "next/navigation"
import { TicketType } from "@prisma/client";

export default function Tickets(){
    const [searchQuery, setSearchQuery] = useState("")
    const { user, events, setEvents, setUser } = useAppStore()

    const [title, setTitle] = useState("")
    const [loc, setLoc] = useState("")
    const [date, setDate] = useState("")
    const [image, setImage] = useState("")
    const [tType, setTtype] = useState<TicketType[]>([])

    const handleAddTicket = () => {
        setTtype([...tType, { id: "", eventId: "", name: '', price: 0, qty: 0}])
    }

    const handleDeleteTicket = (i: number) => {
        const newTickets = [...tType]
        newTickets.splice(i, 1)
        setTtype(newTickets)
    }

    const handleChange = (i:number, f: keyof TicketType, v: string | number) => {
        const newTickets = [...tType]
        newTickets[i][f] = v as never
        setTtype(newTickets)
    }

    const [eventAdd, setEventAdd] = useState(false)

    const router = useRouter()

    const filteredEvents = events.filter(
        (event) =>
        event.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        event.location.toLowerCase().includes(searchQuery.toLowerCase()),
    )

    useEffect(() => {
        const fun = async() => {
            if(!user){
                await axios.get(USER_INFO_ROUTE, { withCredentials: true })
                .then((res) => {
                    setUser(res.data)
                })
                .catch((err) => {
                    router.replace("/")
                })
            }
        }
        fun();
    },[user, setUser, router])
    
    const handleSubmit = async(e: React.FormEvent) => { // izveidots jauns pasākums
        e.preventDefault();

        const inputDate = new Date(date)
        inputDate.setHours(inputDate.getHours() + 3);

        const localTime = inputDate.toISOString()
        
        await axios.post(CREATE_EVENT, {title: title, location: loc, date: localTime, image: image}, { withCredentials: true })
        .then( async(res) => {
            await Promise.all(
                tType.map(t =>
                    axios.post(CREATE_TTYPE, { eventId: res.data.id, name: t.name, price: Number(t.price), qty: Number(t.qty)}, { withCredentials: true })
                )
            )
            setEventAdd(false)
        })
    }

    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">Events</h1>
                    <div className="w-full sm:w-max flex gap-4">
                        <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)}/>
                        {user?.role === 1 && (
                            <button className="h-10 px-2.5 hidden sm:flex items-center gap-2 rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 transition-colors cursor-pointer"  onClick={() => setEventAdd(true)}>
                                <PlusIcon className="size-4"/> Add Event
                            </button>
                        )}
                    </div>
                </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={`/events/${e.id}`} className="rounded-xl border border-neutral-200 shadow-sm overflow-hidden">
                                <div className="h-48 bg-cover bg-center" style={{backgroundImage: `url(${e.image?.trim() ? e.image : placeholder.src})`}}/>
                                <div className="p-6">
                                    <h1 className="text-2xl font-semibold leading-none tracking-tight mb-1.5">{e.title}</h1>
                                    <div className="flex items-center text-sm text-neutral-500 mb-2">
                                        <CalendarIcon className="size-4 mr-2"/>
                                        <span>{format(new Date(e.date), 'EEE dd.MM.yyyy HH:mm')}</span> 
                                    </div>
                                    <div className="flex items-center text-sm text-neutral-500 ">
                                        <MapPinIcon className="size-4 mr-2"/>
                                        <span>{e.location}</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 className={`min-h-screen w-screen p-4 flex items-end sm:items-center justify-center sm:justify-end fixed left-0 top-0 bg-black/80 transition-all duration-300 ${eventAdd ? "translate-y-0 sm:translate-x-0" : "translate-y-full sm:translate-y-0 sm:translate-x-full"} z-60`}>
                <div className="w-full max-w-md p-6 flex flex-col bg-white rounded-lg">
                    <div className="flex items-center justify-between mb-6">
                        <h1 className="text-xl font-semibold tracking-tight">Add event</h1>
                        <p className="py-1 px-2 border border-neutral-200 rounded-md cursor-pointer" onClick={() => setEventAdd(false)}>X</p>
                    </div>
                    <form className="flex flex-col gap-4 mb-4" onSubmit={handleSubmit}>
                        <div>
                            <span className="text-sm font-medium leading-none">Title</span>
                            <input type="text" className="w-full px-3 py-2 mt-2 outline-none border border-neutral-200 rounded-md" value={title} onChange={(e) => setTitle(e.target.value)}/>
                        </div>
                        <div>
                            <span className="text-sm font-medium leading-none">Location</span>
                            <input type="text" className="w-full px-3 py-2 mt-2 outline-none border border-neutral-200 rounded-md" value={loc} onChange={(e) => setLoc(e.target.value)}/>
                        </div>
                        <div>
                            <span className="text-sm font-medium leading-none">Date</span>
                            <input type="datetime-local" className="w-full px-3 py-2 mt-2 outline-none border border-neutral-200 rounded-md" value={date} onChange={(e) => setDate(e.target.value)}/>
                        </div>
                        <div>
                            <span className="text-sm font-medium leading-none">Image</span>
                            <input type="text" className="w-full px-3 py-2 mt-2 outline-none border border-neutral-200 rounded-md" value={image} onChange={(e) => setImage(e.target.value)}/>
                        </div>
                        <div>
                            <div className="flex items-center justify-between">
                                <span className="text-sm font-medium leading-none">Ticket types</span>
                                <p className="py-1 px-2 border border-neutral-200 rounded-md cursor-pointer" onClick={() => handleAddTicket()}>+</p>
                            </div>
                            <div className="w-full h-60 sm:h-80 px-3 mt-2 border border-neutral-200 rounded-md overflow-hidden">
                                {tType.length > 0 && (  
                                    <table className="w-full border-collapse">
                                        <thead>
                                            <tr>
                                                <th className="pr-1.5 py-2 text-sm font-semibold text-left">Name</th>
                                                <th className="pr-1.5 py-2 text-sm font-semibold text-left">Price</th>
                                                <th className="pr-1.5 py-2 text-sm font-semibold text-left">Qty</th>
                                                <th className="pr-1.5 py-2 text-sm font-semibold text-left"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {tType.map((t, i) => (
                                                <tr key={i} className="border-b border-neutral-200 first:border-t">
                                                    <td className="pr-1.5 py-2">
                                                        <input type="text" className="w-full px-3 py-2 outline-none border border-neutral-200 rounded-md" value={t.name} onChange={(e) => handleChange(i, 'name', e.target.value)}/>
                                                    </td>
                                                    <td className="pr-1.5 py-2">
                                                        <input type="number" inputMode="numeric" min={0} className="w-full px-3 py-2 outline-none border border-neutral-200 rounded-md" value={t.price} onChange={(e) => handleChange(i, 'price', e.target.value)}/>
                                                    </td>
                                                    <td className="pr-1.5 py-2">
                                                        <input type="number" inputMode="numeric" min={0} className="w-full px-3 py-2 outline-none border border-neutral-200 rounded-md" value={t.qty} onChange={(e) => handleChange(i, 'qty', e.target.value)}/>
                                                    </td>
                                                    <td className="pr-1.5 py-2">
                                                        <TrashIcon className="size-5 hover:stroke-red-500 cursor-pointer transition-colors" onClick={() => handleDeleteTicket(i)}/>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                )}
                            </div>
                        </div>
                        <input type="submit" className="h-10 rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 transition-colors cursor-pointer" value="Create" />
                    </form>
                </div>
            </div>
        </div>
    )
}