"use client";

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

const API_URL = "";

type User = {
  id: number;
  username: string;
  role: number;
};

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

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

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

export default function AdminPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [editing, setEditing] = useState<number | null>(null);
  const [newUsername, setNewUsername] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [newRole, setNewRole] = useState<number | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedOrders, setSelectedOrders] = useState<number[]>([]);
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const [newItem, setNewItem] = useState("");
  const [newCategory, setNewCategory] = useState("main");
  const [editingItem, setEditingItem] = useState<MenuItem | null>(null);
  const router = useRouter();
  const [finalizeTime, setFinalizeTime] = useState("10:30");
  const [lastSummary, setLastSummary] = useState<FinalizedSummary | null>(null);

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

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

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

    fetch(`${API_URL}/api/me`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((res) => {
        console.log(res);
        return res.json();
      })
      .then((data: { role?: number; username?: string }) => {
        if (data.role == undefined || data.role > 1) {
          console.log(data);
          console.log("Not admin, redirecting");
          router.push("/landing");
        }
      })
      .catch(() => router.push("/auth"));
  }, [router]);

  useEffect(() => {
    fetch(`${API_URL}/api/admin/users`, { headers: auth() })
      .then((r) => (r.ok ? r.json() : []))
      .then(setUsers)
      .catch(() => setUsers([]));
  }, []);

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

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

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

  async function refreshOrders() {
    try {
      const res = await fetch(`${API_URL}/api/admin/orders`, {
        headers: auth(),
      });
      if (res.ok) {
        const data: Order[] = await res.json();
        setOrders(data || []);
      } else {
        setOrders([]);
      }
    } catch {
      setOrders([]);
    }
  }

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

  async function addMenuItem() {
    await fetch(`${API_URL}/api/admin/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/admin/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/admin/menu`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify({ action: "delete", id }),
    });
    await refreshMenu();
  }

  async function deleteUser(id: number) {
    if (!confirm("Biztos törlöd a felhasználót?")) return;
    await fetch(`${API_URL}/api/admin/users/${id}`, {
      method: "DELETE",
      headers: auth(),
    });
    setUsers((prev) => prev.filter((u) => u.id !== id));
  }

  async function updateUser(id: number) {
    const body: {
      username?: string;
      password?: string;
      role?: number;
    } = {};

    if (newUsername) body.username = newUsername;
    if (newPassword) body.password = newPassword;
    if (newRole !== null) body.role = newRole;

    await fetch(`${API_URL}/api/admin/users/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json", ...auth() },
      body: JSON.stringify(body),
    });

    setUsers((prev) =>
      prev.map((u) =>
        u.id === id ? { ...u, username: body.username || u.username } : u
      )
    );

    setUsers((prev) =>
      prev.map((u) =>
        u.id === id
          ? {
              ...u,
              username: body.username ?? u.username,
              role: body.role ?? u.role,
            }
          : u
      )
    );

    setEditing(null);
    setNewUsername("");
    setNewPassword("");
    setNewRole(null);
  }

  function toggleSelect(id: number) {
    setSelectedOrders((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );
  }

  async function updateStatusSelected(status: string) {
    for (const id of selectedOrders) {
      await fetch(`${API_URL}/api/admin/orders/${id}/status`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", ...auth() },
        body: JSON.stringify({ status }),
      });
    }

    setSelectedOrders([]);
    await refreshOrders(); // always refresh after
  }

  async function deleteSelected() {
    await Promise.all(
      selectedOrders.map(async (id) => {
        await fetch(`${API_URL}/api/admin/orders/${id}/status`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ status: "history" }),
        });
        await fetch(`${API_URL}/api/admin/orders/${id}`, {
          method: "DELETE",
          headers: auth(),
        });
      })
    );
    const res = await fetch(`${API_URL}/api/admin/orders`);
    setSelectedOrders([]);
    await refreshOrders();
  }

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

  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);
  }

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

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

      <h1 className="text-white text-3xl sm:text-4xl font-bold text-center">
        Users
      </h1>

      <div className="w-full max-w-3xl">
        <div className="glass-panel max-h-[400px] overflow-y-auto space-y-4 p-4">
          {users.length > 0 ? (
            users.map((u) => (
              <Card
                key={u.id}
                className="glass-panel flex flex-col sm:flex-row sm:items-center sm:justify-between p-4 gap-3"
              >
                {editing === u.id ? (
                  <div className="flex flex-col sm:flex-row gap-2 w-full items-center justify-between">
                    {/* Keep current username visible */}
                    <span className="text-white font-medium">
                      {u.username}{" "}
                      <span className="text-sm text-white/60">
                        (role: {u.role})
                      </span>
                    </span>

                    {/* Inputs + buttons */}
                    <div className="flex flex-col sm:flex-row gap-2">
                      <Input
                        placeholder="New Username"
                        value={newUsername}
                        onChange={(e) => setNewUsername(e.target.value)}
                        className="bg-white/70 text-black sm:w-40 border-white"
                      />
                      <Input
                        type="password"
                        placeholder="New Password"
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        className="bg-white/70 text-black sm:w-40 border-white"
                      />
                      <Input
                        type="number"
                        placeholder="Role"
                        value={newRole !== null ? newRole : ""}
                        onChange={(e) => setNewRole(Number(e.target.value))}
                        className="bg-white/70 text-black sm:w-20 border-white"
                      />
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          onClick={() => updateUser(u.id)}
                          className="bg-black/35 hover:bg-green-700/35 px-3"
                        >
                          Save
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => setEditing(null)}
                          className="bg-black/35 hover:bg-blue-700/35 px-3"
                        >
                          Cancel
                        </Button>
                      </div>
                    </div>
                  </div>
                ) : (
                  <>
                    <span className="text-white font-medium">
                      {u.username}{" "}
                      <span className="text-sm text-white/60">
                        (role: {u.role})
                      </span>
                    </span>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        onClick={() => setEditing(u.id)}
                        className="bg-black/35 hover:bg-blue-700/35 px-3"
                      >
                        Edit
                      </Button>
                      <Button
                        size="sm"
                        onClick={() => deleteUser(u.id)}
                        className="bg-red-600 hover:bg-red-700 px-3"
                      >
                        Delete
                      </Button>
                    </div>
                  </>
                )}
              </Card>
            ))
          ) : (
            <p className="text-white/70 text-center">No registered users.</p>
          )}
        </div>
      </div>

      {/* Orders panel */}
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Orders
      </h2>

      <div className="glass-panel w-full max-w-3xl">
        <div className="max-h-[400px] overflow-y-auto space-y-2 p-4">
          {orders.length > 0 ? (
            orders.map((o) => (
              <Card
                key={o.id}
                onClick={() => toggleSelect(o.id)}
                className={`glass-panel p-3 cursor-pointer ${
                  selectedOrders.includes(o.id) ? "ring-2 ring-orange-400" : ""
                }`}
              >
                <CardContent className="text-white flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2">
                  <div>
                    <strong>{o.username}:</strong>{" "}
                    {o.soup && o.soup.trim() !== "" ? `${o.soup}, ` : ""}
                    {o.main}, {o.side}
                    <span
                      className={`ml-2 px-2 py-0.5 rounded text-xs ${
                        o.status === "active"
                          ? "bg-green-600/70"
                          : o.status === "history"
                          ? "bg-gray-600/70"
                          : "bg-red-600/70"
                      }`}
                    >
                      {o.status}
                    </span>
                  </div>
                  <span className="text-sm text-white/60">
                    {new Date(o.created_at).toLocaleString()}
                  </span>
                </CardContent>
              </Card>
            ))
          ) : (
            <p className="text-white/70 text-center">No orders to display.</p>
          )}
        </div>

        {/* Action buttons */}
        <div className="flex gap-3 justify-center mt-4 pb-4">
          <Button
            size="sm"
            variant="ghost"
            onClick={refreshOrders}
            className="text-white hover:bg-blue-700/40 rounded-full p-2"
            title="Frissítés"
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
          <Button
            size="sm"
            className="bg-green-600 hover:bg-green-700 px-4"
            onClick={() => updateStatusSelected("active")}
          >
            Set Active
          </Button>
          <Button
            size="sm"
            className="bg-gray-600 hover:bg-gray-700 px-4"
            onClick={() => updateStatusSelected("history")}
          >
            Set History
          </Button>
          <Button
            size="sm"
            className="bg-red-600 hover:bg-red-700 px-4"
            onClick={deleteSelected}
          >
            Delete
          </Button>
        </div>
      </div>

      {/* Menu Management Panel */}
      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Menu Editor
      </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"
                  ? "Soups"
                  : cat === "main"
                  ? "Main courses"
                  : "Sides"}
              </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"
                            >
                              Save
                            </Button>
                            <Button
                              size="sm"
                              onClick={() => setEditingItem(null)}
                              className="bg-gray-600 hover:bg-gray-700 px-3"
                            >
                              Cancel
                            </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"
                            >
                              Edit
                            </Button>
                            <Button
                              size="sm"
                              onClick={() => deleteMenuItem(item.id)}
                              className="bg-red-600 hover:bg-red-700 px-3"
                            >
                              Del
                            </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"
                >
                  Add
                </Button>
              </div>
            </div>
          ))}
        </div>
      </div>

      <h2 className="text-white text-2xl sm:text-3xl font-semibold text-center mt-8">
        Order Finalization
      </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"
          >
            Save Time
          </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">
                Átvételi 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>
  );
}
