"use client"

import { useAppStore } from "@/lib/store";
import { useEffect, useState } from "react";
import { redirect, useRouter } from "next/navigation";
import { XCircleIcon, CheckCircleIcon, EyeIcon, EyeSlashIcon } from "@heroicons/react/24/outline"
import axios from "axios";
import { LOGIN_ROUTE, REGISTER_ROUTE, USER_INFO_ROUTE, EVENT_GET, TICKET_GET, TTYPE_GET } from "@/routes/routes";
import { Ticket } from "@prisma/client";

export default function Main(){
    const { setEvents, setTickets, setTTypes, setUser, user } = useAppStore()

    const router = useRouter();

    const [email, setEmail] = useState("")
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const [rPassword, setRPassword] = useState("")

    const [showPassword, setShowPassword] = useState(false)
    const [showRPassword, setShowRPassword] = useState(false)

    const [registring, setRegistring] = useState(false)

    const [errors, setErrors] = useState({ email: "", username: "", password: "", rPassword: ""})

    const handleSubmit = async(e: React.FormEvent) => { // funkcijas kas palaižas pēc submit
        e.preventDefault()

        setErrors({ email: "", username: "", password: "", rPassword: ""})

        const newErrors = {
            email: validateEmail(email),
            username: !username ? "Username is required" : "",
            password: !password ? "Password is required" : "",
            rPassword: password !== rPassword ? "Passwords do not match" : "",
        }

        const passwordMCriteria = passwordCriteria.every((c) => c.test(password))

        if(!passwordMCriteria && password && registring){
            newErrors.password = "Password does not meet all requirements"
        }

        setErrors(newErrors)

        if(!registring){
            await axios.post(LOGIN_ROUTE, {username, password}, { withCredentials: true })
            .then(async (res) => {
                await axios.get(USER_INFO_ROUTE, { withCredentials: true })
                .then((res) => {
                    appInit()
                    setUser(res.data)
                    redirect("/events")
                })
            })
            return
        }else{
            const hasErrors = Object.values(errors).some(error => error !== "");
            if(hasErrors) return

            await axios.post(REGISTER_ROUTE, {name, email, username, password}, { withCredentials: true })
            .then(async (res) => {
                await axios.get(USER_INFO_ROUTE, { withCredentials: true })
                .then((res) => {
                    setUser(res.data)
                    redirect("/")
                })
            })
            return
        }
    }

    const passwordCriteria = [// paroles kritēriji
        { id: "length", label: "At least 12 characters long", test: (pass: string) => pass.length >= 12 },
        { id: "lowercase", label: "Contains lowercase letters", test: (pass: string) => /[a-z]/.test(pass) },
        { id: "uppercase", label: "Contains uppercase letters", test: (pass: string) => /[A-Z]/.test(pass) },
        { id: "numbers", label: "Contains numbers", test: (pass: string) => /[0-9]/.test(pass) },
        { id: "symbols", label: "Contains symbols", test: (pass: string) => /[^a-zA-Z0-9]/.test(pass) },
    ]

    const validateEmail = (email: string) => { // epasta parbaude
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!email) return "Email is required"
        if (!emailRegex.test(email)) return "Invalid email format"
        return ""
    }

    const appInit = async () => { // datu ievākšana
        try {
            const [ eventRes, ticketRes, ttypeRes ] = await Promise.all([
                axios.get(EVENT_GET, { withCredentials: true }),
                axios.get(TICKET_GET, { withCredentials: true }),
                axios.get(TTYPE_GET, { withCredentials: true })
            ])

            let filteredTickets = ticketRes.data

            if(user?.role === 0){
                filteredTickets = ticketRes.data.filter((t: Ticket) => t.userId === user.id)
            }

            setEvents(eventRes.data)
            setTickets(filteredTickets)
            setTTypes(ttypeRes.data)
        }catch(err){
            console.error('Error fetching data:', err);
        }    
    }

    return(
        <div className="min-h-screen relative overflow-hidden">
            <div className="block absolute inset-0 bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500 animate-gradient"/>
            <div className="p-4 min-h-screen relative flex items-center justify-center">
                <div className="w-full max-w-md p-6 shadow-xl rounded-md sm:rounded-xl bg-white">
                    <h1 className="text-2xl font-semibold mb-4">{registring ? "Sign up" : "Sign in"}</h1>
                    <form onSubmit={handleSubmit} className="flex flex-col gap-4 mb-4">
                        {registring &&(
                            <div>
                                <span className="text-sm font-medium leading-none">Email</span>
                                <input type="email" className={`w-full px-3 py-2 mt-2 outline-none border border-neutral-200 ${errors.email && "border-red-500"} rounded-md`} value={email} onChange={(e) => setEmail(e.target.value)}/>
                                {errors.email && <p className="text-sm mt-2 text-red-500">{errors.email}</p>}
                            </div>
                        )}
                        <div>
                            <span className="text-sm font-medium leading-none">Username</span>
                            <input type="text" className={`w-full px-3 py-2 mt-2 outline-none border border-neutral-200 ${errors.username && "border-red-500"} rounded-md`} value={username} onChange={(e) => setUsername(e.target.value)}/>
                            {errors.username && <p className="text-sm mt-2 text-red-500">{errors.username}</p>}
                        </div>
                        <div>
                            <span className="text-sm font-medium leading-none">Password</span>
                            <div className={`flex border border-neutral-200 mt-2 ${errors.password && "border-red-500"} rounded-md`}>
                                <input type={showPassword ? "text" : "password"} className="grow px-3 py-2 outline-none" value={password} onChange={(e) => setPassword(e.target.value)}/>
                                <div className="h-10 px-2.5 flex items-center justify-center text-neutral-500 cursor-pointer" onClick={(e) => setShowPassword(!showPassword)}>
                                    {showPassword ? (
                                        <EyeSlashIcon className="h-4" />
                                    ) : (
                                        <EyeIcon className="h-4"/>
                                    )}
                                </div>
                            </div>
                            {errors.password && <p className="text-sm mt-2 text-red-500">{errors.password}</p>}
                        </div>
                        {(password.length > 0 && registring) && (
                            <div className="space-y-2">
                                <p className="text-sm font-medium">Password requirements:</p>
                                <ul className="space-y-1 text-sm">
                                    {passwordCriteria.map((c) => (
                                        <li key={c.id} className="flex items-center gap-2">
                                            {c.test(password) ? (
                                                <CheckCircleIcon className="h-4 text-base text-green-500"/>
                                            ): (
                                                <XCircleIcon className="h-4 text-base text-red-500"/>
                                            )}
                                            <span className={c.test(password) ?  "text-green-500" : "text-red-500"}>{c.label}</span>
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        )}
                        {registring && (
                            <div>
                                <span className="text-sm font-medium leading-none">Repeat Password</span>
                                <div className={`flex border border-neutral-200 mt-2 ${errors.rPassword && "border-red-500"} rounded-md`}>
                                    <input type={showRPassword ? "text" : "password"} className="grow px-3 py-2 outline-none" value={rPassword} onChange={(e) => setRPassword(e.target.value)}/>
                                    <div className="h-10 px-2.5 flex items-center justify-center text-neutral-500 cursor-pointer" onClick={(e) => setShowRPassword(!showRPassword)}>
                                        {showRPassword ? (
                                            <EyeSlashIcon className="h-4" />
                                        ) : (
                                            <EyeIcon className="h-4"/>
                                        )}
                                    </div>
                                </div>
                                {errors.rPassword && <p className="text-sm mt-2 text-red-500">{errors.rPassword}</p>}
                            </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={registring ? "Sign up" : "Sign in"} />
                    </form>
                    <p className="text-center text-neutral-500">{registring ? "Have an account?" : "Don't you have an account"}<span className="text-blue-600 font-semibold cursor-pointer" onClick={() => setRegistring(!registring)}>{registring ? " Sign in" : " Sign Up"}</span></p>
                </div>
            </div>
        </div>
    )
}