"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { StatCard } from "@/components/ui/stat-card";
import { Card } from "@/components/ui/card";
import { DataTable, type Column } from "@/components/ui/data-table";
import {
  DollarSign,
  TrendingUp,
  PiggyBank,
  Wifi,
  Shield,
} from "lucide-react";
import { formatCurrency } from "@/lib/utils";
import {
  LineChart,
  Line,
  PieChart,
  Pie,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Cell,
} from "recharts";

interface CostEntry {
  id: string;
  provider: string;
  amount: number;
  period: string;
  category: string;
  note: string | null;
  createdAt: string;
}

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

const providerLabels: Record<string, string> = {
  openai: "OpenAI",
  anthropic: "Anthropic",
  google: "Google AI",
  aws: "AWS Bedrock",
  azure: "Azure",
  manual: "Manual",
  other: "Other",
};

const providerColors: Record<string, string> = {
  openai: "#10b981", // emerald
  anthropic: "#8b5cf6", // violet
  google: "#3b82f6", // blue
  aws: "#f59e0b", // amber
  azure: "#06b6d4", // cyan
  manual: "#6366f1", // indigo
  other: "#6b7280", // gray
};

const CHART_COLORS = [
  "#8b5cf6", // violet
  "#10b981", // emerald
  "#3b82f6", // blue
  "#f59e0b", // amber
  "#06b6d4", // cyan
  "#6366f1", // indigo
];

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

const recentColumns: Column<CostEntry>[] = [
  {
    key: "createdAt",
    header: "Date",
    render: (row) => new Date(row.createdAt).toLocaleDateString(),
  },
  {
    key: "provider",
    header: "Provider",
    render: (row) => (
      <span className="font-medium text-gray-100">
        {providerLabels[row.provider] ?? row.provider}
      </span>
    ),
  },
  {
    key: "amount",
    header: "Amount",
    render: (row) => (
      <span className="text-gray-100">{formatCurrency(row.amount)}</span>
    ),
  },
  { key: "category", header: "Category" },
];

