"use client";

import { useEffect, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ServerControls } from "@/components/ServerControls";
import { Analytics } from "@/components/Analytics";
import { PlayerManager } from "@/components/PlayerManager";
import { ChatBridge } from "@/components/ChatBridge";
import { ModManager } from "@/components/ModManager";
import { BackupManager } from "@/components/BackupManager";
import { LogViewer } from "@/components/LogViewer";

const TABS = [
  { value: "server", label: "Server" },
  { value: "players", label: "Players" },
  { value: "chat", label: "Chat" },
  { value: "mods", label: "Mods" },
  { value: "backups", label: "Backups" },
  { value: "logs", label: "Logs" },
];

export function AdminTabs() {
  const [mounted, setMounted] = useState(false);
  const [value, setValue] = useState<string>("server");

  useEffect(() => {
    setMounted(true);
    const hash = window.location.hash.replace("#", "");
    if (hash && TABS.some((t) => t.value === hash)) {
      setValue(hash);
      return;
    }
    const saved = localStorage.getItem("admin-tab");
    if (saved && TABS.some((t) => t.value === saved)) setValue(saved);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    localStorage.setItem("admin-tab", value);
    history.replaceState(null, "", `#${value}`);
  }, [value, mounted]);

  if (!mounted) return null;

  return (
    <Tabs
      value={value}
      onValueChange={(v) => setValue(v as string)}
      className="w-full"
    >
      <TabsList className="flex w-full flex-wrap h-auto sm:h-9 gap-1 p-1 overflow-x-auto justify-start sm:justify-center">
        {TABS.map((t) => (
          <TabsTrigger key={t.value} value={t.value} className="text-xs sm:text-sm">
            {t.label}
          </TabsTrigger>
        ))}
      </TabsList>

      <TabsContent value="server" className="mt-4 space-y-4 sm:space-y-6">
        <ServerControls />
        <Analytics />
      </TabsContent>
      <TabsContent value="players" className="mt-4">
        <PlayerManager />
      </TabsContent>
      <TabsContent value="chat" className="mt-4" keepMounted={false}>
        <ChatBridge />
      </TabsContent>
      <TabsContent value="mods" className="mt-4">
        <ModManager />
      </TabsContent>
      <TabsContent value="backups" className="mt-4">
        <BackupManager />
      </TabsContent>
      <TabsContent value="logs" className="mt-4" keepMounted={false}>
        <LogViewer />
      </TabsContent>
    </Tabs>
  );
}
