"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import MainTitle from "@/components/layout/dashboard/main-title";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { KeyRound, ListChecks, Shield, Users } from "lucide-react";
import { toast } from "sonner";

type Stats = {
  userCount: number;
  clientCount: number;
  roleCount: number;
  permissionCount: number;
};

export default function SuperAdminHome() {
  const { app } = useParams() as { app: string };
  const base = `/${app}`;
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await DataService.get("/admin/dashboard-stats");
        if (!cancelled) setStats(res.data?.data ?? null);
      } catch (e) {
        if (!cancelled) {
          setError(true);
          toast.error(getApiErrorMessage(e, "Could not load dashboard stats"));
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const cards: {
    title: string;
    description: string;
    count: number | string;
    href: string;
    icon: React.ReactNode;
  }[] = stats
    ? [
        {
          title: "Users",
          description: "Accounts you can manage (your account is hidden)",
          count: stats.userCount,
          href: `${base}/admin/users`,
          icon: <Users className="size-8 text-primary" />,
        },
        {
          title: "API clients",
          description: "OAuth-style client IDs (secrets stored hashed)",
          count: stats.clientCount,
          href: `${base}/admin/clients`,
          icon: <KeyRound className="size-8 text-primary" />,
        },
        {
          title: "Roles",
          description: "Roles and visibility rules",
          count: stats.roleCount,
          href: `${base}/admin/roles`,
          icon: <Shield className="size-8 text-primary" />,
        },
        {
          title: "Permissions",
          description: "Permission keys assigned to roles",
          count: stats.permissionCount,
          href: `${base}/admin/permissions`,
          icon: <ListChecks className="size-8 text-primary" />,
        },
      ]
    : [];

  return (
    <div className="space-y-6">
      <MainTitle title="Super admin dashboard" />
      <p className="text-sm text-gray-600">
        Overview of users, API clients, roles, and permissions. Open a card to manage that area.
      </p>

      {error && (
        <p className="text-sm text-red-600">Could not load statistics. Check your connection.</p>
      )}

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {!stats && !error && (
          <>
            {[1, 2, 3, 4].map((i) => (
              <Card key={i} className="animate-pulse bg-white">
                <CardHeader className="h-28 rounded-t-lg bg-gray-100" />
              </Card>
            ))}
          </>
        )}
        {cards.map((c) => (
          <Link key={c.href} href={c.href} className="block transition hover:opacity-95">
            <Card className="h-full bg-white shadow-sm hover:border-primary/40">
              <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
                <div>
                  <CardTitle className="text-lg font-semibold text-gray-800">{c.title}</CardTitle>
                  <CardDescription className="mt-1 line-clamp-2">{c.description}</CardDescription>
                </div>
                {c.icon}
              </CardHeader>
              <CardContent>
                <p className="text-4xl font-bold tabular-nums text-gray-900">{c.count}</p>
                <p className="mt-2 text-xs font-medium text-primary">View →</p>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