export default function DashboardOverview() {
  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 totalAll = data?.totals.total ?? 0;
  const recentEntries = data?.entries.slice(0, 5) ?? [];

  // Simple savings estimate: 35% of current spend via caching + local routing
  const savingsPercent = 35;
  const savingsAmount = currentTotal * (savingsPercent / 100);

  // Chart data preparation
  const monthlyTrendData = useMemo(() => {
    if (!data) return [];

    // Get last 6 months
    const now = new Date();
    const months: string[] = [];
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
    }

    // Group entries by month and provider
    const monthlyByProvider: Record<string, Record<string, number>> = {};
    data.entries.forEach((entry) => {
      if (!monthlyByProvider[entry.period]) {
        monthlyByProvider[entry.period] = {};
      }
      const prev = monthlyByProvider[entry.period][entry.provider] ?? 0;
      monthlyByProvider[entry.period][entry.provider] = prev + entry.amount;
    });

    // Build chart data
    return months.map((month) => {
      const monthData = monthlyByProvider[month] ?? {};
      const monthLabel = new Date(month + "-01").toLocaleDateString("en-US", {
        month: "short",
        year: "numeric",
      });
      return {
        month: monthLabel,
        ...monthData,
        total: Object.values(monthData).reduce((sum, v) => sum + v, 0),
      };
    });
  }, [data]);

  const providerPieData = useMemo(() => {
    if (!data) return [];
    return Object.entries(data.totals.byProvider)
      .map(([provider, amount]) => ({
        name: providerLabels[provider] ?? provider,
        value: amount,
      }))
      .sort((a, b) => b.value - a.value);
  }, [data]);

  const savingsProjectionData = useMemo(() => {
    if (!data) return [];

    // Get last 6 months for projection
    const now = new Date();
    const months: string[] = [];
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
    }

    return months.map((month) => {
      const actual = data.totals.byMonth[month] ?? 0;
      const withLLMHosts = actual * (1 - savingsPercent / 100);
      const monthLabel = new Date(month + "-01").toLocaleDateString("en-US", {
        month: "short",
      });
      return {
        month: monthLabel,
        actual,
        withLLMHosts,
      };
    });
  }, [data, savingsPercent]);

  // Get unique providers for trend chart
  const uniqueProviders = useMemo(() => {
    if (!data) return [];
    return Object.keys(data.totals.byProvider).sort();
  }, [data]);

  return (
    <div className="space-y-8">
      {/* Page header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-100">Overview</h1>
        <p className="mt-1 text-sm text-gray-400">
          Your AI cloud spending at a glance
        </p>
      </div>

      {loading ? (
        <p className="py-8 text-center text-sm text-gray-500">Loading...</p>
      ) : (
        <>
          {/* Stat cards */}
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <StatCard
              title="This Month"
              value={formatCurrency(currentTotal)}
              change={currentMonth}
              changeType="neutral"
              icon={<DollarSign size={20} />}
            />
            <StatCard
              title="All Time"
              value={formatCurrency(totalAll)}
              change={`${data?.entries.length ?? 0} entries`}
              changeType="neutral"
              icon={<TrendingUp size={20} />}
            />
            <StatCard
              title="Potential Savings"
              value={`${formatCurrency(savingsAmount)} (${savingsPercent}%)`}
              change="With LLMHosts caching + routing"
              changeType="positive"
              icon={<PiggyBank size={20} />}
            />
            <StatCard
              title="LLMHosts Status"
              value="Ready"
              change="Configure in Settings"
              changeType="neutral"
              icon={<Wifi size={20} />}
            />
          </div>

          {/* Privacy mode indicator */}
          <div className="flex items-center gap-3 rounded-lg border border-green-800/30 bg-green-900/10 px-4 py-2">
            <Shield size={16} className="text-green-400" />
            <p className="text-sm text-green-300">
              Privacy: <span className="font-medium">Standard Mode</span> -- PII auto-detected, clean requests can use cloud
            </p>
          </div>

          {/* Charts row */}
          {data && data.entries.length > 0 && (
            <>
              {/* Monthly Spending Trend */}
              <Card
                title="Monthly Spending Trend"
                description="Last 6 months by provider"
              >
                {monthlyTrendData.length > 0 ? (
                  <ResponsiveContainer width="100%" height={300}>
                    <LineChart data={monthlyTrendData}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
                      <XAxis
                        dataKey="month"
                        stroke="#9ca3af"
                        style={{ fontSize: "12px" }}
                      />
                      <YAxis
                        stroke="#9ca3af"
                        style={{ fontSize: "12px" }}
                        tickFormatter={(value) => `$${value}`}
                      />
                      <Tooltip
                        contentStyle={{
                          backgroundColor: "#1f2937",
                          border: "1px solid #374151",
                          borderRadius: "6px",
                          color: "#f3f4f6",
                        }}
                        formatter={(value) => formatCurrency(value as number)}
                      />
                      <Legend
                        wrapperStyle={{ color: "#9ca3af", fontSize: "12px" }}
                        formatter={(value) => providerLabels[value] ?? value}
                      />
                      {uniqueProviders.map((provider, idx) => (
                        <Line
                          key={provider}
                          type="monotone"
                          dataKey={provider}
                          stroke={providerColors[provider] ?? CHART_COLORS[idx % CHART_COLORS.length]}
                          strokeWidth={2}
                          dot={{ r: 3 }}
                          activeDot={{ r: 5 }}
                        />
                      ))}
                    </LineChart>
                  </ResponsiveContainer>
                ) : (
                  <p className="py-8 text-center text-sm text-gray-500">
                    No monthly data available
                  </p>
                )}
              </Card>

              {/* Provider Breakdown & Savings Projection side-by-side */}
              <div className="grid gap-4 lg:grid-cols-2">
                {/* Provider Breakdown Pie Chart */}
                <Card
                  title="Provider Breakdown"
                  description="All-time spending distribution"
                >
                  {providerPieData.length > 0 ? (
                    <ResponsiveContainer width="100%" height={300}>
                      <PieChart>
                        <Pie
                          data={providerPieData}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={(entry) => {
                            const percent = entry.percent ? (entry.percent * 100).toFixed(1) : "0";
                            return `${entry.name} ${percent}%`;
                          }}
                          outerRadius={80}
                          fill="#8884d8"
                          dataKey="value"
                        >
                          {providerPieData.map((entry, index) => (
                            <Cell
                              key={`cell-${index}`}
                              fill={CHART_COLORS[index % CHART_COLORS.length]}
                            />
                          ))}
                        </Pie>
                        <Tooltip
                          contentStyle={{
                            backgroundColor: "#1f2937",
                            border: "1px solid #374151",
                            borderRadius: "6px",
                            color: "#f3f4f6",
                          }}
                          formatter={(value) => formatCurrency(value as number)}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                  ) : (
                    <p className="py-8 text-center text-sm text-gray-500">
                      No provider data available
                    </p>
                  )}
                </Card>

                {/* Savings Projection Area Chart */}
                <Card
                  title="Savings Projection"
                  description={`Actual vs with LLMHosts (${savingsPercent}% savings)`}
                >
                  {savingsProjectionData.length > 0 ? (
                    <ResponsiveContainer width="100%" height={300}>
                      <AreaChart data={savingsProjectionData}>
                        <defs>
                          <linearGradient
                            id="colorActual"
                            x1="0"
                            y1="0"
                            x2="0"
                            y2="1"
                          >
                            <stop offset="5%" stopColor="#ef4444" stopOpacity={0.8} />
                            <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                          </linearGradient>
                          <linearGradient
                            id="colorSavings"
                            x1="0"
                            y1="0"
                            x2="0"
                            y2="1"
                          >
                            <stop offset="5%" stopColor="#10b981" stopOpacity={0.8} />
                            <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                          </linearGradient>
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
                        <XAxis
                          dataKey="month"
                          stroke="#9ca3af"
                          style={{ fontSize: "12px" }}
                        />
                        <YAxis
                          stroke="#9ca3af"
                          style={{ fontSize: "12px" }}
                          tickFormatter={(value) => `$${value}`}
                        />
                        <Tooltip
                          contentStyle={{
                            backgroundColor: "#1f2937",
                            border: "1px solid #374151",
                            borderRadius: "6px",
                            color: "#f3f4f6",
                          }}
                          formatter={(value) => formatCurrency(value as number)}
                        />
                        <Legend wrapperStyle={{ color: "#9ca3af", fontSize: "12px" }} />
                        <Area
                          type="monotone"
                          dataKey="actual"
                          stroke="#ef4444"
                          fillOpacity={1}
                          fill="url(#colorActual)"
                          name="Actual Spending"
                        />
                        <Area
                          type="monotone"
                          dataKey="withLLMHosts"
                          stroke="#10b981"
                          fillOpacity={1}
                          fill="url(#colorSavings)"
                          name="With LLMHosts"
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  ) : (
                    <p className="py-8 text-center text-sm text-gray-500">
                      No projection data available
                    </p>
                  )}
                </Card>
              </div>
            </>
          )}

          {/* Empty state when no data — onboarding CTA */}
          {data && data.entries.length === 0 && (
            <Card
              title="Get started in 90 seconds"
              description="Connect your first GPU and make your first API call"
            >
              <div className="space-y-4 py-4">
                <div className="flex items-start gap-4">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-indigo-500/20 text-sm font-bold text-indigo-400">1</div>
                  <div>
                    <p className="text-sm font-medium text-gray-200">Connect your GPU</p>
                    <div className="mt-1 rounded bg-gray-800 px-3 py-2">
                      <code className="text-xs text-gray-300 select-all">pip install llmhosts && llmhosts up</code>
                    </div>
                  </div>
                </div>
                <div className="flex items-start gap-4">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-indigo-500/20 text-sm font-bold text-indigo-400">2</div>
                  <div>
                    <p className="text-sm font-medium text-gray-200">Create an API key</p>
                    <p className="mt-1 text-xs text-gray-400">
                      Go to{" "}
                      <a href="/dashboard/keys" className="text-indigo-400 hover:underline">API Keys</a>
                      {" "}and create your first key.
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-4">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-indigo-500/20 text-sm font-bold text-indigo-400">3</div>
                  <div>
                    <p className="text-sm font-medium text-gray-200">Make your first API call</p>
                    <div className="mt-1 rounded bg-gray-800 px-3 py-2">
                      <code className="text-xs text-gray-300 select-all">curl https://llmhosts.com/v1/chat/completions \{"\n"}  -H &quot;Authorization: Bearer lh_sk_...&quot; \{"\n"}  -d &apos;{`{"model":"llama3.2","messages":[{"role":"user","content":"Hello"}]}`}&apos;</code>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          )}

          {/* Recent entries */}
          <Card title="Recent Entries" description="Latest cost entries">
            <DataTable<CostEntry>
              columns={recentColumns}
              data={recentEntries}
              keyExtractor={(row) => row.id}
              emptyMessage="No entries yet. Add your first cost entry."
            />
          </Card>
        </>
      )}
    </div>
  );
}
