"use client";

import Link from "next/link";
import { useEffect, useState, useCallback } from "react";
import { api } from "@/app/adminx/admin-api";
import { Card, Badge, Button, Field, Input, ErrorNote } from "@/app/adminx/ui";
import { formatDateTime, formatDate } from "@/lib/utils";
import { ToolsSection } from "@/app/adminx/sections/ToolsSection";
import { PostsSection } from "@/app/adminx/sections/PostsSection";
import { CategoriesSection } from "@/app/adminx/sections/CategoriesSection";
import { ProvidersSection } from "@/app/adminx/sections/ProvidersSection";
import { MediaSection } from "@/app/adminx/sections/MediaSection";
import { MonetizationSection } from "@/app/adminx/sections/MonetizationSection";
import { MessagesSection } from "@/app/adminx/sections/MessagesSection";
import { SettingsSection } from "@/app/adminx/sections/SettingsSection";
import { StatusSection } from "@/app/adminx/sections/StatusSection";

interface Admin {
  id: number;
  username: string;
  email: string;
  mustChangePassword: boolean;
}

interface DashboardData {
  stats: any;
  recentPosts: any[];
  recentActivity: any[];
  usage: { today: number; month: number; errorsToday: number };
  topTools: any[];
  providerUsage: any[];
}

const NAV = [
  { key: "dashboard", label: "Dashboard", icon: "📊" },
  { key: "tools", label: "AI Tools", icon: "🛠️" },
  { key: "articles", label: "Articles", icon: "📝" },
  { key: "pages", label: "Pages", icon: "📄" },
  { key: "categories", label: "Categories", icon: "🗂️" },
  { key: "providers", label: "AI Providers", icon: "🔌" },
  { key: "media", label: "Media", icon: "🖼️" },
  { key: "monetization", label: "Monetization", icon: "💰" },
  { key: "messages", label: "Messages", icon: "✉️" },
  { key: "activity", label: "Activity", icon: "📜" },
  { key: "settings", label: "Settings", icon: "⚙️" },
  { key: "status", label: "System Status", icon: "📡" },
];

export function AdminShell({ section, admin }: { section: string; admin: Admin }) {
  const [dash, setDash] = useState<DashboardData | null>(null);

  useEffect(() => {
    if (section === "dashboard" || section === "activity") {
      api.get("dashboard").then(setDash).catch(() => {});
    }
  }, [section]);

  async function logout() {
    await api.post("logout", {});
    window.location.href = "/adminx";
  }

  const activeKey = NAV.some((n) => n.key === section) ? section : "dashboard";

  return (
    <div className="flex min-h-screen bg-slate-100">
      {/* Sidebar */}
      <aside className="fixed inset-y-0 left-0 z-30 flex w-16 flex-col border-r border-slate-200 bg-white lg:w-60">
        <div className="flex h-16 items-center gap-2 border-b border-slate-100 px-3 lg:px-5">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-indigo-600 to-violet-600 text-white">⚡</span>
          <span className="hidden text-sm font-bold text-slate-900 lg:block">Admin Panel</span>
        </div>
        <nav className="flex-1 space-y-1 overflow-y-auto p-2 lg:p-3">
          {NAV.map((n) => (
            <Link
              key={n.key}
              href={`/adminx/${n.key === "dashboard" ? "dashboard" : n.key}`}
              className={`flex items-center gap-3 rounded-lg px-2 py-2 text-sm font-medium transition lg:px-3 ${
                activeKey === n.key ? "bg-indigo-50 text-indigo-700" : "text-slate-600 hover:bg-slate-100"
              }`}
            >
              <span className="text-base">{n.icon}</span>
              <span className="hidden lg:block">{n.label}</span>
            </Link>
          ))}
        </nav>
        <div className="border-t border-slate-100 p-2 lg:p-3">
          <Link href="/" className="flex items-center gap-3 rounded-lg px-2 py-2 text-sm font-medium text-slate-600 hover:bg-slate-100 lg:px-3" target="_blank">
            <span>🌐</span>
            <span className="hidden lg:block">View website</span>
          </Link>
        </div>
      </aside>

      {/* Main */}
      <div className="ml-16 flex-1 lg:ml-60">
        <header className="sticky top-0 z-20 flex h-16 items-center justify-between border-b border-slate-200 bg-white px-4 lg:px-6">
          <h1 className="text-base font-semibold text-slate-900">
            {NAV.find((n) => n.key === activeKey)?.label || "Dashboard"}
          </h1>
          <div className="flex items-center gap-3">
            <span className="hidden text-sm text-slate-500 sm:block">{admin.username}</span>
            <button
              onClick={logout}
              className="rounded-lg border border-slate-300 px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50"
            >
              Logout
            </button>
          </div>
        </header>

        <main className="p-4 lg:p-6">
          {admin.mustChangePassword ? (
            <ChangePassword />
          ) : activeKey === "dashboard" ? (
            <Dashboard dash={dash} />
          ) : activeKey === "tools" ? (
            <ToolsSection />
          ) : activeKey === "articles" ? (
            <PostsSection pageType="post" />
          ) : activeKey === "pages" ? (
            <PostsSection pageType="page" />
          ) : activeKey === "categories" ? (
            <CategoriesSection />
          ) : activeKey === "providers" ? (
            <ProvidersSection />
          ) : activeKey === "media" ? (
            <MediaSection />
          ) : activeKey === "monetization" ? (
            <MonetizationSection />
          ) : activeKey === "messages" ? (
            <MessagesSection />
          ) : activeKey === "settings" ? (
            <SettingsSection />
          ) : activeKey === "status" ? (
            <StatusSection />
          ) : activeKey === "activity" ? (
            <ActivityLog dash={dash} />
          ) : (
            <Dashboard dash={dash} />
          )}
        </main>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
function ChangePassword() {
  const [current, setCurrent] = useState("");
  const [next, setNext] = useState("");
  const [confirm, setConfirm] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  async function submit() {
    setError("");
    if (next.length < 8) return setError("New password must be at least 8 characters.");
    if (next !== confirm) return setError("Passwords do not match.");
    setBusy(true);
    try {
      await api.post("password", { current, next });
      window.location.reload();
    } catch (e: any) {
      setError(e.message);
      setBusy(false);
    }
  }

  return (
    <div className="mx-auto max-w-md">
      <Card className="p-6">
        <div className="text-center">
          <span className="text-3xl">🔒</span>
          <h2 className="mt-2 text-lg font-bold text-slate-900">Change your password</h2>
          <p className="mt-1 text-sm text-slate-500">
            For security, you must change the default password before continuing.
          </p>
        </div>
        <div className="mt-6 space-y-4">
          <Field label="Current password"><Input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} /></Field>
          <Field label="New password (min 8 characters)"><Input type="password" value={next} onChange={(e) => setNext(e.target.value)} /></Field>
          <Field label="Confirm new password"><Input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} /></Field>
          <ErrorNote message={error} />
          <Button className="w-full" onClick={submit} disabled={busy || !current || !next}>
            {busy ? "Updating…" : "Update Password"}
          </Button>
        </div>
      </Card>
    </div>
  );
}

