"use client";

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

const API_URL = "";

type MenuItem = { 
  id: number; 
  category: string; 
  name: string 
};

type FinalizedSummary = { pickup: string[]; kitchen: string[] };


export default function ModPage() {
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const [newItem, setNewItem] = useState("");
  const [newCategory, setNewCategory] = useState("main");
  const [editingItem, setEditingItem] = useState<MenuItem | null>(null);
  const [finalizeTime, setFinalizeTime] = useState("10:30");
  const router = useRouter();
  const [lastSummary, setLastSummary] = useState<FinalizedSummary | null>(null);


  const auth = (): Record<string, string> => {
    const token = localStorage.getItem("token");
    return token ? { Authorization: `Bearer ${token}` } : {};
  };

  // Redirect if not logged in
  useEffect(() => {
    const token = localStorage.getItem("token");
    if (!token) {
      router.push("/auth");
      return;
    }

    fetch(`${API_URL}/api/me`, { headers: { Authorization: `Bearer ${token}` } })
      .then((res) => res.json())
      .then((data) => {
        if (!data.role || data.role > 50) {
          router.push("/landing");
        }
      })
      .catch(() => router.push("/auth"));
  }, [router]);

  // Load menu
  useEffect(() => {
    fetch(`${API_URL}/api/mod/menu`, { headers: auth() })
      .then((res) => res.json())
      .then((data: MenuItem[]) => setMenuItems(data || []))
      .catch(() => setMenuItems([]));
  }, []);

  // Load finalize time
  useEffect(() => {
    fetch(`${API_URL}/api/mod/finalize/time`, { headers: auth() })
      .then((r) => r.json())
      .then((data) => setFinalizeTime(data.time));
  }, []);

  useEffect(() => {
    loadLastSummary();
  }, []);

  async function refreshMenu() {
    const res = await fetch(`${API_URL}/api/mod/menu`, { headers: auth() });
    const data = await res.json();
    setMenuItems(data || []);
  }

  async function addMenuItem() {
    await fetch(`${API_URL}/api/mod/menu`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify({ action: "add", category: newCategory, name: newItem }),
    });
    setNewItem("");
    await refreshMenu();
  }

  async function updateMenuItem() {
    if (!editingItem) return;
    await fetch(`${API_URL}/api/mod/menu`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify({ action: "update", id: editingItem.id, name: editingItem.name }),
    });
    setEditingItem(null);
    await refreshMenu();
  }

  async function deleteMenuItem(id: number) {
    await fetch(`${API_URL}/api/mod/menu`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify({ action: "delete", id }),
    });
    await refreshMenu();
  }

  async function saveFinalizeTime() {
    await fetch(`${API_URL}/api/mod/finalize/time`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify({ time: finalizeTime }),
    });
  }

  async function triggerFinalizeNow() {
    await fetch(`${API_URL}/api/mod/finalize/now`, {
      method: "POST",
      headers: auth(),
    });
    await loadLastSummary();
  }

  async function loadLastSummary() {
    const res = await fetch(`${API_URL}/api/mod/finalize/last`, { headers: auth() });
    const data = await res.json();
    if (data.status !== "none") setLastSummary(data);
    else setLastSummary(null);
  }


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

      {/* Menu Management Panel */}
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Menü szerkesztő
      </h2>

      <div className="glass-panel w-full max-w-6xl p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {["soup", "main", "side"].map((cat) => (
            <div key={cat} className="flex flex-col">
              <h3 className="text-center text-xl font-semibold text-white mb-2">
                {cat === "soup" ? "Levesek" : cat === "main" ? "Főételek" : "Köretek"}
              </h3>

              <div className="max-h-[300px] overflow-y-auto space-y-2">
                {menuItems.filter((i) => i.category === cat).map((item) => (
                  <Card
                    key={item.id}
                    className="glass-panel flex flex-col lg:flex-row md:items-center sm:justify-between p-2 gap-2"
                  >
                    {editingItem?.id === item.id ? (
                      <div className="flex flex-col lg:flex-row gap-2 w-full items-center justify-between">
                        <Input
                          value={editingItem.name}
                          onChange={(e) =>
                            setEditingItem({ ...editingItem, name: e.target.value })
                          }
                          className="bg-white/70 text-black sm:w-40 border-white"
                        />
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            onClick={updateMenuItem}
                            className="bg-green-600 hover:bg-green-700 px-3"
                          >
                            Mentés
                          </Button>
                          <Button
                            size="sm"
                            onClick={() => setEditingItem(null)}
                            className="bg-gray-600 hover:bg-gray-700 px-3"
                          >
                            Mégse
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <>
                        <span className="text-white font-medium">{item.name}</span>
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            onClick={() => setEditingItem(item)}
                            className="bg-black/35 hover:bg-blue-700/35 px-3"
                          >
                            Szerk.
                          </Button>
                          <Button
                            size="sm"
                            onClick={() => deleteMenuItem(item.id)}
                            className="bg-red-600 hover:bg-red-700 px-3"
                          >
                            Töröl
                          </Button>
                        </div>
                      </>
                    )}
                  </Card>
                ))}
              </div>

              {/* Add new item for this category */}
              <div className="flex flex-col sm:flex-row gap-2 mt-3">
                <Input
                  placeholder={`Új ${cat === "soup" ? "Soup" : cat === "main" ? "Main" : "Side"}`}
                  value={newCategory === cat ? newItem : ""}
                  onChange={(e) => {
                    setNewItem(e.target.value);
                    setNewCategory(cat);
                  }}
                  className="bg-white/70 text-black sm:w-2/3 border-white"
                />
                <Button
                  size="sm"
                  onClick={addMenuItem}
                  className="bg-green-600 hover:bg-green-700 px-4"
                >
                  Hozzáad
                </Button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Order Finalization Panel */}
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Rendelési időkorlát
      </h2>

      <div className="glass-panel flex flex-col sm:items-center w-full max-w-3xl p-4 space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center gap-3">
          <input
            type="time"
            value={finalizeTime}
            onChange={(e) => setFinalizeTime(e.target.value)}
            className="bg-white/70 text-black rounded px-2 py-1 border border-white w-full sm:w-40"
          />
          <Button
            onClick={saveFinalizeTime}
            className="bg-green-600 hover:bg-green-700 px-4 w-full sm:w-auto"
          >
            Időpont Mentése
          </Button>
          <Button
            onClick={triggerFinalizeNow}
            className="bg-red-600 hover:bg-red-700 px-4 w-full sm:w-auto"
          >
            Finalize Orders Now
          </Button>
        </div>
      </div>

      {/* Finalized Order Summary Panel */}
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Legutóbbi összesítés
      </h2>

      <div className="glass-panel w-full max-w-4xl p-4 space-y-4">
        {lastSummary ? (
            <>
            <div>
                <h3 className="text-xl font-semibold text-white mb-2">Pickup nézet</h3>
                <ul className="list-disc list-inside text-white space-y-1">
                {lastSummary.pickup.map((line, idx) => (
                    <li key={idx}>{line}</li>
                ))}
                </ul>
            </div>

            <div>
                <h3 className="text-xl font-semibold text-white mb-2">Konyha nézet</h3>
                <ul className="list-disc list-inside text-white space-y-1">
                {lastSummary.kitchen.map((line, idx) => (
                    <li key={idx}>{line}</li>
                ))}
                </ul>
            </div>
            </>
        ) : (
            <p className="text-white italic">Nincs elérhető összesítés.</p>
        )}
      </div>


    </main>
  );
}
