"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

type Recipient = {
  type: "VISITOR" | "COMPANY";
  id: string;
};

type Context = {
  entityType: string;
  entityId: string;
  title: string;
  path: string;
  imageUrl?: string | null;
};

type Props = {
  recipient: Recipient;
  context?: Context;
  /** Visual variant. */
  variant?: "primary" | "ghost";
  className?: string;
  /** Optional label override (default "Pošalji poruku"). */
  label?: string;
};

/**
 * "Pošalji poruku" button that:
 *   1. Auth-gates on click — anonymous users get redirected to /prijavi-se
 *      with a return path back to where they came from.
 *   2. Opens a small popover with a textarea, sends a POST to
 *      `/api/messages/start`, and navigates to the new thread on success.
 *
 * Drop on listing detail pages and company profiles.
 */
export function StartConversationButton({
  recipient,
  context,
  variant = "primary",
  className,
  label = "Pošalji poruku",
}: Props) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [body, setBody] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [isAuthed, setIsAuthed] = useState(false);
  const [returnPath, setReturnPath] = useState("/");

  useEffect(() => {
    setReturnPath(window.location.pathname);
    let cancelled = false;
    Promise.all([
      fetch("/api/visitor-auth/me", { cache: "no-store" }).then((r) => r.json()),
    ])
      .then(([visitorData]) => {
        if (cancelled) return;
        setIsAuthed(Boolean(visitorData?.account));
        setAuthChecked(true);
      })
      .catch(() => {
        if (cancelled) return;
        setAuthChecked(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  async function send() {
    const trimmed = body.trim();
    if (trimmed.length < 2) {
      setErr("Napišite poruku.");
      return;
    }
    setBusy(true);
    setErr(null);
    try {
      const res = await fetch("/api/messages/start", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          recipientType: recipient.type,
          recipientId: recipient.id,
          body: trimmed,
          contextEntityType: context?.entityType,
          contextEntityId: context?.entityId,
          contextTitle: context?.title,
          contextPath: context?.path,
          contextImageUrl: context?.imageUrl,
        }),
      });
      const data = (await res.json().catch(() => ({}))) as {
        conversationId?: string;
        error?: string;
      };
      if (!res.ok) throw new Error(data?.error || "Slanje nije uspelo.");
      if (data.conversationId) {
        router.push(`/nalog/poruke/${data.conversationId}`);
      } else {
        setOpen(false);
      }
    } catch (caught) {
      setErr(caught instanceof Error ? caught.message : "Slanje nije uspelo.");
    } finally {
      setBusy(false);
    }
  }

  // Default styles (primary).
  const baseCls =
    variant === "ghost"
      ? "inline-flex h-10 items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-4 text-sm font-semibold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c]"
      : "inline-flex h-10 items-center gap-2 rounded-xl bg-[#c2410c] px-4 text-sm font-bold text-white transition hover:bg-[#d94e22] active:scale-[0.97]";

  // Anonymous → redirect to login with return path.
  if (authChecked && !isAuthed) {
    return (
      <Link
        href={`/prijavi-se?redirectTo=${encodeURIComponent(returnPath)}`}
        className={className || baseCls}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
        {label}
      </Link>
    );
  }

  return (
    <div className="relative inline-block">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={className || baseCls}
        aria-expanded={open}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
        {label}
      </button>

      {open && (
        <>
          <button
            aria-hidden="true"
            tabIndex={-1}
            type="button"
            className="fixed inset-0 z-30 cursor-default"
            onClick={() => setOpen(false)}
          />
          <div
            role="dialog"
            className="absolute right-0 top-full z-40 mt-2 w-[340px] overflow-hidden rounded-2xl border border-[#ede8e3] bg-white p-5 shadow-[0_24px_60px_rgba(12,24,40,0.18)]"
          >
            <p className="text-[0.65rem] font-bold uppercase tracking-[0.12em] text-[#9ca3af]">
              Nova poruka
            </p>
            {context?.title && (
              <p className="mt-1 line-clamp-2 text-sm font-bold text-[#0c1828]">
                O temi: {context.title}
              </p>
            )}
            <textarea
              rows={4}
              autoFocus
              value={body}
              onChange={(e) => setBody(e.target.value)}
              placeholder="Zdravo, zainteresovan/a sam za ovaj oglas..."
              className="mt-3 w-full resize-none rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-3 py-2 text-sm outline-none transition focus:border-[#c2410c]/40 focus:bg-white focus:ring-2 focus:ring-[#c2410c]/15"
            />
            {err && (
              <p className="mt-2 rounded-lg bg-red-50 px-3 py-2 text-xs font-semibold text-red-700 border border-red-200">
                {err}
              </p>
            )}
            <div className="mt-3 flex items-center gap-2">
              <button
                type="button"
                onClick={send}
                disabled={busy}
                className="inline-flex items-center gap-1.5 rounded-xl bg-[#c2410c] px-4 py-2 text-xs font-bold text-white transition hover:bg-[#d94e22] disabled:opacity-60"
              >
                {busy ? "Šaljem..." : "Pošalji"}
              </button>
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="text-xs font-semibold text-[#9ca3af] hover:text-[#0c1828]"
              >
                Otkaži
              </button>
            </div>
            <p className="mt-3 text-[0.65rem] leading-snug text-[#9ca3af]">
              Razgovor će se voditi unutar BiznisPortal-a, dobijaš obaveštenje na e-mail za
              svaki odgovor.
            </p>
          </div>
        </>
      )}
    </div>
  );
}