/* ------------------------------------------------------------------ */
function Dashboard({ dash }: { dash: DashboardData | null }) {
  const stats = dash?.stats;
  const cards = [
    { label: "Total tools", value: stats?.totalTools, color: "text-indigo-600" },
    { label: "Published articles", value: stats?.publishedPosts, color: "text-green-600" },
    { label: "Draft articles", value: stats?.draftPosts, color: "text-amber-600" },
    { label: "Categories", value: stats?.totalCategories, color: "text-violet-600" },
    { label: "AI providers", value: stats?.totalProviders, color: "text-sky-600" },
    { label: "Unread messages", value: stats?.unreadMessages, color: "text-rose-600" },
  ];

  return (
    <div className="space-y-6">
      {!dash ? (
        <p className="text-slate-500">Loading…</p>
      ) : (
        <>
          {/* Stat cards */}
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
            {cards.map((c) => (
              <Card key={c.label} className="p-4">
                <p className={`text-2xl font-bold ${c.color}`}>{c.value ?? 0}</p>
                <p className="mt-1 text-xs font-medium text-slate-500">{c.label}</p>
              </Card>
            ))}
          </div>

          {/* Status row */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">Monetization</p>
              <p className="mt-1 text-sm font-semibold text-slate-800">{stats?.monetization || "None"}</p>
            </Card>
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">Website status</p>
              <p className="mt-1 flex items-center gap-2 text-sm font-semibold capitalize text-slate-800">
                <span className={`h-2 w-2 rounded-full ${stats?.websiteStatus === "operational" ? "bg-green-500" : "bg-amber-500"}`} />
                {stats?.websiteStatus}
              </p>
            </Card>
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">API status</p>
              <p className="mt-1 text-sm font-semibold text-slate-800">
                {stats?.apiStatus === "connected" ? `Connected (${stats.enabledProviders} provider${stats.enabledProviders !== 1 ? "s" : ""})` : "Not configured"}
              </p>
            </Card>
          </div>

          {/* Usage */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">Requests today</p>
              <p className="mt-1 text-xl font-bold text-slate-900">{dash.usage.today}</p>
            </Card>
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">Requests this month</p>
              <p className="mt-1 text-xl font-bold text-slate-900">{dash.usage.month}</p>
            </Card>
            <Card className="p-4">
              <p className="text-xs font-medium text-slate-500">Errors today</p>
              <p className="mt-1 text-xl font-bold text-red-600">{dash.usage.errorsToday}</p>
            </Card>
          </div>

          {/* Quick actions */}
          <Card className="p-4">
            <p className="text-xs font-medium text-slate-500">Quick actions</p>
            <div className="mt-3 flex flex-wrap gap-2">
              {[
                { label: "+ New Tool", href: "/adminx/tools" },
                { label: "+ New Article", href: "/adminx/articles" },
                { label: "AI API Settings", href: "/adminx/providers" },
                { label: "Ad Settings", href: "/adminx/monetization" },
                { label: "SEO Settings", href: "/adminx/settings" },
                { label: "Website Settings", href: "/adminx/settings" },
              ].map((a) => (
                <Link key={a.label} href={a.href} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:border-indigo-200 hover:bg-indigo-50 hover:text-indigo-700">
                  {a.label}
                </Link>
              ))}
            </div>
          </Card>

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
            {/* Recent posts */}
            <Card className="p-5">
              <h3 className="font-semibold text-slate-900">Recent posts</h3>
              <ul className="mt-3 space-y-2.5">
                {dash.recentPosts.map((p) => (
                  <li key={p.id} className="flex items-center justify-between">
                    <span className="truncate text-sm text-slate-700">{p.title}</span>
                    <Badge color={p.status === "published" ? "green" : "slate"}>{p.status}</Badge>
                  </li>
                ))}
              </ul>
            </Card>

            {/* Provider usage */}
            <Card className="p-5">
              <h3 className="font-semibold text-slate-900">API provider usage</h3>
              <ul className="mt-3 space-y-2.5">
                {dash.providerUsage.length === 0 && <li className="text-sm text-slate-400">No requests yet.</li>}
                {dash.providerUsage.map((p, i) => (
                  <li key={i} className="flex items-center justify-between text-sm">
                    <span className="text-slate-700">{p.name}</span>
                    <span className="font-medium text-slate-900">{p.n}</span>
                  </li>
                ))}
              </ul>
            </Card>
          </div>

          {/* Recent activity */}
          <Card className="p-5">
            <h3 className="font-semibold text-slate-900">Recent admin activity</h3>
            {dash.recentActivity.length === 0 ? (
              <p className="mt-3 text-sm text-slate-400">No activity yet.</p>
            ) : (
              <ul className="mt-3 divide-y divide-slate-100">
                {dash.recentActivity.slice(0, 6).map((a) => (
                  <li key={a.id} className="flex items-center justify-between py-2 text-sm">
                    <div>
                      <span className="font-medium text-slate-800">{a.action}</span>
                      {a.detail && <span className="text-slate-500"> — {a.detail}</span>}
                    </div>
                    <span className="text-xs text-slate-400">{formatDateTime(a.createdAt)}</span>
                  </li>
                ))}
              </ul>
            )}
          </Card>

          {/* Top tools */}
          {dash.topTools.length > 0 && (
            <Card className="p-5">
              <h3 className="font-semibold text-slate-900">Most-used tools</h3>
              <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3">
                {dash.topTools.map((t, i) => (
                  <div key={i} className="flex items-center justify-between rounded-lg bg-slate-50 px-3 py-2">
                    <span className="truncate text-sm text-slate-700">{t.name}</span>
                    <span className="text-sm font-semibold text-slate-900">{t.n}</span>
                  </div>
                ))}
              </div>
            </Card>
          )}
        </>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
function ActivityLog({ dash }: { dash: DashboardData | null }) {
  return (
    <div>
      <Card className="p-5">
        <h3 className="font-semibold text-slate-900">Recent admin activity</h3>
        {!dash ? (
          <p className="mt-3 text-sm text-slate-500">Loading…</p>
        ) : dash.recentActivity.length === 0 ? (
          <p className="mt-3 text-sm text-slate-400">No activity yet.</p>
        ) : (
          <ul className="mt-3 divide-y divide-slate-100">
            {dash.recentActivity.map((a) => (
              <li key={a.id} className="flex items-center justify-between py-2.5 text-sm">
                <div>
                  <span className="font-medium text-slate-800">{a.action}</span>
                  {a.detail && <span className="text-slate-500"> — {a.detail}</span>}
                </div>
                <span className="text-xs text-slate-400">{formatDateTime(a.createdAt)}</span>
              </li>
            ))}
          </ul>
        )}
      </Card>
    </div>
  );
}
