"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { TopBar } from "@/components/ui/topbar";

const API_URL = "";

type Order = {
  id: number;
  username: string;
  soup?: string;
  main: string;
  side: string;
  created_at: string;
  status: string;
};

export default function LandingPage() {
  const [username, setUsername] = useState<string | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);
  const router = useRouter();
  const [finalizeTime, setFinalizeTime] = useState("10:30");

  // Load username + initial active orders
  useEffect(() => {
    const storedUser = localStorage.getItem("username");
    const token = localStorage.getItem("token");

    if (!storedUser || !token) {
      router.push("/auth");
      return;
    }

    setUsername(storedUser);

    fetch(`${API_URL}/api/orders`)
      .then((res) => res.json())
      .then((data: Order[]) => setOrders(data || []))
      .catch(() => setOrders([]));
  }, [router]);

  // Live updates via SSE
  useEffect(() => {
    const es = new EventSource(`${API_URL}/api/orders/stream`);

    es.onmessage = (e) => {
      if (!e.data || e.data.startsWith(":")) return;

      try {
        const msg = JSON.parse(e.data);

        if (msg.event === "deleted") {
          setOrders((prev) => prev.filter((o) => o.id !== Number(msg.id)));
        } else if (msg.event === "updated") {
          setOrders((prev) =>
            prev.map((o) =>
              o.id === Number(msg.id) ? { ...o, status: msg.status } : o
            )
          );
        } else {
          const ord: Order = msg;
          setOrders((prev) => {
            const filtered = prev.filter((o) => o.id !== ord.id);
            return [ord, ...filtered];
          });
        }
      } catch (err) {
        console.warn("Failed to parse SSE data:", e.data, err);
      }
    };

    es.onerror = () => es.close();
    return () => es.close();
  }, []);

  useEffect(() => {
    fetch(`${API_URL}/api/finalize/time`)
      .then((r) => r.json())
      .then((data) => setFinalizeTime(data.time))
      .catch(() => setFinalizeTime("10:30"));
  }, []);

  if (!username) return null;

  return (
    <main className="relative flex flex-col min-h-screen items-center p-6 space-y-8">
      <TopBar />
      <div className="h-16" />

      {/* My orders */}
      {orders.some((o) => o.username === username) && (
        <>
          <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-4">
            Rendeléseim
          </h2>

          {orders
            .filter((o) => o.username === username)
            .map((o) => (
              <Card
                className="glass-panel w-full max-w-3xl text-center"
                key={o.id}
              >
                <CardContent className="text-white py-4">
                  <p>
                    {o.soup && o.soup.trim() !== "" ? `${o.soup}, ` : ""}
                    {o.main}, {o.side}
                  </p>
                  <p className="text-sm text-white/60">
                    {new Date(o.created_at).toLocaleString()}
                  </p>
                </CardContent>
                <CardContent className="flex justify-center pb-4">
                  <Button
                    variant="food"
                    onClick={async () => {
                      const token = localStorage.getItem("token");
                      await fetch(`${API_URL}/api/orders/${o.id}`, {
                        method: "DELETE",
                        headers: { Authorization: `Bearer ${token}` },
                      });
                      setOrders((prev) =>
                        prev.filter((ord) => ord.id !== o.id)
                      );
                    }}
                    className="sm:w-1/2 lg:w-1/3 bg-gray-900/55 hover:bg-white/35"
                  >
                    Törlés
                  </Button>
                </CardContent>
              </Card>
            ))}
        </>
      )}

      {/* If no orders, show message */}
      {!orders.some((o) => o.username === username) && (
        <p className="text-white/70">Ma még nem rendeltél.</p>
      )}

      {/* New order button */}

      <p className="text-2xl text-white/80 text-center mt-2 ">
        A rendeléseket minden nap {finalizeTime}-kor zárjuk le. Addig tudsz
        választani!
      </p>
      <Button
        variant="food"
        onClick={() => router.push("/menu")}
        className="sm:w-1/2 lg:w-1/3"
      >
        Új rendelés
      </Button>

      {/* Global orders */}
      <hr className="w-full border-t border-white/30 my-6" />
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-4">
        Aktív rendelések
      </h2>

      <Card className="glass-panel w-full max-w-3xl pt-2 pb-2">
        <CardContent className="text-white space-y-2 max-h-[300px] overflow-y-auto">
          {orders.length > 0 ? (
            orders.map((o) => (
              <p key={o.id} className="text-center">
                <strong>{o.username}:</strong>{" "}
                {o.soup && o.soup.trim() !== "" ? `${o.soup}, ` : ""}
                {o.main}, {o.side}
              </p>
            ))
          ) : (
            <p className="text-center text-white/70">Nincs aktív rendelés</p>
          )}
        </CardContent>
      </Card>
    </main>
  );
}
