import { auth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { redirect } from "next/navigation";
import Link from "next/link";
import EarningsChart from "./EarningsChart";

export const metadata = { title: "Earnings", robots: { index: false, follow: false } };

export default async function ProviderEarningsPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string }>;
}) {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const userId = parseInt(session.user.id);
  const params = await searchParams;
  const page = Math.max(1, parseInt(params.page ?? "1") || 1);
  const perPage = 20;
  const skip = (page - 1) * perPage;

  // Compute last 7 days for chart
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 6);
  sevenDaysAgo.setHours(0, 0, 0, 0);

  const [creditBalance, totalTransactions, transactions, breakdownRaw, recentTransactions] = await Promise.all([
    prisma.credit
      .findUnique({ where: { user_id: userId } })
      .then((c) => c?.credits ?? 0)
      .catch(() => 0),
    prisma.transaction
      .count({ where: { receiver_id: userId } })
      .catch(() => 0),
    prisma.transaction
      .findMany({
        where: { receiver_id: userId },
        orderBy: { created_at: "desc" },
        skip,
        take: perPage,
      })
      .catch(() => []),
    prisma.transaction
      .groupBy({
        by: ["type"],
        where: { receiver_id: userId },
        _sum: { amount: true },
        _count: true,
      })
      .catch(() => []),
    prisma.transaction
      .findMany({
        where: {
          receiver_id: userId,
          created_at: { gte: sevenDaysAgo },
        },
        select: { amount: true, created_at: true },
      })
      .catch(() => []),
  ]);

  // Build chart data for last 7 days
  const chartMap = new Map<string, number>();
  for (let i = 0; i < 7; i++) {
    const d = new Date(sevenDaysAgo);
    d.setDate(d.getDate() + i);
    chartMap.set(d.toISOString().slice(0, 10), 0);
  }
  for (const tx of recentTransactions) {
    const key = new Date(tx.created_at).toISOString().slice(0, 10);
    if (chartMap.has(key)) {
      chartMap.set(key, (chartMap.get(key) || 0) + Number(tx.amount));
    }
  }
  const chartData = Array.from(chartMap.entries()).map(([date, total]) => ({
    date: new Date(date).toLocaleDateString("en-US", { weekday: "short" }),
    total,
  }));

  const totalPages = Math.ceil(totalTransactions / perPage);

  // Build earnings breakdown
  const breakdown = breakdownRaw.map((b) => ({
    type: b.type,
    total: Number(b._sum.amount ?? 0),
    count: b._count,
  }));

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-text">Earnings</h1>
        <Link
          href="/dashboard/provider"
          className="text-sm text-primary hover:underline"
        >
          Back to Dashboard
        </Link>
      </div>

      {/* Credit Balance */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <p className="text-sm text-text-muted">Current Credit Balance</p>
        <p className="text-4xl font-bold text-text mt-1">
          {creditBalance.toLocaleString()}
        </p>
        <p className="text-xs text-text-muted mt-2">
          Total transactions: {totalTransactions.toLocaleString()}
        </p>
      </div>

      {/* Earnings Chart */}
      <EarningsChart data={chartData} />

      {/* Earnings Breakdown by Type */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold text-text mb-4">Earnings by Type</h2>
        {breakdown.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {breakdown.map((b) => (
              <div
                key={b.type}
                className="bg-background rounded-lg p-4"
              >
                <p className="text-xs text-text-muted uppercase tracking-wide">
                  {b.type.replace("_", " ")}
                </p>
                <p className="text-2xl font-bold text-text mt-1">
                  {b.total.toLocaleString()} credits
                </p>
                <p className="text-xs text-text-muted mt-1">
                  {b.count} transaction{b.count !== 1 ? "s" : ""}
                </p>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-text-muted">No earnings data yet.</p>
        )}
      </div>

      {/* Transaction History */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold text-text mb-4">All Transactions</h2>
        {transactions.length > 0 ? (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-surface-light text-left">
                    <th className="pb-3 text-text-muted font-medium">Date</th>
                    <th className="pb-3 text-text-muted font-medium">Type</th>
                    <th className="pb-3 text-text-muted font-medium text-right">Amount</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-surface-light">
                  {transactions.map((tx) => (
                    <tr key={tx.id}>
                      <td className="py-3 text-text-muted">
                        {new Date(tx.created_at).toLocaleDateString()}
                      </td>
                      <td className="py-3">
                        <span className="text-xs bg-primary/20 text-primary px-2 py-1 rounded-full">
                          {tx.type}
                        </span>
                      </td>
                      <td className="py-3 text-right font-semibold text-green-400">
                        +{Number(tx.amount)} credits
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center justify-center gap-2 mt-6">
                {page > 1 && (
                  <Link
                    href={`/dashboard/provider/earnings?page=${page - 1}`}
                    className="px-3 py-1 text-sm bg-surface-light rounded-lg text-text hover:bg-primary/20 transition-colors"
                  >
                    Previous
                  </Link>
                )}
                <span className="text-sm text-text-muted">
                  Page {page} of {totalPages}
                </span>
                {page < totalPages && (
                  <Link
                    href={`/dashboard/provider/earnings?page=${page + 1}`}
                    className="px-3 py-1 text-sm bg-surface-light rounded-lg text-text hover:bg-primary/20 transition-colors"
                  >
                    Next
                  </Link>
                )}
              </div>
            )}
          </>
        ) : (
          <p className="text-text-muted">No transactions found.</p>
        )}
      </div>
    </div>
  );
}
