"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Database, Link2, Server, Wallet } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { type AppDetail, DELETE_APP_CONFIRMATION, deleteApp, dropAppQueries } from "@/lib/apps";
import { SESSION_ROUTE } from "@/lib/sessions";

interface DeleteAppDialogProps {
  app: AppDetail;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const LIVE_STATUSES = new Set(["running", "building", "switching", "suspended"]);

/**
 * 删应用确认框: 逐条列清会拆掉什么, 手打确认词才放行.
 *
 * 这是把一个应用连同部署、两个托管库、域名一起清掉的唯一入口, 不可撤销.
 */
export const DeleteAppDialog = ({ app, open, onOpenChange }: DeleteAppDialogProps) => {
  const router = useRouter();
  const queryClient = useQueryClient();
  const [confirm, setConfirm] = useState("");

  const remove = useMutation({
    mutationFn: () => deleteApp(app.id),
    onSuccess: () => {
      onOpenChange(false);
      router.push(SESSION_ROUTE);
      void dropAppQueries(queryClient, app.id);
    },
    onError: (err) => {
      toast.error(err instanceof Error ? err.message : "删除应用失败");
    },
  });

  const hasDeployment = app.deployment != null && LIVE_STATUSES.has(app.deployment.status);
  const losses = [
    hasDeployment
      ? { icon: Server, text: "拆掉 1 个在跑的部署，线上地址立刻打不开" }
      : null,
    {
      icon: Database,
      text: "永久删除应用的两个托管库（线上库 + 开发库），里面的业务数据一并清空",
    },
    app.custom_domain ? { icon: Link2, text: "释放自定义域名，别人可以再绑" } : null,
  ].filter((x) => x != null);

  const pending = remove.isPending;
  const ready = confirm === DELETE_APP_CONFIRMATION;

  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        if (pending) return;
        onOpenChange(next);
        if (!next) setConfirm("");
      }}
    >
      <DialogContent showCloseButton={!pending}>
        <DialogHeader>
          <DialogTitle className="text-destructive">删除应用「{app.title}」？</DialogTitle>
          <DialogDescription>删掉之后没有任何地方能把它找回来。</DialogDescription>
        </DialogHeader>

        <ul className="flex flex-col gap-2 text-[13px] text-foreground">
          {losses.map(({ icon: Icon, text }) => (
            <li key={text} className="flex items-start gap-2">
              <Icon size={14} className="mt-0.5 shrink-0 text-destructive" />
              <span>{text}</span>
            </li>
          ))}
        </ul>

        {hasDeployment && (
          <p className="flex items-start gap-2 text-[13px] text-muted-foreground">
            <Wallet size={14} className="mt-0.5 shrink-0" />
            <span>占用的 1 个部署位退回，可以给别的应用用</span>
          </p>
        )}

        <div className="grid gap-2">
          <Label htmlFor="delete-app-confirm" className="font-semibold text-destructive">
            请输入「{DELETE_APP_CONFIRMATION}」
          </Label>
          <input
            id="delete-app-confirm"
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            autoComplete="off"
            disabled={pending}
            className="h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
          />
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={pending}>
            取消
          </Button>
          <Button
            variant="destructive"
            onClick={() => remove.mutate()}
            disabled={!ready || pending}
          >
            {pending ? "删除中…" : "确认删除并清空数据"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
