"use client";

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

const API_URL = "";

type MenuOptions = {
  foetelek: string[];
  levesek: string[];
  koretek: string[];
};

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

function FoodList({
  items,
  onSelect,
  selected,
}: {
  items: string[];
  onSelect: (item: string) => void;
  selected: string;
}) {
  return (
    <div className="grid grid-cols-1 gap-2 pb-4">
      {items.map((item) => (
        <Card
          key={item}
          onClick={() => onSelect(selected === item ? "" : item)}
          className={`p-3 text-center cursor-pointer transition ${
            selected === item ? "food-option-selected" : "food-option"
          }`}
        >
          {item}
        </Card>
      ))}
    </div>
  );
}

export default function HomePage() {
  const [username, setUsername] = useState<string | null>(null);
  const [menu, setMenu] = useState<MenuOptions | null>(null);
  const [main, setMain] = useState("");
  const [soup, setSoup] = useState("");
  const [side, setSide] = useState("");
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);

  // Fetch menu options
  useEffect(() => {
    const storedUser = localStorage.getItem("username");
    const token = localStorage.getItem("token");

    if (storedUser && token) {
      setUsername(storedUser);
      fetch(`${API_URL}/api/options`, {
        headers: { Authorization: `Bearer ${token}` },
      })
        .then((res) => res.json())
        .then((data) => setMenu(data))
        .catch((err) => console.error("Failed to load options", err));
    } else {
      router.push("/auth");
    }
  }, [router]);

  // Fetch existing orders on load
  useEffect(() => {
    fetch(`${API_URL}/api/orders`)
      .then((res) => (res.ok ? res.json() : []))
      .then((data) => setOrders(data || []))
      .catch(() => setOrders([]));
  }, []);

  // Subscribe to live order updates (SSE)
  useEffect(() => {
    console.log("Opening SSE connection…");
    const es = new EventSource(`${API_URL}/api/orders/stream`);

    es.onopen = () => {
      console.log("SSE connection established ✅");
    };

    es.onmessage = (e) => {
      // console.log("SSE message received:", e.data);

      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 {
          const ord: Order = msg;
          setOrders((prev) => {
            const filtered = prev.filter((o) => o.username !== ord.username);
            return [ord, ...filtered];
          });
        }
      } catch (err) {
        console.warn("Failed to parse SSE data:", e.data, err);
      }
    };

    es.onerror = (err) => {
      console.error("SSE connection lost ❌", err);
      es.close();
    };

    return () => {
      console.log("Closing SSE connection…");
      es.close();
    };
  }, []);

  if (!username) return null;

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (!main || !side) {
      setError("Kérlek válassz legalább egy főételt és egy köretet!");
      setSuccess(null);
      return;
    }
    setError(null);

    const token = localStorage.getItem("token");
    if (!token) {
      router.push("/auth");
      return;
    }

    const res = await fetch(`${API_URL}/api/orders`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ main, soup, side }),
    });

    if (res.ok) {
      setSuccess("A rendelés sikeresen mentve!");
      setError(null);
      setSoup("");
      setMain("");
      setSide("");
      router.push("/landing");
    } else {
      setError("Nem sikerült menteni a rendelést.");
      setSuccess(null);
    }
  };

  return (
    <main className="relative flex flex-col min-h-screen items-center p-4 sm:p-6 space-y-6">
      <TopBar />
      <div className="h-8" /> {/* spacer for ribbon */}
      {/* Header with welcome text */}
      <div className="w-full max-w-6xl text-center">
        <h1 className="text-white text-3xl sm:text-4xl font-bold">
          No?... Mit együnk?
        </h1>
      </div>
      {menu ? (
        <form onSubmit={handleSubmit} className="w-full max-w-6xl space-y-6">
          {/* Selection panels */}
          <div className="flex flex-col md:flex-row gap-6 items-start">
            <div className="flex flex-col w-full md:w-1/3">
              <h2 className="text-center text-2xl sm:text-3xl text-white mb-2">
                Levesek
              </h2>
              <Card className="glass-panel flex flex-col">
                <CardContent className="pb-1 pt-5">
                  <FoodList
                    items={menu.levesek}
                    onSelect={setSoup}
                    selected={soup}
                  />
                </CardContent>
              </Card>
            </div>

            <div className="flex flex-col w-full md:w-1/3">
              <h2 className="text-center text-2xl sm:text-3xl text-white mb-2">
                Főételek
              </h2>
              <Card className="glass-panel flex flex-col">
                <CardContent className="pb-1 pt-5">
                  <FoodList
                    items={menu.foetelek}
                    onSelect={setMain}
                    selected={main}
                  />
                </CardContent>
              </Card>
            </div>

            <div className="flex flex-col w-full md:w-1/3">
              <h2 className="text-center text-2xl sm:text-3xl text-white mb-2">
                Köretek
              </h2>
              <Card className="glass-panel flex flex-col">
                <CardContent className="pb-1 pt-5">
                  <FoodList
                    items={menu.koretek}
                    onSelect={setSide}
                    selected={side}
                  />
                </CardContent>
              </Card>
            </div>
          </div>

          {/* My Choice */}
          <div className="relative flex flex-col items-center p-6 ">
            <Card className="glass-panel pt-4 w-full md:w-1/3">
              <CardHeader>
                <CardTitle className="text-center text-2xl sm:text-3xl text-white">
                  Szóval...
                </CardTitle>
              </CardHeader>
              <CardContent className="text-white text-center space-y-2">
                {soup && (
                  <p>
                    <strong>Leves:</strong> {soup}
                  </p>
                )}
                {(main || side) && (
                  <p>
                    <strong>Második:</strong>{" "}
                    {[main, side].filter(Boolean).join(", ")}
                  </p>
                )}
                {!soup && !main && !side && <p>–</p>}
              </CardContent>
              <CardContent className="flex flex-col items-center w-full pt-3 pb-4">
                <Button
                  type="submit"
                  variant="food"
                  className="w-full sm:w-1/3 lg:w-1/3"
                >
                  Mehet!
                </Button>
                {error && (
                  <p className="mt-2 text-center text-red-400">{error}</p>
                )}
                {success && (
                  <p className="mt-2 text-center text-green-400">{success}</p>
                )}
              </CardContent>
            </Card>
          </div>
        </form>
      ) : (
        <p className="text-white">Étlap betöltése…</p>
      )}
    </main>
  );
}
