"use client";

import { useState, useEffect } from "react";
import { fetchApi } from "@/lib/api-client";
import { useAuth } from "@/components/auth-provider";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Users, FileText, ShieldAlert, Settings, ArrowRight } from "lucide-react";
import Link from "next/link";

export default function AdminDashboard() {
  const { user } = useAuth();
  const [stats, setStats] = useState([
    { title: "Total Users", value: "...", icon: Users, color: "text-blue-500" },
    { title: "Active Articles", value: "...", icon: FileText, color: "text-green-500" },
    { title: "Pending Reports", value: "...", icon: ShieldAlert, color: "text-red-500" },
    { title: "System Status", value: "Healthy", icon: Settings, color: "text-purple-500" },
  ]);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const [usersData, guidesData, postsData] = await Promise.all([
          fetchApi("admin/users.php"),
          fetchApi("admin/content.php?type=guides"),
          fetchApi("admin/content.php?type=posts")
        ]);

        setStats([
          { title: "Total Users", value: usersData.length.toString(), icon: Users, color: "text-blue-500" },
          { title: "Active Articles", value: guidesData.length.toString(), icon: FileText, color: "text-green-500" },
          { title: "Pending Reports", value: postsData.filter((p: any) => p.status === 'flagged').length.toString(), icon: ShieldAlert, color: "text-red-500" },
          { title: "System Status", value: "Healthy", icon: Settings, color: "text-purple-500" },
        ]);
      } catch (error) {
        console.error("Failed to fetch dashboard stats:", error);
      }
    };
    fetchStats();
  }, []);

  const modules = [
    {
      name: "User Management",
      description: "Manage user accounts, roles, and permissions.",
      href: "/orchard-v3-panel/users",
      icon: Users,
    },
    {
      name: "Content Moderation",
      description: "Review and moderate forum posts, articles, and comments.",
      href: "/orchard-v3-panel/content",
      icon: FileText,
    },
    {
      name: "Security Logs",
      description: "View login attempts and security-related events.",
      href: "/orchard-v3-panel/logs",
      icon: ShieldAlert,
    },
    {
      name: "Site Settings",
      description: "Configure site-wide content, branding, and global variables.",
      href: "/orchard-v3-panel/settings",
      icon: Settings,
    },
  ];

  return (
    <div className="container py-10 space-y-8">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">System Management</h1>
        <p className="text-muted-foreground">
          Welcome back, {user?.first_name}. Here is an overview of the platform status.
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {stats.map((stat) => (
          <Card key={stat.title}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
              <stat.icon className={`h-4 w-4 ${stat.color}`} />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stat.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {modules.map((module) => (
          <Link key={module.name} href={module.href}>
            <Card className="h-full hover:shadow-md transition-shadow cursor-pointer group">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <module.icon className="h-8 w-8 text-primary mb-2" />
                  <ArrowRight className="h-5 w-5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
                </div>
                <CardTitle>{module.name}</CardTitle>
                <CardDescription>{module.description}</CardDescription>
              </CardHeader>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
