"use client";

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

type UpdateCreativeFormProps = {
  previewId: string;
  currentUrl: string;
  clientEmail?: string;
  publicToken: string;
  currentStatus: string;
};

export default function UpdateCreativeForm({
  previewId,
  currentUrl,
  clientEmail,
  publicToken,
  currentStatus,
}: UpdateCreativeFormProps) {
  const router = useRouter();

  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isUpdateOpen, setIsUpdateOpen] = useState(false);
  const [showNotifyConfirm, setShowNotifyConfirm] = useState(false);
  const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);

  const [vendorUrl, setVendorUrl] = useState(currentUrl);

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isArchiving, setIsArchiving] = useState(false);

  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    setIsSubmitting(true);
    setError("");
    setSuccess("");

    try {
      const response = await fetch(`/api/previews/${previewId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          vendorUrl,
        }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Unable to update creative.");
      }

      setSuccess("Revised creative saved.");
      setIsUpdateOpen(false);
      setIsMenuOpen(false);

      router.refresh();
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Unable to update creative.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  async function handleArchive() {
    setIsArchiving(true);
    setError("");

    try {
      const response = await fetch(`/api/previews/${previewId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          archived: true,
        }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Unable to move preview to Bin.");
      }

      setShowArchiveConfirm(false);
      setIsMenuOpen(false);

      router.refresh();
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Unable to move preview to Bin.",
      );
    } finally {
      setIsArchiving(false);
    }
  }

  function handleNotifyClient() {
    if (!clientEmail) {
      setShowNotifyConfirm(false);
      setError("No client email is available for this preview.");
      return;
    }

    const previewUrl = `${window.location.origin}/preview/${publicToken}`;

    const subject = "Your revised creative is ready for review";

    const body = `Hi,

The changes requested for your creative have been completed.

Please review the revised creative using the same preview link:

${previewUrl}

Kind regards,
Rook Digital`;

    const outlookUrl =
      `https://outlook.office.com/mail/deeplink/compose` +
      `?to=${encodeURIComponent(clientEmail)}` +
      `&subject=${encodeURIComponent(subject)}` +
      `&body=${encodeURIComponent(body)}`;

    window.open(outlookUrl, "_blank");

    setShowNotifyConfirm(false);
    setIsMenuOpen(false);
  }

  return (
    <>
      {/* THREE-DOT ACTION MENU */}
      <div className="absolute right-5 top-5 z-30">
        <button
          aria-label="Preview actions"
          className="flex h-10 w-10 items-center justify-center rounded-full border border-slate-200 bg-white text-lg font-bold tracking-[0.08em] text-slate-500 shadow-sm transition hover:border-[#309FC3]/40 hover:bg-[#F2FAFC] hover:text-[#309FC3]"
          onClick={() => {
            setIsMenuOpen((current) => !current);
            setError("");
          }}
          type="button"
        >
          •••
        </button>

        {isMenuOpen && (
          <div className="absolute right-0 mt-2 w-52 overflow-hidden rounded-2xl border border-slate-200 bg-white p-1.5 shadow-[0_18px_55px_rgba(7,23,34,0.18)]">
            <button
              className="flex w-full items-center rounded-xl px-4 py-3 text-left text-sm font-semibold text-[#071722] transition hover:bg-[#EEF8FB] hover:text-[#287F9C]"
              onClick={() => {
                setVendorUrl(currentUrl);
                setError("");
                setIsMenuOpen(false);
                setIsUpdateOpen(true);
              }}
              type="button"
            >
              Update Creative
            </button>

            {clientEmail && currentStatus === "pending" && (
              <button
                className="flex w-full items-center rounded-xl px-4 py-3 text-left text-sm font-semibold text-[#287F9C] transition hover:bg-[#EEF8FB]"
                onClick={() => {
                  setIsMenuOpen(false);
                  setShowNotifyConfirm(true);
                }}
                type="button"
              >
                Notify Client
              </button>
            )}

            <div className="my-1 border-t border-slate-100" />

            <button
              className="flex w-full items-center rounded-xl px-4 py-3 text-left text-sm font-semibold text-rose-600 transition hover:bg-rose-50"
              onClick={() => {
                setError("");
                setIsMenuOpen(false);
                setShowArchiveConfirm(true);
              }}
              type="button"
            >
              Move to Bin
            </button>
          </div>
        )}
      </div>

      {/* SUCCESS MESSAGE */}
      {success && (
        <div className="fixed bottom-6 right-6 z-40 rounded-2xl border border-emerald-200 bg-white px-5 py-4 shadow-xl">
          <p className="text-sm font-semibold text-emerald-700">
            Revised creative saved.
          </p>
        </div>
      )}

      {/* UPDATE CREATIVE MODAL */}
      {isUpdateOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <form
            className="w-full max-w-lg rounded-3xl bg-white p-6 shadow-2xl"
            onSubmit={handleSubmit}
          >
            <p className="text-[10px] font-bold tracking-[0.14em] text-[#309FC3] uppercase">
              Creative management
            </p>

            <h3 className="mt-2 text-xl font-bold text-[#071722]">
              Update Creative
            </h3>

            <p className="mt-2 text-sm leading-6 text-slate-500">
              Paste the revised Nexd or Innovid preview URL below. The existing
              Rook client link will stay the same.
            </p>

            <label
              className="mt-6 block text-[10px] font-bold tracking-[0.12em] text-slate-500 uppercase"
              htmlFor={`vendorUrl-${previewId}`}
            >
              Revised creative URL
            </label>

            <input
              className="mt-2 w-full rounded-xl border border-slate-200 px-4 py-3 text-sm text-[#071722] outline-none transition focus:border-[#309FC3]"
              id={`vendorUrl-${previewId}`}
              onChange={(event) => setVendorUrl(event.target.value)}
              required
              type="url"
              value={vendorUrl}
            />

            {error && (
              <p className="mt-3 text-xs font-semibold text-rose-700">
                {error}
              </p>
            )}

            <div className="mt-6 flex gap-3">
              <button
                className="flex-1 rounded-xl border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-slate-50"
                onClick={() => {
                  setIsUpdateOpen(false);
                  setVendorUrl(currentUrl);
                  setError("");
                }}
                type="button"
              >
                Cancel
              </button>

              <button
                className="flex-1 rounded-xl bg-[#071722] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#309FC3] disabled:opacity-60"
                disabled={isSubmitting}
                type="submit"
              >
                {isSubmitting ? "Saving..." : "Save Revised Creative"}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* NOTIFY CLIENT CONFIRMATION */}
      {showNotifyConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="w-full max-w-md rounded-3xl bg-white p-6 shadow-2xl">
            <h3 className="text-xl font-bold text-[#071722]">
              Notify client?
            </h3>

            <p className="mt-3 text-sm leading-6 text-slate-600">
              Are you sure the revised creative is ready for client review?
              The client will be notified to review it using the same preview
              link.
            </p>

            <div className="mt-6 flex gap-3">
              <button
                className="flex-1 rounded-xl border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-600"
                onClick={() => setShowNotifyConfirm(false)}
                type="button"
              >
                Cancel
              </button>

              <button
                className="flex-1 rounded-xl bg-[#071722] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#309FC3]"
                onClick={handleNotifyClient}
                type="button"
              >
                Yes, Notify Client
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MOVE TO BIN CONFIRMATION */}
      {showArchiveConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="w-full max-w-md rounded-3xl bg-white p-6 shadow-2xl">
            <h3 className="text-xl font-bold text-[#071722]">
              Move preview to Bin?
            </h3>

            <p className="mt-3 text-sm leading-6 text-slate-600">
              This preview will disappear from the main dashboard, but it can
              be restored later.
            </p>

            <div className="mt-6 flex gap-3">
              <button
                className="flex-1 rounded-xl border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-600"
                onClick={() => setShowArchiveConfirm(false)}
                type="button"
              >
                Cancel
              </button>

              <button
                className="flex-1 rounded-xl bg-rose-600 px-4 py-3 text-sm font-semibold text-white transition hover:bg-rose-700 disabled:opacity-60"
                disabled={isArchiving}
                onClick={handleArchive}
                type="button"
              >
                {isArchiving ? "Moving..." : "Yes, Move to Bin"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}