"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Check } from "lucide-react";
import {
  retryEmailJobAction,
  resendEmailAction,
} from "@/features/email/actions";

const BTN_CLS =
  "rounded-lg border border-primary-200 bg-primary-50 px-2.5 py-1 text-[11px] font-semibold text-primary-700 transition-colors hover:bg-primary-100 disabled:cursor-not-allowed disabled:opacity-50";

/** E5.2 — tombol kirim ulang untuk satu EmailJob (antri / gagal). */
export function RetryEmailButton({ jobId }: { jobId: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleRetry() {
    setLoading(true);
    setError("");
    const res = await retryEmailJobAction(jobId);
    setLoading(false);
    if ("error" in res) {
      setError(res.error ?? "Gagal");
      return;
    }
    router.refresh();
  }

  return (
    <div>
      <button
        type="button"
        onClick={handleRetry}
        disabled={loading}
        className={BTN_CLS}
      >
        {loading ? "Mengirim…" : "Kirim ulang"}
      </button>
      {error && (
        <p className="mt-1 max-w-50 text-[10px] text-red-600">{error}</p>
      )}
    </div>
  );
}

/** E5.3 — tombol resend untuk email yang sudah terkirim. */
export function ResendEmailButton({
  emailSentId,
  disabled,
}: {
  emailSentId: string;
  disabled?: boolean;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState(false);

  async function handleResend() {
    setLoading(true);
    setError("");
    const res = await resendEmailAction(emailSentId);
    setLoading(false);
    if ("error" in res) {
      setError(res.error ?? "Gagal");
      return;
    }
    setDone(true);
    router.refresh();
  }

  if (disabled) {
    return (
      <span
        className="text-[10px] text-neutral-400"
        title="Body email lama tidak tersimpan"
      >
        —
      </span>
    );
  }

  return (
    <div>
      <button
        type="button"
        onClick={handleResend}
        disabled={loading || done}
        className={`${BTN_CLS} inline-flex items-center gap-1`}
      >
        {loading ? (
          "Mengirim…"
        ) : done ? (
          <>
            <Check size={12} strokeWidth={2.5} aria-hidden />
            Terkirim
          </>
        ) : (
          "Resend"
        )}
      </button>
      {error && (
        <p className="mt-1 max-w-50 text-[10px] text-red-600">{error}</p>
      )}
    </div>
  );
}
