"use client";

import * as React from "react";
import {
  FileText,
  CheckCircle,
  AlertTriangle,
  Clock,
  UserCheck,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";

type Stats = {
  total: number;
  byOcrStatus: Record<string, number>;
  byReviewStatus: Record<string, number>;
  myCards?: number;
};

export type StatFilter = "all" | "complete" | "error" | "unreviewed" | "my_cards" | null;

type StatCardData = {
  label: string;
  value: number;
  icon: React.ElementType;
  filterKey: StatFilter;
  accentClass: string;
  activeRing: string;
};

interface StatCardsProps {
  activeFilter: StatFilter;
  onFilterChange: (filter: StatFilter) => void;
}

export function StatCards({ activeFilter, onFilterChange }: StatCardsProps) {
  const [stats, setStats] = React.useState<Stats | null>(null);

  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch("/api/stats")
      .then((r) => r.json())
      .then(setStats)
      .catch(() => { toast.error("Failed to load card stats"); })
      .finally(() => setLoading(false));
  }, []);

  const cards: StatCardData[] = React.useMemo(() => {
    if (!stats) {
      return [
        { label: "Total Cards", value: 0, icon: FileText, filterKey: "all", accentClass: "text-primary bg-primary/10", activeRing: "ring-primary/40" },
        { label: "OCR Complete", value: 0, icon: CheckCircle, filterKey: "complete", accentClass: "text-emerald-600 bg-emerald-500/10 dark:text-emerald-400", activeRing: "ring-emerald-500/40" },
        { label: "Errors", value: 0, icon: AlertTriangle, filterKey: "error", accentClass: "text-red-600 bg-red-500/10 dark:text-red-400", activeRing: "ring-red-500/40" },
        { label: "Pending Review", value: 0, icon: Clock, filterKey: "unreviewed", accentClass: "text-amber-600 bg-amber-500/10 dark:text-amber-400", activeRing: "ring-amber-500/40" },
        { label: "My Cards", value: 0, icon: UserCheck, filterKey: "my_cards", accentClass: "text-blue-600 bg-blue-500/10 dark:text-blue-400", activeRing: "ring-blue-500/40" },
      ];
    }
    return [
      {
        label: "Total Cards",
        value: stats.total,
        icon: FileText,
        filterKey: "all" as StatFilter,
        accentClass: "text-primary bg-primary/10",
        activeRing: "ring-primary/40",
      },
      {
        label: "OCR Complete",
        value: stats.byOcrStatus["complete"] || 0,
        icon: CheckCircle,
        filterKey: "complete" as StatFilter,
        accentClass: "text-emerald-600 bg-emerald-500/10 dark:text-emerald-400",
        activeRing: "ring-emerald-500/40",
      },
      {
        label: "Errors",
        value: stats.byOcrStatus["error"] || 0,
        icon: AlertTriangle,
        filterKey: "error" as StatFilter,
        accentClass: "text-red-600 bg-red-500/10 dark:text-red-400",
        activeRing: "ring-red-500/40",
      },
      {
        label: "Pending Review",
        value: stats.byReviewStatus["unreviewed"] || 0,
        icon: Clock,
        filterKey: "unreviewed" as StatFilter,
        accentClass: "text-amber-600 bg-amber-500/10 dark:text-amber-400",
        activeRing: "ring-amber-500/40",
      },
      {
        label: "My Cards",
        value: stats.myCards ?? 0,
        icon: UserCheck,
        filterKey: "my_cards" as StatFilter,
        accentClass: "text-blue-600 bg-blue-500/10 dark:text-blue-400",
        activeRing: "ring-blue-500/40",
      },
    ];
  }, [stats]);

  const handleClick = (filterKey: StatFilter) => {
    if (activeFilter === filterKey) {
      onFilterChange(null);
    } else {
      onFilterChange(filterKey);
    }
  };

  if (loading) {
    return (
      <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 md:grid-cols-5">
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} className="h-[88px] rounded-xl sm:rounded-2xl" />
        ))}
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 md:grid-cols-5">
      {cards.map((card) => {
        const Icon = card.icon;
        const isActive = activeFilter === card.filterKey;
        return (
          <button
            key={card.label}
            type="button"
            onClick={() => handleClick(card.filterKey)}
            className={cn(
              "gradient-stat flex flex-col gap-2 rounded-xl p-3 text-left transition-all sm:rounded-2xl sm:p-4",
              "hover:scale-[1.02] hover:shadow-lg active:scale-[0.98]",
              isActive && `ring-2 ${card.activeRing} shadow-lg`
            )}
          >
            <div
              className={cn(
                "flex size-8 items-center justify-center rounded-lg sm:size-9 sm:rounded-xl",
                card.accentClass
              )}
            >
              <Icon className="size-4 sm:size-5" />
            </div>
            <div>
              <p className="text-lg font-bold tracking-tight sm:text-2xl">
                {card.value.toLocaleString()}
              </p>
              <p className="text-[11px] text-muted-foreground sm:text-xs">
                {card.label}
              </p>
            </div>
          </button>
        );
      })}
    </div>
  );
}
