"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { StatCard } from "@/components/ui/stat-card";
import {
  ProjectionsBarChart,
  type ProjectionData,
} from "@/components/charts/projections-bar-chart";
import {
  SavingsAreaChart,
  type SavingsData,
} from "@/components/charts/savings-area-chart";
import { TrendingUp, TrendingDown, PiggyBank, BarChart3 } from "lucide-react";
import { formatCurrency } from "@/lib/utils";

interface CostData {
  entries: { period: string; amount: number }[];
  totals: {
    byMonth: Record<string, number>;
    total: number;
  };
}

function getCurrentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

function getConfidenceLevel(dataMonths: number): {
  label: string;
  color: string;
  percent: number;
} {
  if (dataMonths >= 6)
    return { label: "High", color: "text-emerald-400", percent: 85 };
  if (dataMonths >= 3)
    return { label: "Medium", color: "text-amber-400", percent: 60 };
  return { label: "Low", color: "text-red-400", percent: 30 };
}

const MONTH_NAMES = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

export default function ProjectionsPage() {
  const [data, setData] = useState<CostData | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch("/api/costs");
      if (res.ok) {
        setData(await res.json());
      }
    } catch {
      // empty state
    } finally {
      setLoading(false);
    }
  }, []);

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

  const currentMonth = getCurrentMonth();
  const currentTotal = data?.totals.byMonth[currentMonth] ?? 0;
  const monthCount = Object.keys(data?.totals.byMonth ?? {}).length;

  // Project monthly rate based on day of month
  const dayOfMonth = new Date().getDate();
  const daysInMonth = new Date(
    new Date().getFullYear(),
    new Date().getMonth() + 1,
    0,
  ).getDate();
  const projected =
    dayOfMonth > 0 ? (currentTotal / dayOfMonth) * daysInMonth : currentTotal;

  const savingsPercent = 35;
  const annualWithout = projected * 12;
  const annualWith = annualWithout * (1 - savingsPercent / 100);
  const annualSavings = annualWithout - annualWith;
  const confidence = getConfidenceLevel(monthCount);

  // 12-month projection starting from next month
  const projectionData = useMemo<ProjectionData[]>(() => {
    const now = new Date();
    return Array.from({ length: 12 }, (_, i) => {
      const date = new Date(now.getFullYear(), now.getMonth() + 1 + i, 1);
      const month = MONTH_NAMES[date.getMonth()];
      const growth = 1 + i * 0.03;
      const withoutLLMHosts = projected * growth;
      const withLLMHosts = withoutLLMHosts * (1 - savingsPercent / 100);
      return { month, withoutLLMHosts, withLLMHosts };
    });
  }, [projected, savingsPercent]);

  const savingsData = useMemo<SavingsData[]>(() => {
    let cumulative = 0;
    const now = new Date();
    return Array.from({ length: 12 }, (_, i) => {
      const date = new Date(now.getFullYear(), now.getMonth() + 1 + i, 1);
      const month = MONTH_NAMES[date.getMonth()];
      const growth = 1 + i * 0.03;
      const savings = projected * growth * (savingsPercent / 100);
      cumulative += savings;
      return { month, savings, cumulative };
    });
  }, [projected, savingsPercent]);

  if (loading) {
    return (
      <div className="space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-100">Projections</h1>
          <p className="mt-1 text-sm text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-gray-100">Projections</h1>
        <p className="mt-1 text-sm text-gray-400">
          Forecast your AI spending and potential savings
        </p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          title="Current Monthly Rate"
          value={formatCurrency(projected)}
          change={`${formatCurrency(currentTotal)} so far this month`}
          changeType="neutral"
          icon={<TrendingUp size={20} />}
        />
        <StatCard
          title="Projected Annual (Without)"
          value={formatCurrency(annualWithout)}
          change="At current rate, no optimization"
          changeType="negative"
          icon={<TrendingDown size={20} />}
        />
        <StatCard
          title="Projected Annual (With LLMHosts)"
          value={formatCurrency(annualWith)}
          change={`Save ${savingsPercent}% with caching + routing`}
          changeType="positive"
          icon={<PiggyBank size={20} />}
        />
        <StatCard
          title="Annual Savings"
          value={formatCurrency(annualSavings)}
          change={`Confidence: ${confidence.label}`}
          changeType="positive"
          icon={<BarChart3 size={20} />}
        />
      </div>

      {/* Confidence indicator */}
      <Card>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-400">
              Projection Confidence
            </p>
            <p className={`text-lg font-bold ${confidence.color}`}>
              {confidence.label} ({confidence.percent}%)
            </p>
            <p className="mt-1 text-xs text-gray-500">
              Based on {monthCount} month{monthCount !== 1 ? "s" : ""} of
              spending data
            </p>
          </div>
          <div className="h-3 w-48 overflow-hidden rounded-full bg-gray-800">
            <div
              className="h-full rounded-full bg-gradient-to-r from-indigo-500 to-emerald-500 transition-all"
              style={{ width: `${confidence.percent}%` }}
            />
          </div>
        </div>
      </Card>

      {/* Bar chart: comparison */}
      <Card
        title="Annual Spending Projection"
        description="Without LLMHosts vs With LLMHosts over 12 months"
      >
        <ProjectionsBarChart data={projectionData} />
      </Card>

      {/* Area chart: savings */}
      <Card
        title="Savings Projection"
        description="Monthly and cumulative savings over 12 months"
      >
        <SavingsAreaChart data={savingsData} />
      </Card>
    </div>
  );
}
