"use client";

import { useState, useTransition } from "react";

import type { CrmActivity } from "@prisma/client";
import { Spinner } from "@/components/common/Spinner";

const ACTIVITY_OPTIONS: Array<{ value: CrmActivity; label: string; icon: string }> = [
  { value: "NOTE", label: "Beleška", icon: "📝" },
  { value: "CALL", label: "Poziv", icon: "📞" },
  { value: "EMAIL", label: "Email", icon: "✉️" },
  { value: "MEETING", label: "Sastanak", icon: "🤝" },
  { value: "PROPOSAL_SENT", label: "Predračun", icon: "📄" },
  { value: "CONTRACT_SIGNED", label: "Ugovor", icon: "✅" },
  { value: "TASK", label: "Zadatak", icon: "☑️" },
];

export function PortalCrmCardActions({ cardId }: { cardId: string }) {
  const [isPending, startTransition] = useTransition();
  const [activity, setActivity] = useState<CrmActivity>("NOTE");
  const [content, setContent] = useState("");
  const [error, setError] = useState<string | null>(null);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (content.trim().length < 3) {
      setError("Beleška mora biti duža od 3 karaktera");
      return;
    }
    startTransition(async () => {
      try {
        const res = await fetch(`/api/portal/crm/${cardId}/note`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ content, activity }),
        });
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data.error || "Greška");
        }
        setContent("");
        window.location.reload();
      } catch (err) {
        setError(err instanceof Error ? err.message : "Greška pri čuvanju");
      }
    });
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="rounded-2xl border border-border bg-white p-4"
    >
      <div className="flex flex-wrap gap-2">
        {ACTIVITY_OPTIONS.map((opt) => (
          <button
            key={opt.value}
            type="button"
            onClick={() => setActivity(opt.value)}
            className={`rounded-full border px-3 py-1 text-xs font-semibold transition ${
              activity === opt.value
                ? "border-[#c2410c] bg-[#fff4f0] text-[#c2410c]"
                : "border-border bg-[#faf9f7] text-muted-foreground hover:border-[#c2410c]"
            }`}
          >
            {opt.icon} {opt.label}
          </button>
        ))}
      </div>
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        rows={3}
        placeholder="Dodaj belešku, npr. „Pozvao Marka, dogovorili predračun za utorak..."
        className="mt-3 w-full rounded-lg border border-border bg-[#faf9f7] px-3 py-2 text-sm focus:border-[#c2410c] focus:outline-none"
      />
      {error ? (
        <p className="mt-2 text-xs text-rose-700">{error}</p>
      ) : null}
      <div className="mt-3 flex items-center justify-end">
        <button
          type="submit"
          disabled={isPending || content.trim().length < 3}
          className="inline-flex items-center justify-center gap-2 rounded-lg bg-[#c2410c] px-4 py-2 text-xs font-bold text-white disabled:opacity-50"
        >
          {isPending ? <Spinner className="h-4 w-4" /> : null}
          {isPending ? "Čuvam…" : "Sačuvaj belešku"}
        </button>
      </div>
    </form>
  );
}
