"use client";

import { use, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Button, Chip, Modal, Spinner } from "@heroui/react";
import { ArrowLeft, ArrowRotateRight, TrashBin } from "@gravity-ui/icons";
import { APIError, api } from "@/lib/api";
import { useSession } from "@/lib/auth-client";
import dayjs from "@/lib/dayjs";

function formatDuration(start: string, stop: string | null): string {
  if (!stop) return "进行中";
  const min = dayjs(stop).diff(dayjs(start), "minute");
  if (min < 60) return `${min} 分钟`;
  const h = Math.floor(min / 60);
  const m = min % 60;
  return `${h}h ${m}m`;
}

function formatDateTime(iso: string | null | undefined): string {
  if (!iso) return "—";
  return dayjs(iso).format("YYYY/M/D HH:mm:ss");
}

function formatEnergy(wh: number | null | undefined): string {
  if (wh == null) return "—";
  return `${(wh / 1000).toFixed(3)} kWh`;
}

function formatAmount(fen: number | null | undefined): string {
  if (fen == null) return "—";
  return `¥${(fen / 100).toFixed(2)}`;
}

export default function TransactionDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const txId = Number(id);
  const isValidId = Number.isInteger(txId) && txId > 0;

  const [stopping, setStopping] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const { data: sessionData } = useSession();
  const isAdmin = sessionData?.user?.role === "admin";

  const {
    data: tx,
    isPending,
    isFetching,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: ["transaction", txId],
    queryFn: () => api.transactions.get(txId),
    enabled: isValidId,
    refetchInterval: 3_000,
    retry: false,
  });

  const handleStop = async () => {
    if (!tx) return;
    setStopping(true);
    try {
      await api.transactions.stop(tx.id);
      await refetch();
    } finally {
      setStopping(false);
    }
  };

  const handleDelete = async () => {
    if (!tx) return;
    setDeleting(true);
    try {
      await api.transactions.delete(tx.id);
      router.push("/dashboard/transactions");
    } finally {
      setDeleting(false);
    }
  };

  if (!isValidId) {
    return (
      <div className="space-y-4">
        <Link
          href="/dashboard/transactions"
          className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
        >
          <ArrowLeft className="size-4" />
          充电记录
        </Link>
        <p className="text-sm text-danger">无效的交易编号。</p>
      </div>
    );
  }

  if (isPending) {
    return (
      <div className="flex h-48 items-center justify-center">
        <Spinner />
      </div>
    );
  }

  if (isError || !tx) {
    const notFound = error instanceof APIError && error.status === 404;
    return (
      <div className="space-y-4">
        <Link
          href="/dashboard/transactions"
          className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
        >
          <ArrowLeft className="size-4" />
          充电记录
        </Link>
        <p className="text-sm text-danger">
          {notFound ? "交易记录不存在。" : "加载交易记录失败。"}
        </p>
      </div>
    );
  }

  const energyWh = tx.energyWh ?? tx.liveEnergyWh;
  const amountFen = tx.chargeAmount ?? tx.estimatedCost;
  const isEstimatedEnergy = tx.energyWh == null && tx.liveEnergyWh != null;
  const isEstimatedAmount = tx.chargeAmount == null && tx.estimatedCost != null;

  return (
    <div className="space-y-6">
      <Link
        href="/dashboard/transactions"
        className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
      >
        <ArrowLeft className="size-4" />
        充电记录
      </Link>

      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-1.5">
          <div className="flex flex-wrap items-center gap-2">
            <h1 className="font-mono text-2xl font-semibold text-foreground">充电订单#{tx.id}</h1>
            {tx.stopTimestamp ? (
              <Chip color="success" size="sm" variant="soft">
                已完成
              </Chip>
            ) : (
              <Chip color="warning" size="sm" variant="soft">
                进行中
              </Chip>
            )}
            {isEstimatedAmount && (
              <Chip color="warning" size="sm" variant="soft">
                费用预估
              </Chip>
            )}
          </div>
          <p className="text-sm text-muted">
            开始于 {formatDateTime(tx.startTimestamp)} · {tx.stopTimestamp ? "时长 " : ""}
            {formatDuration(tx.startTimestamp, tx.stopTimestamp)}
          </p>
        </div>

        <div className="flex items-center gap-2">
          <Button
            isIconOnly
            size="sm"
            variant="ghost"
            isDisabled={isFetching}
            onPress={() => refetch()}
            aria-label="刷新"
          >
            <ArrowRotateRight className={`size-4 ${isFetching ? "animate-spin" : ""}`} />
          </Button>

          {!tx.stopTimestamp && (
            <Modal>
              <Button size="sm" variant="danger-soft" isDisabled={stopping}>
                {stopping ? <Spinner size="sm" /> : "中止充电"}
              </Button>
              <Modal.Backdrop>
                <Modal.Container scroll="outside">
                  <Modal.Dialog className="sm:max-w-96">
                    <Modal.CloseTrigger />
                    <Modal.Header>
                      <Modal.Heading>确认中止充电</Modal.Heading>
                    </Modal.Header>
                    <Modal.Body>
                      <p className="text-sm text-muted">
                        将远程中止充电交易{" "}
                        <span className="font-mono text-foreground">#{tx.id}</span>。
                      </p>
                    </Modal.Body>
                    <Modal.Footer className="flex justify-end gap-2">
                      <Button slot="close" variant="ghost">
                        取消
                      </Button>
                      <Button
                        slot="close"
                        variant="danger"
                        isDisabled={stopping}
                        onPress={handleStop}
                      >
                        {stopping ? <Spinner size="sm" /> : "确认中止"}
                      </Button>
                    </Modal.Footer>
                  </Modal.Dialog>
                </Modal.Container>
              </Modal.Backdrop>
            </Modal>
          )}

          {isAdmin && (
            <Modal>
              <Button isIconOnly size="sm" variant="tertiary" isDisabled={deleting}>
                {deleting ? <Spinner size="sm" /> : <TrashBin className="size-4" />}
              </Button>
              <Modal.Backdrop>
                <Modal.Container scroll="outside">
                  <Modal.Dialog className="sm:max-w-96">
                    <Modal.CloseTrigger />
                    <Modal.Header>
                      <Modal.Heading>确认删除记录</Modal.Heading>
                    </Modal.Header>
                    <Modal.Body>
                      <p className="text-sm text-muted">
                        将永久删除交易 <span className="font-mono text-foreground">#{tx.id}</span>。
                      </p>
                    </Modal.Body>
                    <Modal.Footer className="flex justify-end gap-2">
                      <Button slot="close" variant="ghost">
                        取消
                      </Button>
                      <Button
                        slot="close"
                        variant="danger"
                        isDisabled={deleting}
                        onPress={handleDelete}
                      >
                        {deleting ? <Spinner size="sm" /> : "确认删除"}
                      </Button>
                    </Modal.Footer>
                  </Modal.Dialog>
                </Modal.Container>
              </Modal.Backdrop>
            </Modal>
          )}
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <div className="rounded-xl border border-border bg-surface-secondary p-4">
          <p className="text-xs text-muted">充电量</p>
          <div className="mt-1 inline-flex items-center gap-1.5">
            <p className="text-xl font-semibold text-foreground">{formatEnergy(energyWh)}</p>
            {isEstimatedEnergy && (
              <span className="rounded bg-warning-soft px-1 py-0.5 text-[10px] font-semibold text-warning leading-none text-nowrap">
                预估
              </span>
            )}
          </div>
        </div>
        <div className="rounded-xl border border-border bg-surface-secondary p-4">
          <p className="text-xs text-muted">总费用</p>
          <div className="mt-1 inline-flex items-center gap-1.5">
            <p className="text-xl font-semibold text-foreground">{formatAmount(amountFen)}</p>
            {isEstimatedAmount && (
              <span className="rounded bg-warning-soft px-1 py-0.5 text-[10px] font-semibold text-warning leading-none text-nowrap">
                预估
              </span>
            )}
          </div>
        </div>
        <div className="rounded-xl border border-border bg-surface-secondary p-4">
          <p className="text-xs text-muted">状态</p>
          <p className="mt-1 text-xl font-semibold text-foreground">
            {tx.stopTimestamp ? "已完成" : "进行中"}
          </p>
        </div>
        <div className="rounded-xl border border-border bg-surface-secondary p-4">
          <p className="text-xs text-muted">停止原因</p>
          <p className="mt-1 text-xl font-semibold text-foreground">{tx.stopReason ?? "—"}</p>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="rounded-xl border border-border bg-surface-secondary">
          <div className="border-b border-border px-5 py-3.5">
            <p className="text-sm font-semibold text-foreground">交易信息</p>
          </div>
          <dl className="grid grid-cols-[120px_1fr] gap-x-4 gap-y-3 px-5 py-4 text-sm">
            <dt className="text-muted">交易编号</dt>
            <dd className="font-mono text-foreground">#{tx.id}</dd>

            <dt className="text-muted">储值卡</dt>
            <dd className="font-mono text-foreground">{tx.idTag}</dd>

            <dt className="text-muted">桩编号</dt>
            <dd className="font-mono text-foreground">{tx.chargePointIdentifier ?? "—"}</dd>

            <dt className="text-muted">连接器</dt>
            <dd className="text-foreground">{tx.connectorNumber ?? "—"}</dd>

            <dt className="text-muted">开始时间</dt>
            <dd className="text-foreground">{formatDateTime(tx.startTimestamp)}</dd>

            <dt className="text-muted">结束时间</dt>
            <dd className="text-foreground">{formatDateTime(tx.stopTimestamp)}</dd>

            <dt className="text-muted">持续时长</dt>
            <dd className="text-foreground">
              {formatDuration(tx.startTimestamp, tx.stopTimestamp)}
            </dd>
          </dl>
        </div>

        <div className="rounded-xl border border-border bg-surface-secondary">
          <div className="border-b border-border px-5 py-3.5">
            <p className="text-sm font-semibold text-foreground">计量与费用</p>
          </div>
          <dl className="grid grid-cols-[140px_1fr] gap-x-4 gap-y-3 px-5 py-4 text-sm">
            <dt className="text-muted">起始表计</dt>
            <dd className="text-foreground">
              {tx.startMeterValue != null ? `${tx.startMeterValue} Wh` : "—"}
            </dd>

            <dt className="text-muted">结束表计</dt>
            <dd className="text-foreground">
              {tx.stopMeterValue != null ? `${tx.stopMeterValue} Wh` : "—"}
            </dd>

            <dt className="text-muted">消耗电量</dt>
            <dd className="text-foreground">
              <span className="inline-flex items-center gap-1">
                {formatEnergy(energyWh)}
                {isEstimatedEnergy && (
                  <span className="rounded bg-warning-soft px-1 py-0.5 text-[10px] font-semibold text-warning leading-none text-nowrap">
                    预估
                  </span>
                )}
              </span>
            </dd>

            <dt className="text-muted">电费</dt>
            <dd className="text-foreground">{formatAmount(tx.electricityFee)}</dd>

            <dt className="text-muted">服务费</dt>
            <dd className="text-foreground">{formatAmount(tx.serviceFee)}</dd>

            <dt className="text-muted">总费用</dt>
            <dd className="text-foreground">
              <span className="inline-flex items-center gap-1">
                {formatAmount(amountFen)}
                {isEstimatedAmount && (
                  <span className="rounded bg-warning-soft px-1 py-0.5 text-[10px] font-semibold text-warning leading-none text-nowrap">
                    预估
                  </span>
                )}
              </span>
            </dd>
          </dl>
        </div>
      </div>
    </div>
  );
}
