"use client";

import { useState } from "react";
import { Trash2 } from "lucide-react";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/components/providers/locale-provider";

export function TemplateDeleteButton({
  id,
  name,
  onDeleted,
}: {
  id: string;
  name: string;
  onDeleted?: () => void;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleDelete() {
    setLoading(true);
    setError(null);
    const res = await fetch(`/api/email-templates/${id}`, { method: "DELETE" });
    const json = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(
        (json as { error?: string }).error ??
          (isAr ? "فشل حذف القالب" : "Failed to delete template")
      );
      return;
    }
    setOpen(false);
    onDeleted?.();
  }

  return (
    <>
      <Button
        type="button"
        variant="outline"
        size="sm"
        title={isAr ? "حذف" : "Delete"}
        className="text-destructive hover:bg-destructive/10"
        onClick={() => setOpen(true)}
      >
        <Trash2 className="h-3.5 w-3.5" />
      </Button>
      <ConfirmDialog
        open={open}
        title={isAr ? "حذف القالب؟" : "Delete template?"}
        description={
          isAr
            ? `سيتم أرشفة القالب «${name}» ولن يظهر في القوائم. الحملات المرتبطة تحتفظ بمراجعته.`
            : `Template "${name}" will be archived and hidden from lists. Linked campaigns keep their reference.`
        }
        confirmLabel={isAr ? "حذف" : "Delete"}
        cancelLabel={isAr ? "إلغاء" : "Cancel"}
        destructive
        loading={loading}
        onCancel={() => {
          setOpen(false);
          setError(null);
        }}
        onConfirm={() => void handleDelete()}
      />
      {error && open ? (
        <p className="fixed bottom-4 left-1/2 z-[60] -translate-x-1/2 rounded bg-destructive px-3 py-2 text-sm text-destructive-foreground">
          {error}
        </p>
      ) : null}
    </>
  );
}
