"use client";

import { useCreditsTransactions } from "@/components/billing/hooks";
import { useLabs } from "@/components/labs/hook";
import { useMe } from "@/components/me-context";
import { Time } from "@/components/time";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useLocaleFunction } from "@/hooks/use-localed";
import { cn } from "@/lib/utils";
import { useState } from "react";

const nf = new Intl.NumberFormat(["en"]);

export function CreditsTransactions() {
  const [page, setPage] = useState(1);
  const { data: me } = useMe();
  const { data: transactions, isFetching } = useCreditsTransactions(me, page);
  const { data: labs } = useLabs();
  const t = useLocaleFunction();

  const { next, previous } = transactions ?? {};

  return (
    <section className="p-4 space-y-2 rounded-lg border bg-card">
      <h2 className="text-lg font-semibold">{t("credits.transactions")}</h2>
      <Table className={cn("transition-opacity", isFetching && "opacity-50")}>
        <TableHeader>
          <TableRow>
            <TableHead>{t("credits.transactions.credits")}</TableHead>
            <TableHead>{t("credits.transactions.source")}</TableHead>
            <TableHead>{t("credits.transactions.date")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {transactions?.results.map((transaction) => (
            <TableRow key={transaction.id}>
              <TableCell className="flex gap-4 items-center">
                {transaction.paid_credits ? (
                  <span className="text-muted-foreground">
                    {t(
                      "credits.transactions.credits.paid",
                      <CreditsValue
                        value={transaction.paid_credits}
                      ></CreditsValue>
                    )}
                  </span>
                ) : undefined}
                {transaction.free_credits ? (
                  <span className="text-muted-foreground">
                    {t(
                      "credits.transactions.credits.free",
                      <CreditsValue
                        value={transaction.free_credits}
                      ></CreditsValue>
                    )}
                  </span>
                ) : undefined}
              </TableCell>
              <TableCell>
                {transaction.transaction_type_display}
                {transaction.lab_code != null && (
                  <>
                    <br />
                    <a
                      className="underline text-xs text-muted-foreground"
                      href={`/lab?preview=${encodeURIComponent(transaction.lab_code)}`}
                      target="_blank"
                    >
                      {t(
                        labs?.find(
                          (lab) => lab.lab_code === transaction.lab_code
                        ),
                        "title"
                      )}
                    </a>
                  </>
                )}
              </TableCell>
              <TableCell>
                <Time value={transaction.created_at} />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      <div className="flex items-center gap-2 justify-end">
        {previous != null && (
          <Button
            variant="secondary"
            disabled={isFetching}
            onClick={() => setPage(getPageNumberFromUrl(previous))}
          >
            Prev Page
          </Button>
        )}
        {next != null && (
          <Button
            variant="secondary"
            disabled={isFetching}
            onClick={() => setPage(getPageNumberFromUrl(next))}
          >
            Next Page
          </Button>
        )}
      </div>
    </section>
  );
}

function CreditsValue({ value }: { value: number }) {
  return (
    <span
      className={cn(
        "font-bold",
        value > 0 ? "text-green-500" : "text-zinc-500"
      )}
    >
      {value > 0 ? "+" : ""}
      {nf.format(value)}
    </span>
  );
}

function getPageNumberFromUrl(url: string) {
  const page = new URL(url).searchParams.get("page");
  if (page == null) {
    return 1;
  }
  return parseInt(page);
}
