"use client"

import { useAppStore } from "@/lib/store";
import { CalendarIcon, MapPinIcon } from "@heroicons/react/24/outline";
import { redirect, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { format, toDate } from "date-fns"
import { useQRCode } from 'next-qrcode';
import axios from "axios";
import { USER_INFO_ROUTE } from "@/routes/routes";
import Navigation from "@/components/Navigation";

export default function Profile(){
    const { tickets, user, events, tTypes, setUser } = useAppStore()
    const { Canvas } = useQRCode();
    const router = useRouter()

    const [sTicket, setSTicket] = useState<UserTicket | null>(null)
    const [tDialog, setTDialog] = useState(false)

    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])

    type UserTicket = {
        id: string
        ticketNr: string
        userId: string | null
        eventId: string
        tTypeId: string
        user: {
            id: string
        }
        event: {
            id: string;
            title: string;
            location: string;
            date: Date;
        }
        tType: {
            id: string;
            eventId: string;
            title: string
        };
    }

    const uTickets: UserTicket[] = tickets.filter(t => t.userId === user?.id).map(t => { // definēts tips
        const event = events.find(e => e.id === t.eventId)
        const tType = tTypes.find(tt => tt.id === t.ttypeId)

        if (!event || !tType) {
            throw new Error(`Missing related data for ticket ${t.ticketnr}`);
        }

        return {
            id: t.id,
            ticketNr: t.ticketnr,
            eventId: t.eventId,
            tTypeId: t.ttypeId,
            user: {
                id: user?.id
            },
            event:{
                id: event.id,
                title: event.title,
                location: event.location,
                date: event.date,
            },
            tType:{
                id: tType.id,
                eventId: tType.eventId,
                title: tType.name
            },
        }
    }).filter(Boolean) as UserTicket[]

    const openTdata = (t: UserTicket) => {
        setSTicket(t)
        setTDialog(true)
    }

    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-3xl font-bold tracking-tight mb-6">Profile</h1>
                <div className="px-3 py-4 sm:p-6 border border-neutral-200 rounded-md mb-4 sm:mb-0">
                    {uTickets.length > 0 ? (
                        <div className="flex flex-col gap-y-6">
                            <h1 className="text-2xl font-semibold tracking-tight">Tickets</h1>
                            <div className="flex flex-col gap-2">
                                {uTickets.map((t) => (
                                    <div key={t.id} className="p-6 border border-neutral-200 rounded-lg space-y-2" onClick={() => openTdata(t)}>
                                        <h1 className="font-semibold text-lg">{t.event.title}</h1>
                                        <div className="flex items-center text-sm text-neutral-500">
                                            <CalendarIcon className="size-4 mr-2"/>
                                            <span>{format(new Date(t.event.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>{t.event.location}</span>
                                        </div>
                                        <p className="text-sm font-medium">Ticket: {t.tType.title}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ): (
                        <p className="text-center py-4 text-neutral-500">You don't have any tickets.</p>
                    )}
                </div>
            </div>
            <div className={`h-screen w-screen p-4 flex items-center justify-center fixed left-0 top-0 bg-black/80 transition-all duration-200 ${tDialog ? "translate-y-0" : "translate-y-full"} z-60`}>
                <div className="w-full max-w-md p-6 bg-white rounded-lg shadow-lg gap-4">
                    <div className="flex items-center justify-between">
                        <div className="space-y-1.5">
                            <h1 className="text-lg font-semibold leading-none tracking-tight">Ticket Details</h1>
                            <p className="text-sm text-neutral-500">Scan this QR code at the event entrance</p>
                        </div>
                        <p className="py-1 px-2 border border-neutral-200 rounded-md cursor-pointer" onClick={() => setTDialog(false)}>X</p>
                    </div>
                    {sTicket && (
                        <div className="flex flex-col items-center space-y-4 py-4">
                            <div className="p-4">
                                <Canvas text={sTicket.ticketNr} options={{margin: 3, scale: 4, width: 200}} />
                            </div>
                            <div className="text-center space-y-2">
                                <h1 className="text-lg font-bold">{sTicket.event.title}</h1>
                                <p className="text-sm font-medium">{sTicket.tType.title}</p>
                                <div className="flex items-center justify-center text-sm text-neutral-500">
                                    <CalendarIcon className="size-4 mr-2"/>
                                    <span>{format(new Date(sTicket.event.date), 'EEE dd.MM.yyyy HH:mm')}</span>
                                </div>
                                <div className="flex items-center justify-center text-sm text-neutral-500">
                                    <MapPinIcon className="size-4 mr-2"/>
                                    <span>{sTicket.event.location}</span>
                                </div>
                                <p className="text-xs text-neutral-500 mt-4">Ticket ID: {sTicket.ticketNr}</p>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}