'use client'
import { use, useEffect, useState, ChangeEvent } from 'react'
import { SingleCard } from "@/components/SingleCard/SingleCard";
import Form from "next/dist/client/form";
import { Button } from "@/components/Button";
import {DetailedTicket, getCategories, Ticket} from "@/components/Tickets";
import { getTicket } from "@/components/Tickets/getTicket";
import {sendRequestwTokenClient} from "@/app/actions/auth";

export default function Page({
                                 params,
                             }: {
    params: Promise<{ slug: string }>
}) {

    const StateMapping = ["A","B","C"]
    const PrioMapping = ["Niedrig","Mittel","Hoch","Notfall"]


    // Initialer State leer, damit wir keine Fehler bei undefined haben
    const [currentTicket, setCurrentTicket] = useState<DetailedTicket | null>(null);
    const [categories, setCategories] = useState<string[] | null>(null);

    const { slug } = use(params);
    const ticketId: number = Number(slug);


    useEffect(() => {
        const runAsync = async () => {
            const ticket = await getTicket(ticketId) || null;
            const category = await getCategories() || null;
            setCategories(category)
            setCurrentTicket(ticket);
        }
        runAsync();
    }, [ticketId]);

    // Zentraler Change-Handler für alle Inputs
    const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        console.log("IS CHANGED", name);

        setCurrentTicket((prev) => {
            if (!prev) return null;

            return {
                ...prev,
                [name]: value
            };
        });
    };

    const formAction = (e: FormData) => {
        // Hier kannst du die Daten an den Server schicken
        console.log("Form submitted with:", currentTicket);

        // Wenn du die Daten aus dem e: FormData Objekt ziehen willst (wie bisher):
        const ticket: Ticket = {
            status: Number(e.get("status")),
            priority: Number(e.get("priority")),
            category: e.get("category")?.toString(),
            ticketname: e.get("ticketname")?.toString() || "none",
            description: e.get("description")?.toString() || "none",
            username: currentTicket?.username || "none",
        };
        sendRequestwTokenClient(`/ticket/update/${ticketId}`, "POST",JSON.stringify(ticket))
        alert("Gespeichert!");
    };

    if (!currentTicket) return <div>Lade Ticket...</div>;
    console.log(currentTicket);
    return (
        <div className={"flex flex-col "}>
            <SingleCard>
                    <Form className={"flex flex-row grow justify-between"} action={formAction}>
                        <div className={"flex flex-col"}>
                            <div className={"flex flex-row"}>
                                <label className={"my-auto w-24"}>Ticketname</label>
                                <input
                                    type={"text"}
                                    name={"ticketname"}
                                    className={"bg-secondary/25 m-2 p-1 w-80"}
                                    value={currentTicket.ticketname}
                                    onChange={handleChange}
                                />
                            </div>
                            <div className={"flex flex-row"}>
                                <label className={"my-auto w-24 min-w-24"}>Status</label>
                                <select
                                    name={"status"}
                                    className={"bg-secondary/25 rounded p-2 m-2 w-80"}
                                    value={currentTicket.status}
                                    onChange={handleChange}
                                >
                                    {
                                        StateMapping?.map((value, index) => {
                                            return (<option key={`${value}-${index}`} value={index +1}>{value}</option>)
                                        })
                                    }
                                </select>
                            </div>
                            <div className={"flex flex-row align-items-center"}>
                                <label className={"my-auto w-24 min-w-24"}>Kategorie</label>
                                <select
                                    className={"bg-secondary/25 rounded p-2 m-2 w-80"}
                                    name={"category"}
                                    value={currentTicket.category}
                                    onChange={handleChange}
                                >
                                    {categories && categories?.map((value, index) => {
                                        return (<option key={`${value}-${index}`} value={value}>{value}</option>)
                                    })}
                                </select>
                            </div>
                            <div className={"flex flex-row"}>
                                <label className={"my-auto w-24 min-w-24"}>Priorität</label>
                                <select

                                    className={"bg-secondary/25 rounded p-2 m-2 w-80"}
                                    name={"priority"}
                                    value={currentTicket.priority}
                                    onChange={handleChange}
                                >
                                    {
                                        PrioMapping?.map((value, index) => {
                                            return (<option key={`${value}-${index}`} value={index +1}>{value}</option>)
                                        })
                                    }
                                </select>
                            </div>
                        </div>
                        <div className={"flex flex-col px-20 grow"}>
                            <label className={"my-auto w-24 min-w-24 m-2"}>Beschreibung</label>
                            <textarea
                                name="description"
                                className="bg-secondary/25 m-2 grow p-2 min-h-10 resize-none overflow-hidden wrap-break-word focus:outline-none"
                                rows={3}
                                value={currentTicket.description}
                                onChange={handleChange}
                            />
                        </div>
                        <Button type={"submit"} className={"w-min p-4 h-min m-auto text-xl"}>Bearbeiten</Button>
                    </Form>
            </SingleCard>
        </div>
    )
}