"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

type Props = {
  notificationId: string;
  unread: boolean;
  canRetry: boolean;
};

export default function NotificationActions({
  notificationId,
  unread,
  canRetry,
}: Props) {
  const router = useRouter();

  const [marking, setMarking] = useState(false);
  const [retrying, setRetrying] = useState(false);
  const [read, setRead] = useState(!unread);
  const [retried, setRetried] = useState(false);
  const [error, setError] = useState("");

  async function markRead() {
    if (marking || read) return;

    setMarking(true);
    setError("");

    try {
      const response = await fetch(
        `/api/notifications/${encodeURIComponent(notificationId)}/read`,
        {
          method: "PATCH",
          headers: {
            Accept: "application/json",
          },
          credentials: "same-origin",
        },
      );

      const body = await response.json().catch(() => null);

      if (!response.ok || !body?.success) {
        throw new Error(
          typeof body?.error === "string"
            ? body.error
            : "Unable to mark notification as read.",
        );
      }

      setRead(true);
      router.refresh();
    } catch (error) {
      setError(
        error instanceof Error
          ? error.message
          : "Unable to mark notification as read.",
      );
    } finally {
      setMarking(false);
    }
  }

  async function retryEmail() {
    if (retrying || retried) return;

    setRetrying(true);
    setError("");

    try {
      const response = await fetch(
        `/api/notifications/${encodeURIComponent(notificationId)}/retry-email`,
        {
          method: "POST",
          headers: {
            Accept: "application/json",
          },
          credentials: "same-origin",
        },
      );

      const body = await response.json().catch(() => null);

      if (!response.ok || !body?.success) {
        throw new Error(
          typeof body?.error === "string"
            ? body.error
            : "Unable to retry notification email.",
        );
      }

      setRetried(true);
      router.refresh();
    } catch (error) {
      setError(
        error instanceof Error
          ? error.message
          : "Unable to retry notification email.",
      );
    } finally {
      setRetrying(false);
    }
  }

  return (
    <div className="mt-4">
      <div className="flex flex-wrap items-center gap-2">
        {!read ? (
          <button
            type="button"
            onClick={markRead}
            disabled={marking}
            className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-slate-700 transition hover:border-blue-300 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {marking ? "MARKING..." : "MARK AS READ"}
          </button>
        ) : (
          <span className="rounded-lg bg-emerald-50 px-3 py-2 text-xs font-bold text-emerald-700">
            READ
          </span>
        )}

        {canRetry && !retried && (
          <button
            type="button"
            onClick={retryEmail}
            disabled={retrying}
            className="rounded-lg bg-blue-600 px-3 py-2 text-xs font-bold text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {retrying ? "RETRYING..." : "RETRY EMAIL"}
          </button>
        )}

        {retried && (
          <span className="rounded-lg bg-emerald-50 px-3 py-2 text-xs font-bold text-emerald-700">
            EMAIL RETRIED
          </span>
        )}
      </div>

      {error && (
        <p className="mt-2 text-xs font-semibold text-red-600">
          {error}
        </p>
      )}
    </div>
  );
}
