"use client";

import * as React from "react";
import Link from "next/link";
import { toast } from "sonner";
import { Loader2, Pause, Play, RotateCw, XCircle } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { StatusBadge } from "@/components/shared/status-badge";
import {
  cancelSubscriptionAction,
  pauseSubscriptionAction,
  resumeSubscriptionAction,
} from "@/lib/actions/bulk";
import { formatDate, formatDateTime, formatMinutes, formatNumber } from "@/lib/format";
import { bulkTexts } from "@/lib/i18n/bulk";

export type SubscriptionRowDTO = {
  id: string;
  shortId: string;
  username: string;
  minQuantity: number;
  maxQuantity: number;
  posts: number | null;
  postsDelivered: number;
  oldPosts: number | null;
  oldPostsDelivered: number;
  delayMinutes: number;
  serviceId: number;
  serviceName: string;
  status: string;
  createdAt: string;
  updatedAt: string;
  expiryAt: string;
  undeliveredPosts: number;
  refundEstimate: string;
  canPause: boolean;
  canResume: boolean;
  canCancel: boolean;
};

function PostsCell({ done, total }: { done: number; total: number | null }) {
  if (total === null || total <= 0) {
    return <span className="text-xs text-muted-foreground">{bulkTexts.subsNotIncluded}</span>;
  }
  const pct = Math.min(100, Math.round((done / total) * 100));
  return (
    <div className="min-w-[84px] space-y-1.5">
      <span className="font-mono text-sm tabular-nums">
        {done} <span className="text-muted-foreground">/ {total}</span>
      </span>
      <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
        <div
          className="h-full rounded-full bg-cyan-500 transition-all"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}

export function SubscriptionsTable({ rows }: { rows: SubscriptionRowDTO[] }) {
  const [target, setTarget] = React.useState<SubscriptionRowDTO | null>(null);
  const [busyId, setBusyId] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  function run(
    id: string,
    action: (id: string) => Promise<{ ok: boolean; error?: string }>,
    successMessage: string,
  ) {
    setBusyId(id);
    startTransition(async () => {
      const result = await action(id);
      if (result.ok) toast.success(successMessage);
      else toast.error(result.error ?? bulkTexts.subsNotFound);
      setBusyId(null);
    });
  }

  function confirmCancel() {
    if (!target) return;
    const row = target;
    setBusyId(row.id);
    startTransition(async () => {
      const result = await cancelSubscriptionAction(row.id);
      if (result.ok) {
        const refunded = result.data?.refunded;
        toast.success(
          refunded && refunded !== "$0.00"
            ? bulkTexts.subsCancelRefunded(refunded)
            : bulkTexts.subsCancelSuccess,
        );
        setTarget(null);
      } else {
        toast.error(result.error);
      }
      setBusyId(null);
    });
  }

  return (
    <>
      <div>
        <Table className="text-sm">
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColId}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColUsername}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColQuantity}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColNewPosts}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColOldPosts}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColDelay}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColService}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColStatus}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColCreated}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColUpdated}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.subsColExpiry}</TableHead>
              <TableHead className="text-right whitespace-nowrap" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.map((row) => {
              const busy = pending && busyId === row.id;
              return (
                <TableRow key={row.id} className="align-top">
                  <TableCell
                    className="font-mono text-xs whitespace-nowrap text-muted-foreground"
                    title={row.id}
                  >
                    {row.shortId}
                  </TableCell>
                  <TableCell className="font-medium whitespace-nowrap">
                    @{row.username}
                  </TableCell>
                  <TableCell className="font-mono whitespace-nowrap tabular-nums">
                    {formatNumber(row.minQuantity)}
                    <span className="text-muted-foreground"> – </span>
                    {formatNumber(row.maxQuantity)}
                  </TableCell>
                  <TableCell>
                    <PostsCell done={row.postsDelivered} total={row.posts} />
                  </TableCell>
                  <TableCell>
                    <PostsCell done={row.oldPostsDelivered} total={row.oldPosts} />
                  </TableCell>
                  <TableCell className="font-mono whitespace-nowrap tabular-nums">
                    {row.delayMinutes > 0 ? (
                      formatMinutes(row.delayMinutes)
                    ) : (
                      <span className="font-sans text-xs text-muted-foreground">
                        {bulkTexts.subsNoDelay}
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="max-w-[220px] whitespace-normal">
                    <Link
                      href={`/?service=${row.serviceId}`}
                      className="line-clamp-2 transition-colors hover:text-blue-600 dark:hover:text-blue-400"
                    >
                      {row.serviceName}
                    </Link>
                    <div className="font-mono text-xs text-muted-foreground">
                      #{row.serviceId}
                    </div>
                  </TableCell>
                  <TableCell className="whitespace-nowrap">
                    <StatusBadge status={row.status} />
                  </TableCell>
                  <TableCell className="whitespace-nowrap text-muted-foreground">
                    {formatDateTime(row.createdAt)}
                  </TableCell>
                  <TableCell className="whitespace-nowrap text-muted-foreground">
                    {formatDateTime(row.updatedAt)}
                  </TableCell>
                  <TableCell className="whitespace-nowrap">
                    {row.expiryAt ? (
                      formatDate(row.expiryAt)
                    ) : (
                      <span className="text-xs text-muted-foreground">
                        {bulkTexts.subsNoExpiry}
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      {row.canPause ? (
                        <Button
                          variant="ghost"
                          size="sm"
                          disabled={pending}
                          onClick={() =>
                            run(row.id, pauseSubscriptionAction, bulkTexts.subsPaused)
                          }
                        >
                          {busy ? (
                            <Loader2 className="size-3.5 animate-spin" />
                          ) : (
                            <Pause className="size-3.5" />
                          )}
                          {bulkTexts.subsPause}
                        </Button>
                      ) : null}
                      {row.canResume ? (
                        <Button
                          variant="ghost"
                          size="sm"
                          disabled={pending}
                          onClick={() =>
                            run(row.id, resumeSubscriptionAction, bulkTexts.subsResumed)
                          }
                        >
                          {busy ? (
                            <Loader2 className="size-3.5 animate-spin" />
                          ) : (
                            <Play className="size-3.5" />
                          )}
                          {bulkTexts.subsResume}
                        </Button>
                      ) : null}
                      <Button variant="ghost" size="sm" asChild>
                        <Link href={`/?service=${row.serviceId}`}>
                          <RotateCw className="size-3.5" />
                          {bulkTexts.subsReorder}
                        </Link>
                      </Button>
                      {row.canCancel ? (
                        <Button
                          variant="destructive"
                          size="sm"
                          disabled={pending}
                          onClick={() => setTarget(row)}
                        >
                          <XCircle className="size-3.5" />
                          {bulkTexts.subsCancel}
                        </Button>
                      ) : null}
                    </div>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>

      <AlertDialog
        open={target !== null}
        onOpenChange={(open) => {
          if (!open && !pending) setTarget(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{bulkTexts.subsCancelTitle}</AlertDialogTitle>
            <AlertDialogDescription>{bulkTexts.subsCancelBody}</AlertDialogDescription>
          </AlertDialogHeader>

          {target ? (
            <dl className="grid gap-2 rounded-xl border bg-muted/40 p-3 text-sm">
              <div className="flex items-center justify-between gap-4">
                <dt className="text-muted-foreground">{bulkTexts.subsColUsername}</dt>
                <dd className="font-medium">@{target.username}</dd>
              </div>
              <div className="flex items-center justify-between gap-4">
                <dt className="text-muted-foreground">{bulkTexts.subsCancelRemaining}</dt>
                <dd className="font-mono tabular-nums">{target.undeliveredPosts}</dd>
              </div>
              <div className="flex items-center justify-between gap-4 border-t pt-2">
                <dt className="font-medium">{bulkTexts.subsCancelRefund}</dt>
                <dd className="font-mono font-semibold text-emerald-600 tabular-nums dark:text-emerald-400">
                  {target.refundEstimate}
                </dd>
              </div>
              {target.refundEstimate === "$0.00" ? (
                <p className="text-xs text-muted-foreground">
                  {bulkTexts.subsCancelNoRefund}
                </p>
              ) : null}
            </dl>
          ) : null}

          <AlertDialogFooter>
            <AlertDialogCancel disabled={pending}>
              {bulkTexts.subsCancelKeep}
            </AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              disabled={pending}
              onClick={(event) => {
                event.preventDefault();
                confirmCancel();
              }}
            >
              {pending ? (
                <Loader2 className="size-3.5 animate-spin" />
              ) : (
                <XCircle className="size-3.5" />
              )}
              {bulkTexts.subsCancelConfirm}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

export default SubscriptionsTable;
