"use client";

import { useEffect, useState } from "react";
import { Bike, CarFront, Eye, FileText, MapPin, Star, TrendingUp } from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { adminRequest } from "@/lib/admin-api";

type ServicePageAnalytics = {
  totalServicePageViews: number;
  servicePageViewsToday: number;
  servicePageViews7Days: number;
  topServicePages: Array<{
    serviceSlug: string;
    serviceLabel: string;
    pagePath: string;
    views: number;
    lastViewedAt: string | null;
  }>;
  dailyServicePageViews: Array<{
    day: string;
    views: number;
  }>;
};

const emptyAnalytics: ServicePageAnalytics = {
  totalServicePageViews: 0,
  servicePageViewsToday: 0,
  servicePageViews7Days: 0,
  topServicePages: [],
  dailyServicePageViews: [],
};

function formatCount(value: number | null) {
  return value === null ? "..." : value.toLocaleString("en-IN");
}

function formatDateLabel(value: string | null) {
  if (!value) {
    return "No visits yet";
  }

  return new Intl.DateTimeFormat("en-IN", {
    day: "numeric",
    month: "short",
    hour: "numeric",
    minute: "2-digit",
  }).format(new Date(value));
}

export default function AdminDashboardPage() {
  const [blogCount, setBlogCount] = useState<number | null>(null);
  const [carLogoCount, setCarLogoCount] = useState<number | null>(null);
  const [carModelCount, setCarModelCount] = useState<number | null>(null);
  const [bikeLogoCount, setBikeLogoCount] = useState<number | null>(null);
  const [bikeModelCount, setBikeModelCount] = useState<number | null>(null);
  const [locationCount, setLocationCount] = useState<number | null>(null);
  const [popularCarLogoCount, setPopularCarLogoCount] = useState<number | null>(null);
  const [popularBikeLogoCount, setPopularBikeLogoCount] = useState<number | null>(null);
  const [analytics, setAnalytics] = useState<ServicePageAnalytics | null>(null);

  useEffect(() => {
    adminRequest<{
      blogCount: number;
      carLogoCount: number;
      carModelCount: number;
      bikeLogoCount: number;
      bikeModelCount: number;
      locationCount: number;
      popularCarLogoCount: number;
      popularBikeLogoCount: number;
      analytics: ServicePageAnalytics;
    }>("/api/admin/stats")
      .then((data) => {
        setBlogCount(data.blogCount);
        setCarLogoCount(data.carLogoCount);
        setCarModelCount(data.carModelCount);
        setBikeLogoCount(data.bikeLogoCount);
        setBikeModelCount(data.bikeModelCount);
        setLocationCount(data.locationCount);
        setPopularCarLogoCount(data.popularCarLogoCount);
        setPopularBikeLogoCount(data.popularBikeLogoCount);
        setAnalytics(data.analytics);
      })
      .catch(() => {
        setBlogCount(0);
        setCarLogoCount(0);
        setCarModelCount(0);
        setBikeLogoCount(0);
        setBikeModelCount(0);
        setLocationCount(0);
        setPopularCarLogoCount(0);
        setPopularBikeLogoCount(0);
        setAnalytics(emptyAnalytics);
      });
  }, []);

  const maxDailyViews = Math.max(
    1,
    ...(analytics?.dailyServicePageViews.map((item) => item.views) ?? [0]),
  );

  return (
    <AdminGuard>
      <AdminShell
        title="Dashboard"
        lead="A quick view of website traffic and content currently managed in admin."
      >
        <section className="mb-6 space-y-4">
          <div className="grid gap-4 md:grid-cols-3">
            <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                    Service page views
                  </p>
                  <p className="mt-3 text-4xl font-black text-foreground">
                    {formatCount(analytics?.totalServicePageViews ?? null)}
                  </p>
                </div>
                <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                  <Eye className="h-6 w-6" />
                </div>
              </div>
            </article>

            <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                    Today
                  </p>
                  <p className="mt-3 text-4xl font-black text-foreground">
                    {formatCount(analytics?.servicePageViewsToday ?? null)}
                  </p>
                </div>
                <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                  <TrendingUp className="h-6 w-6" />
                </div>
              </div>
            </article>

            <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                    Last 7 days
                  </p>
                  <p className="mt-3 text-4xl font-black text-foreground">
                    {formatCount(analytics?.servicePageViews7Days ?? null)}
                  </p>
                </div>
                <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                  <TrendingUp className="h-6 w-6" />
                </div>
              </div>
            </article>
          </div>

          <div className="grid gap-4 xl:grid-cols-[1fr_1.35fr]">
            <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
              <div className="flex items-center justify-between gap-4">
                <div>
                  <h2 className="text-lg font-black tracking-tight text-foreground">
                    7-day traffic
                  </h2>
                  <p className="mt-1 text-sm font-semibold text-muted-foreground">
                    Daily service page views
                  </p>
                </div>
              </div>

              <div className="mt-6 flex h-44 items-end gap-3">
                {(analytics?.dailyServicePageViews ?? []).map((item) => (
                  <div key={item.day} className="flex min-w-0 flex-1 flex-col items-center gap-2">
                    <div className="flex h-32 w-full items-end rounded-md bg-slate-100 p-1">
                      <div
                        className="w-full rounded-sm bg-primary"
                        style={{ height: `${Math.max(8, (item.views / maxDailyViews) * 100)}%` }}
                      />
                    </div>
                    <p className="text-xs font-black text-foreground">{item.views}</p>
                    <p className="w-full truncate text-center text-[10px] font-bold uppercase tracking-[0.12em] text-muted-foreground">
                      {new Intl.DateTimeFormat("en-IN", {
                        day: "numeric",
                        month: "short",
                      }).format(new Date(item.day))}
                    </p>
                  </div>
                ))}
              </div>
            </article>

            <article className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
              <div className="border-b border-border p-6">
                <h2 className="text-lg font-black tracking-tight text-foreground">
                  Top service pages
                </h2>
                <p className="mt-1 text-sm font-semibold text-muted-foreground">
                  Pages ranked by total tracked visits
                </p>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full min-w-[560px] text-left">
                  <thead className="bg-slate-50 text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
                    <tr>
                      <th className="px-6 py-3">Service</th>
                      <th className="px-6 py-3">Path</th>
                      <th className="px-6 py-3 text-right">Views</th>
                      <th className="px-6 py-3 text-right">Last visit</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border text-sm">
                    {(analytics?.topServicePages ?? []).length > 0 ? (
                      analytics?.topServicePages.map((item) => (
                        <tr key={item.serviceSlug}>
                          <td className="px-6 py-4 font-black text-foreground">
                            {item.serviceLabel}
                          </td>
                          <td className="px-6 py-4 font-semibold text-muted-foreground">
                            {item.pagePath}
                          </td>
                          <td className="px-6 py-4 text-right font-black text-foreground">
                            {item.views.toLocaleString("en-IN")}
                          </td>
                          <td className="px-6 py-4 text-right font-semibold text-muted-foreground">
                            {formatDateLabel(item.lastViewedAt)}
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td
                          colSpan={4}
                          className="px-6 py-8 text-center font-semibold text-muted-foreground"
                        >
                          No service traffic has been tracked yet.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </article>
          </div>
        </section>

        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Locations
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {locationCount === null ? "..." : locationCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <MapPin className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Blogs
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {blogCount === null ? "..." : blogCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <FileText className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Car models
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {carModelCount === null ? "..." : carModelCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <CarFront className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Bike models
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {bikeModelCount === null ? "..." : bikeModelCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <Bike className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Bike companies
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {bikeLogoCount === null ? "..." : bikeLogoCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <Bike className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Car companies
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {carLogoCount === null ? "..." : carLogoCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <CarFront className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Popular car companies
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {popularCarLogoCount === null ? "..." : popularCarLogoCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <Star className="h-6 w-6" />
              </div>
            </div>
          </article>
          <article className="rounded-lg border border-border bg-white p-6 shadow-sm">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.16em] text-muted-foreground">
                  Popular bike companies
                </p>
                <p className="mt-3 text-4xl font-black text-foreground">
                  {popularBikeLogoCount === null ? "..." : popularBikeLogoCount}
                </p>
              </div>
              <div className="grid h-12 w-12 place-items-center rounded-md bg-primary/10 text-primary">
                <Star className="h-6 w-6" />
              </div>
            </div>
          </article>
        </div>
      </AdminShell>
    </AdminGuard>
  );
}
