"use client";

import * as React from "react";
import Link from "next/link";
import { toast } from "sonner";
import { Clock, ExternalLink, Loader2, 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 { cancelDripFeedAction } from "@/lib/actions/bulk";
import { formatDateTime, formatMinutes, formatNumber, truncateLink } from "@/lib/format";
import { bulkTexts } from "@/lib/i18n/bulk";
import { cn } from "@/lib/utils";

export type DripFeedRowDTO = {
  id: string;
  orderId: number;
  createdAt: string;
  link: string;
  totalCharge: string;
  quantityPerRun: number;
  serviceId: number;
  serviceName: string;
  runs: number;
  runsCompleted: number;
  intervalMinutes: number;
  totalQuantity: number;
  undeliveredQuantity: number;
  status: string;
  orderStatus: string;
  nextRunAt: string;
  refundEstimate: string;
  canCancel: boolean;
};

function RunsCell({ done, total }: { done: number; total: number }) {
  const pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : 0;
  return (
    <div className="min-w-[92px] 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-blue-600 transition-all dark:bg-blue-500"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}

export function DripFeedTable({ rows }: { rows: DripFeedRowDTO[] }) {
  const [target, setTarget] = React.useState<DripFeedRowDTO | null>(null);
  const [pending, startTransition] = React.useTransition();

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

  return (
    <>
      <div>
        <Table className="text-sm">
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColId}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColDate}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColLink}</TableHead>
              <TableHead className="whitespace-nowrap">
                {bulkTexts.dripColTotalCharge}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {bulkTexts.dripColQuantity}
              </TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColService}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColRuns}</TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColInterval}</TableHead>
              <TableHead className="whitespace-nowrap">
                {bulkTexts.dripColTotalQuantity}
              </TableHead>
              <TableHead className="whitespace-nowrap">{bulkTexts.dripColStatus}</TableHead>
              <TableHead className="text-right whitespace-nowrap" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.map((row) => (
              <TableRow key={row.id} className="align-top">
                <TableCell className="font-mono text-sm whitespace-nowrap tabular-nums">
                  {row.orderId}
                </TableCell>
                <TableCell className="whitespace-nowrap text-muted-foreground">
                  {formatDateTime(row.createdAt)}
                </TableCell>
                <TableCell className="max-w-[220px]">
                  <a
                    href={row.link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-blue-600 transition-colors hover:underline dark:text-blue-400"
                    title={row.link}
                  >
                    <span className="truncate">{truncateLink(row.link, 34)}</span>
                    <ExternalLink className="size-3 shrink-0 opacity-60" />
                  </a>
                </TableCell>
                <TableCell className="font-mono whitespace-nowrap tabular-nums">
                  {row.totalCharge}
                </TableCell>
                <TableCell className="whitespace-nowrap">
                  <div className="font-mono tabular-nums">
                    {formatNumber(row.quantityPerRun)}
                  </div>
                  <div className="text-xs text-muted-foreground">{bulkTexts.dripPerRun}</div>
                </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>
                  <RunsCell done={row.runsCompleted} total={row.runs} />
                </TableCell>
                <TableCell className="whitespace-nowrap">
                  <div className="font-mono tabular-nums">
                    {formatMinutes(row.intervalMinutes)}
                  </div>
                  {row.nextRunAt && row.status === "ACTIVE" ? (
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                      <Clock className="size-3" />
                      {formatDateTime(row.nextRunAt)}
                    </div>
                  ) : null}
                </TableCell>
                <TableCell className="font-mono whitespace-nowrap tabular-nums">
                  {formatNumber(row.totalQuantity)}
                </TableCell>
                <TableCell className="whitespace-nowrap">
                  <StatusBadge status={row.status} />
                  <div className="mt-1 text-xs text-muted-foreground">
                    Order: {row.orderStatus.replace(/_/g, " ").toLowerCase()}
                  </div>
                </TableCell>
                <TableCell className="text-right whitespace-nowrap">
                  {row.canCancel ? (
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => setTarget(row)}
                      disabled={pending}
                    >
                      <XCircle className="size-3.5" />
                      {bulkTexts.dripCancel}
                    </Button>
                  ) : (
                    <span className="text-xs text-muted-foreground">—</span>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <AlertDialog
        open={target !== null}
        onOpenChange={(open) => {
          if (!open && !pending) setTarget(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{bulkTexts.dripCancelTitle}</AlertDialogTitle>
            <AlertDialogDescription>{bulkTexts.dripCancelBody}</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.dripCancelRunsLeft}</dt>
                <dd className="font-mono tabular-nums">
                  {Math.max(0, target.runs - target.runsCompleted)} / {target.runs}
                </dd>
              </div>
              <div className="flex items-center justify-between gap-4">
                <dt className="text-muted-foreground">{bulkTexts.dripCancelUndelivered}</dt>
                <dd className="font-mono tabular-nums">
                  {formatNumber(target.undeliveredQuantity)}
                </dd>
              </div>
              <div className="flex items-center justify-between gap-4 border-t pt-2">
                <dt className="font-medium">{bulkTexts.dripCancelRefund}</dt>
                <dd className="font-mono font-semibold text-emerald-600 tabular-nums dark:text-emerald-400">
                  {target.refundEstimate}
                </dd>
              </div>
            </dl>
          ) : null}

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

export default DripFeedTable;
