"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import {
  CreditCard,
  CalendarDays,
  Upload,
  ArrowRight,
  CheckCircle2,
  AlertCircle,
  Clock,
  Users,
  Plug,
  UserPlus,
  X,
} from "lucide-react";
import {
  ResponsiveContainer,
  AreaChart,
  Area,
} from "recharts";
import { toast } from "sonner";
import { Header } from "@/components/layout/header";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";

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

type TrendPoint = { date: string; total: number; scanned: number; survey: number };

type TrendsData = {
  series: TrendPoint[];
  peopleCount: number;
  newPeopleThisPeriod: number;
};

const HINTS_STORAGE_KEY = "echo-ocr-dismissed-hints";

function loadDismissedHints(): string[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = localStorage.getItem(HINTS_STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

function dismissHint(id: string) {
  const current = loadDismissedHints();
  if (!current.includes(id)) {
    localStorage.setItem(
      HINTS_STORAGE_KEY,
      JSON.stringify([...current, id])
    );
  }
}

export default function DashboardHomePage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [trends, setTrends] = useState<TrendsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [dismissedHints, setDismissedHints] = useState<string[]>([]);

  useEffect(() => {
    setDismissedHints(loadDismissedHints());
  }, []);

  const handleDismiss = useCallback((id: string) => {
    dismissHint(id);
    setDismissedHints((prev) => [...prev, id]);
  }, []);

  useEffect(() => {
    Promise.all([
      fetch("/api/stats").then((r) => r.json()),
      fetch("/api/stats/trends?period=7&groupBy=day")
        .then((r) => (r.ok ? r.json() : null))
        .catch(() => null),
    ])
      .then(([statsData, trendsData]) => {
        setStats(statsData);
        setTrends(trendsData);
      })
      .catch(() => { toast.error("Failed to load dashboard stats"); })
      .finally(() => setLoading(false));
  }, []);

  const completed = stats?.byOcrStatus?.complete ?? 0;
  const errors = stats?.byOcrStatus?.error ?? 0;
  const pending = (stats?.byOcrStatus?.pending ?? 0) + (stats?.byOcrStatus?.processing ?? 0);
  const unreviewed = stats?.byReviewStatus?.unreviewed ?? 0;

  const sparkData = trends?.series ?? [];

  const summaryCards = [
    {
      label: "Total Cards",
      value: stats?.total ?? 0,
      icon: CreditCard,
      href: "/cards",
      sparkKey: "total" as const,
    },
    {
      label: "OCR Complete",
      value: completed,
      icon: CheckCircle2,
      href: "/cards?ocrStatus=complete",
      sparkKey: "scanned" as const,
    },
    {
      label: "Needs Review",
      value: unreviewed,
      icon: Clock,
      href: "/cards?reviewStatus=unreviewed",
      sparkKey: null,
    },
    {
      label: "Errors",
      value: errors,
      icon: AlertCircle,
      href: "/cards?ocrStatus=error",
      sparkKey: null,
    },
    {
      label: "People",
      value: trends?.peopleCount ?? 0,
      icon: Users,
      href: "/people",
      sparkKey: null,
      sub: trends ? `+${trends.newPeopleThisPeriod} this week` : undefined,
    },
  ];

  const quickActions = [
    {
      label: "Upload Documents",
      description: "Scan or import new response cards",
      icon: Upload,
      onClick: () => window.dispatchEvent(new CustomEvent("open-upload-modal")),
    },
    {
      label: "View Response Cards",
      description: "Browse and manage all scanned cards",
      icon: CreditCard,
      href: "/cards",
    },
    {
      label: "Collection Days",
      description: "Manage events and service times",
      icon: CalendarDays,
      href: "/events",
    },
    {
      label: "People",
      description: "View contact directory",
      icon: Users,
      href: "/people",
    },
  ];

  return (
    <div className="space-y-8">
      <Header
        title="Dashboard"
        description="Overview of your response card activity"
        icon={CreditCard}
      />

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
        {summaryCards.map((card) =>
          loading ? (
            <Skeleton key={card.label} className="h-28 rounded-2xl" />
          ) : (
            <Link
              key={card.label}
              href={card.href}
              className="gradient-stat group flex flex-col justify-between rounded-2xl p-5 transition-transform hover:scale-[1.02]"
            >
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-muted-foreground">
                  {card.label}
                </span>
                <card.icon className="size-4 text-muted-foreground" />
              </div>
              <p className="mt-2 text-3xl font-bold tracking-tight">
                {card.value.toLocaleString()}
              </p>
              {"sub" in card && card.sub && (
                <p className="text-xs text-muted-foreground">{card.sub}</p>
              )}
              {card.sparkKey && sparkData.length > 1 && (
                <div className="mt-1">
                  <ResponsiveContainer width="100%" height={40}>
                    <AreaChart data={sparkData}>
                      <defs>
                        <linearGradient id={`spark-${card.sparkKey}`} x1="0" y1="0" x2="0" y2="1">
                          <stop offset="0%" stopColor="#6366f1" stopOpacity={0.15} />
                          <stop offset="100%" stopColor="#6366f1" stopOpacity={0} />
                        </linearGradient>
                      </defs>
                      <Area
                        type="monotone"
                        dataKey={card.sparkKey}
                        stroke="#6366f1"
                        fill={`url(#spark-${card.sparkKey})`}
                        strokeWidth={1.5}
                      />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
              )}
            </Link>
          )
        )}
      </div>

      <div>
        <h2 className="mb-4 text-lg font-semibold">Quick Actions</h2>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {quickActions.map((action) => {
            const className =
              "glass-card group flex items-start gap-4 rounded-xl p-4 text-left transition-all hover:scale-[1.01]";
            const inner = (
              <>
                <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                  <action.icon className="size-5 text-primary" />
                </div>
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-semibold">{action.label}</p>
                  <p className="mt-0.5 text-xs text-muted-foreground">
                    {action.description}
                  </p>
                </div>
                <ArrowRight className="mt-1 size-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
              </>
            );

            if (action.href) {
              return (
                <Link key={action.label} href={action.href} className={className}>
                  {inner}
                </Link>
              );
            }
            return (
              <button
                key={action.label}
                type="button"
                onClick={action.onClick}
                className={className}
              >
                {inner}
              </button>
            );
          })}
        </div>
      </div>

      {/* Contextual guidance cards */}
      {!loading && (
        <GuidanceCards
          totalCards={stats?.total ?? 0}
          dismissedHints={dismissedHints}
          onDismiss={handleDismiss}
        />
      )}
    </div>
  );
}

function GuidanceCards({
  totalCards,
  dismissedHints,
  onDismiss,
}: {
  totalCards: number;
  dismissedHints: string[];
  onDismiss: (id: string) => void;
}) {
  const hints = [
    {
      id: "no_cards",
      show: totalCards === 0,
      icon: Upload,
      title: "Upload your first response card",
      description:
        "Get started by scanning or importing a response card. You can upload PDFs, images, or use the email inbox.",
      href: "/cards",
      cta: "Go to Cards",
    },
    {
      id: "no_integrations",
      show: true,
      icon: Plug,
      title: "Connect an integration",
      description:
        "Sync processed cards to Planning Center, Monday.com, Airtable, or any webhook endpoint.",
      href: "/settings/integrations",
      cta: "Set up Integrations",
    },
    {
      id: "invite_team",
      show: true,
      icon: UserPlus,
      title: "Invite team members",
      description:
        "Add reviewers, editors, or admins to help process and manage response cards.",
      href: "/settings/users",
      cta: "Invite Members",
    },
    {
      id: "collection_days",
      show: true,
      icon: CalendarDays,
      title: "Set up your service schedule",
      description:
        "Configure your weekly collection days to automatically assign cards to events.",
      href: "/settings/locations",
      cta: "Manage Schedule",
    },
  ];

  const visible = hints.filter(
    (h) => h.show && !dismissedHints.includes(h.id)
  );
  if (visible.length === 0) return null;

  return (
    <div className="space-y-3">
      <h2 className="text-lg font-semibold">Getting Started</h2>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        {visible.map((hint) => (
          <div
            key={hint.id}
            className="glass-card relative flex items-start gap-4 rounded-xl p-4"
          >
            <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
              <hint.icon className="size-5 text-primary" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-sm font-semibold">{hint.title}</p>
              <p className="mt-0.5 text-xs text-muted-foreground">
                {hint.description}
              </p>
              <Link
                href={hint.href}
                className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
              >
                {hint.cta}
                <ArrowRight className="size-3" />
              </Link>
            </div>
            <Button
              variant="ghost"
              size="icon"
              className="absolute right-2 top-2 size-6 text-muted-foreground hover:text-foreground"
              onClick={() => onDismiss(hint.id)}
            >
              <X className="size-3" />
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
}
