"use client";

import { useEffect, useState, useCallback } from "react";
import { BarChart3, Download, Users, Clock, CreditCard, FileText } from "lucide-react";
import {
  ResponsiveContainer,
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";
import { Header } from "@/components/layout/header";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";

type Period = 7 | 30 | 90 | 365;

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

type Pipeline = {
  pending: number;
  processing: number;
  complete: number;
  error: number;
  unreviewed: number;
  reviewed: number;
  exported: number;
};

type TeamMember = {
  userId: string;
  name: string;
  reviewed: number;
  assigned: number;
};

type TrendsData = {
  series: SeriesPoint[];
  pipeline: Pipeline;
  teamActivity: TeamMember[];
  avgReviewTimeHours: number | null;
  peopleCount: number;
  newPeopleThisPeriod: number;
};

const PERIOD_OPTIONS: { label: string; value: Period }[] = [
  { label: "7D", value: 7 },
  { label: "30D", value: 30 },
  { label: "90D", value: 90 },
  { label: "1Y", value: 365 },
];

function groupByForPeriod(period: Period): string {
  if (period <= 30) return "day";
  if (period <= 90) return "week";
  return "month";
}

export default function ReportsPage() {
  const [period, setPeriod] = useState<Period>(30);
  const [data, setData] = useState<TrendsData | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async (p: Period) => {
    setLoading(true);
    try {
      const res = await fetch(
        `/api/stats/trends?period=${p}&groupBy=${groupByForPeriod(p)}`
      );
      if (res.ok) setData(await res.json());
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData(period);
  }, [period, fetchData]);

  const handlePeriodChange = (p: Period) => setPeriod(p);

  const downloadCsv = () => {
    if (!data) return;
    const header = "date,total,scanned,survey\n";
    const rows = data.series
      .map((r) => `${r.date},${r.total},${r.scanned},${r.survey}`)
      .join("\n");
    const blob = new Blob([header + rows], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `echo-report-${period}d.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const totalCards = data?.series.reduce((s, r) => s + r.total, 0) ?? 0;
  const totalSurvey = data?.series.reduce((s, r) => s + r.survey, 0) ?? 0;

  const pipelineChartData = data
    ? [
        { stage: "Pending", count: data.pipeline.pending },
        { stage: "Processing", count: data.pipeline.processing },
        { stage: "Complete", count: data.pipeline.complete },
        { stage: "Unreviewed", count: data.pipeline.unreviewed },
        { stage: "Reviewed", count: data.pipeline.reviewed },
        { stage: "Exported", count: data.pipeline.exported },
      ]
    : [];

  return (
    <div className="space-y-8">
      <Header
        title="Reports"
        description="Analytics, trends, and export center"
        icon={BarChart3}
      />

      {/* Period selector + export */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex gap-1 rounded-lg bg-muted/50 p-1">
          {PERIOD_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              onClick={() => handlePeriodChange(opt.value)}
              className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                period === opt.value
                  ? "bg-background text-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
        <Button variant="outline" size="sm" onClick={downloadCsv} disabled={!data}>
          <Download className="mr-2 size-4" />
          Export CSV
        </Button>
      </div>

      {/* Summary stat cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {loading ? (
          Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-24 rounded-2xl" />
          ))
        ) : (
          <>
            <StatCard
              label="Total Cards"
              value={totalCards}
              icon={CreditCard}
              sub={`in last ${period} days`}
            />
            <StatCard
              label="People"
              value={data?.peopleCount ?? 0}
              icon={Users}
              sub={`+${data?.newPeopleThisPeriod ?? 0} this period`}
            />
            <StatCard
              label="Avg Review Time"
              value={
                data?.avgReviewTimeHours != null
                  ? `${data.avgReviewTimeHours}h`
                  : "—"
              }
              icon={Clock}
              sub="hours to review"
            />
            <StatCard
              label="Survey Submissions"
              value={totalSurvey}
              icon={FileText}
              sub={`of ${totalCards} total`}
            />
          </>
        )}
      </div>

      {/* Charts grid */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Cards Over Time */}
        <div className="glass-card rounded-2xl p-5">
          <h3 className="mb-4 text-sm font-semibold">Cards Over Time</h3>
          {loading ? (
            <Skeleton className="h-64 rounded-xl" />
          ) : (
            <ResponsiveContainer width="100%" height={260}>
              <AreaChart data={data?.series ?? []}>
                <defs>
                  <linearGradient id="gradScanned" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#6366f1" stopOpacity={0.3} />
                    <stop offset="100%" stopColor="#6366f1" stopOpacity={0} />
                  </linearGradient>
                  <linearGradient id="gradSurvey" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#10b981" stopOpacity={0.3} />
                    <stop offset="100%" stopColor="#10b981" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                <XAxis
                  dataKey="date"
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                  tickFormatter={(v: string) =>
                    new Date(v + "T00:00:00").toLocaleDateString(undefined, {
                      month: "short",
                      day: "numeric",
                    })
                  }
                />
                <YAxis
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                  allowDecimals={false}
                />
                <Tooltip
                  contentStyle={{
                    background: "hsl(var(--popover))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 8,
                    fontSize: 12,
                  }}
                />
                <Legend wrapperStyle={{ fontSize: 12 }} />
                <Area
                  type="monotone"
                  dataKey="scanned"
                  stroke="#6366f1"
                  fill="url(#gradScanned)"
                  strokeWidth={2}
                  name="Scanned"
                />
                <Area
                  type="monotone"
                  dataKey="survey"
                  stroke="#10b981"
                  fill="url(#gradSurvey)"
                  strokeWidth={2}
                  name="Survey"
                />
              </AreaChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Processing Pipeline */}
        <div className="glass-card rounded-2xl p-5">
          <h3 className="mb-4 text-sm font-semibold">Processing Pipeline</h3>
          {loading ? (
            <Skeleton className="h-64 rounded-xl" />
          ) : (
            <ResponsiveContainer width="100%" height={260}>
              <BarChart data={pipelineChartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                <XAxis
                  dataKey="stage"
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                />
                <YAxis
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                  allowDecimals={false}
                />
                <Tooltip
                  contentStyle={{
                    background: "hsl(var(--popover))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 8,
                    fontSize: 12,
                  }}
                />
                <Bar dataKey="count" fill="#6366f1" radius={[6, 6, 0, 0]} name="Cards" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Team Activity */}
        <div className="glass-card col-span-1 rounded-2xl p-5 lg:col-span-2">
          <h3 className="mb-4 text-sm font-semibold">Team Activity</h3>
          {loading ? (
            <Skeleton className="h-64 rounded-xl" />
          ) : data?.teamActivity.length === 0 ? (
            <div className="flex h-48 items-center justify-center text-sm text-muted-foreground">
              No team activity yet
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={Math.max(200, (data?.teamActivity.length ?? 0) * 50)}>
              <BarChart
                data={data?.teamActivity ?? []}
                layout="vertical"
                margin={{ left: 20 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                <XAxis
                  type="number"
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                  allowDecimals={false}
                />
                <YAxis
                  type="category"
                  dataKey="name"
                  tick={{ fontSize: 11 }}
                  stroke="hsl(var(--muted-foreground))"
                  width={100}
                />
                <Tooltip
                  contentStyle={{
                    background: "hsl(var(--popover))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 8,
                    fontSize: 12,
                  }}
                />
                <Legend wrapperStyle={{ fontSize: 12 }} />
                <Bar dataKey="reviewed" fill="#6366f1" radius={[0, 6, 6, 0]} name="Reviewed" />
                <Bar dataKey="assigned" fill="#a78bfa" radius={[0, 6, 6, 0]} name="Assigned" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  icon: Icon,
  sub,
}: {
  label: string;
  value: string | number;
  icon: React.ComponentType<{ className?: string }>;
  sub: string;
}) {
  return (
    <div className="gradient-stat flex flex-col justify-between rounded-2xl p-5">
      <div className="flex items-center justify-between">
        <span className="text-sm font-medium text-muted-foreground">{label}</span>
        <Icon className="size-4 text-muted-foreground" />
      </div>
      <p className="mt-2 text-3xl font-bold tracking-tight">
        {typeof value === "number" ? value.toLocaleString() : value}
      </p>
      <p className="mt-1 text-xs text-muted-foreground">{sub}</p>
    </div>
  );
}
