"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import {
  CreditCard,
  Mail,
  Package,
  Settings,
  ShoppingBag,
  Users,
} from "lucide-react";
import { Reveal } from "@/components/motion/Reveal";
import { Stagger, StaggerItem } from "@/components/motion/Stagger";
import { formatPrice } from "@/lib/format";
import { easeSoft } from "@/lib/motion";

type Stats = {
  revenue: number;
  orders: number;
  customers: number;
  products: number;
  pending: number;
  lowStock: number;
  avgOrder: number;
};

export default function AdminOverviewPage() {
  const [stats, setStats] = useState<Stats | null>(null);

  useEffect(() => {
    void fetch("/api/admin/stats", { credentials: "include" })
      .then((res) => res.json())
      .then((data: Stats & { error?: string }) => {
        if (!data.error) setStats(data);
      });
  }, []);

  const cards = [
    {
      label: "Revenue",
      value: stats ? formatPrice(stats.revenue) : "—",
      hint: "All-time paid orders",
    },
    {
      label: "Orders",
      value: stats ? String(stats.orders) : "—",
      hint: stats ? `${stats.pending} pending` : "Loading…",
    },
    {
      label: "Customers",
      value: stats ? String(stats.customers) : "—",
      hint: "Registered shoppers",
    },
    {
      label: "Catalog",
      value: stats ? String(stats.products) : "—",
      hint: stats ? `${stats.lowStock} low stock` : "Loading…",
    },
  ];

  const shortcuts = [
    { href: "/admin/products", label: "Manage products", icon: Package },
    { href: "/admin/orders", label: "View orders", icon: ShoppingBag },
    { href: "/admin/customers", label: "Customers", icon: Users },
    { href: "/admin/settings", label: "Branding", icon: Settings },
    { href: "/admin/settings/stripe", label: "Stripe", icon: CreditCard },
    { href: "/admin/settings/email", label: "SMTP email", icon: Mail },
  ];

  return (
    <div className="space-y-8">
      <Reveal>
        <h1 className="text-2xl font-semibold tracking-tight text-foreground sm:text-3xl">
          Dashboard
        </h1>
        <p className="mt-2 text-sm text-muted">
          Live store metrics, catalog tools, and payment/email configuration.
        </p>
      </Reveal>

      <Stagger className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {cards.map((stat) => (
          <StaggerItem key={stat.label}>
            <motion.div
              whileHover={{ y: -3 }}
              transition={{ duration: 0.35, ease: easeSoft }}
              className="rounded-2xl border border-border bg-card p-5 shadow-sm transition-colors"
            >
              <p className="text-sm text-muted">{stat.label}</p>
              <p className="mt-2 text-2xl font-semibold text-foreground">
                {stat.value}
              </p>
              <p className="mt-1 text-xs text-muted">{stat.hint}</p>
            </motion.div>
          </StaggerItem>
        ))}
      </Stagger>

      <section>
        <Reveal>
          <h2 className="mb-3 text-sm font-semibold uppercase tracking-[0.14em] text-muted">
            Quick actions
          </h2>
        </Reveal>
        <Stagger className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3" delay={0.08}>
          {shortcuts.map((item) => {
            const Icon = item.icon;
            return (
              <StaggerItem key={item.href}>
                <motion.div
                  whileHover={{ y: -2 }}
                  transition={{ duration: 0.3, ease: easeSoft }}
                >
                  <Link
                    href={item.href}
                    className="flex items-center gap-3 rounded-2xl border border-border bg-card px-4 py-4 text-sm text-foreground shadow-sm transition-colors hover:border-emerald-500/40 hover:bg-emerald-500/5"
                  >
                    <span className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-surface text-emerald-700 dark:text-emerald-300">
                      <Icon className="h-4 w-4" />
                    </span>
                    {item.label}
                  </Link>
                </motion.div>
              </StaggerItem>
            );
          })}
        </Stagger>
      </section>

      <Reveal delay={0.1}>
        <section className="rounded-2xl border border-border bg-card p-5 shadow-sm">
          <h2 className="font-semibold text-foreground">Average order value</h2>
          <p className="mt-2 text-3xl font-semibold text-emerald-700 dark:text-emerald-300">
            {stats ? formatPrice(stats.avgOrder) : "—"}
          </p>
          <p className="mt-2 text-sm text-muted">
            Keep catalog photos uploaded locally via Products → Photos for faster
            loads and full control.
          </p>
        </section>
      </Reveal>
    </div>
  );
}
