"use client";

import { useState } from "react";
import { Loader2, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { notify } from "@/lib/notifications/store";

interface DeleteAccountCardProps {
  accountId: string;
  accountName: string;
  onDeleted?: () => void;
}

export function DeleteAccountCard({ accountId, accountName, onDeleted }: DeleteAccountCardProps) {
  const [deleting, setDeleting] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);

  async function handleDelete() {
    setDeleting(true);
    try {
      const res = await fetch(`/api/accounts/${accountId}`, { method: "DELETE" });
      const text = await res.text();
      const data = text.trim() ? (JSON.parse(text) as { error?: string; activeAccountId?: string | null }) : {};

      if (!res.ok) {
        throw new Error(data.error ?? "刪除失敗");
      }

      notify({ type: "success", title: "已刪除帳號" });
      if (data.activeAccountId) {
        onDeleted?.();
        return;
      }
      window.location.reload();
    } catch (error) {
      notify({
        type: "error",
        title: "刪除失敗",
        message: error instanceof Error ? error.message : "未知錯誤",
      });
    } finally {
      setDeleting(false);
    }
  }

  return (
    <Card className="border-destructive/30">
      <CardHeader>
        <CardTitle className="text-destructive">刪除帳號</CardTitle>
        <CardDescription>
          永久刪除「{accountName}」與其主題、海巡、草稿、發文紀錄。不會影響你的 AI Key 與其他帳號。
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Button variant="destructive" onClick={() => setConfirmOpen(true)} disabled={deleting}>
          {deleting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
          刪除目前帳號
        </Button>
        <ConfirmDialog
          open={confirmOpen}
          onOpenChange={setConfirmOpen}
          title="刪除帳號"
          description={`確定要刪除「${accountName}」？會一併刪除這個帳號的主題、海巡紀錄、草稿與發文資料，且無法復原。`}
          confirmText="永久刪除"
          danger
          onConfirm={handleDelete}
        />
      </CardContent>
    </Card>
  );
}
