"use client";

import { useState, useTransition } from "react";

import type { OutreachType, OutreachStatus } from "@prisma/client";

interface AudienceCompany {
  id: string;
  name: string;
  email: string;
  cityName: string | null;
  industryName: string | null;
  healthScore: number | null;
  isVerified: boolean;
}

interface CampaignData {
  id: string;
  name: string;
  type: OutreachType;
  subjectTemplate: string;
  bodyTemplate: string;
  bodyTextTemplate: string;
  audienceFilter: unknown;
  status: OutreachStatus;
}

interface Props {
  campaign: CampaignData;
  audience: AudienceCompany[];
}

export function OutreachCampaignEditor({ campaign, audience }: Props) {
  const [isPending, startTransition] = useTransition();
  const [name, setName] = useState(campaign.name);
  const [subject, setSubject] = useState(campaign.subjectTemplate);
  const [bodyText, setBodyText] = useState(campaign.bodyTextTemplate);
  const [savedMsg, setSavedMsg] = useState<string | null>(null);
  const [sendResult, setSendResult] = useState<string | null>(null);

  function saveTemplate() {
    setSavedMsg(null);
    startTransition(async () => {
      try {
        const res = await fetch(`/api/admin/outreach/${campaign.id}/save`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name, subject, bodyText }),
        });
        if (!res.ok) throw new Error("Greška pri čuvanju");
        setSavedMsg("✓ Sačuvano");
        setTimeout(() => setSavedMsg(null), 2000);
      } catch (err) {
        setSavedMsg(err instanceof Error ? err.message : "Greška");
      }
    });
  }

  function previewEmail() {
    if (audience.length === 0) return;
    const first = audience[0];
    const cityLine = first.cityName ? ` iz ${first.cityName}` : "";
    const rendered = bodyText
      .replace(/\{firmName\}/g, first.name)
      .replace(/\{cityLine\}/g, cityLine)
      .replace(/\{magicLink\}/g, "https://biznisportal.rs/owner-login/MAGIC_LINK_PREVIEW")
      .replace(/\{awardTitle\}/g, "Top kategorija 2026")
      .replace(/\{articleTitle\}/g, "Top firme 2026");
    alert(`SUBJECT:\n${subject.replace(/\{firmName\}/g, first.name).replace(/\{cityLine\}/g, cityLine)}\n\nBODY:\n${rendered}`);
  }

  function sendCampaign() {
    if (!confirm(`Šaljete email-ove za ${audience.length} firmi. Nastaviti?`)) return;
    setSendResult(null);
    startTransition(async () => {
      try {
        const res = await fetch(`/api/admin/outreach/${campaign.id}/send`, {
          method: "POST",
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Greška");
        setSendResult(`✓ Poslato ${data.sent} · Neuspešno ${data.failed} · Skip ${data.skipped}`);
        setTimeout(() => window.location.reload(), 2500);
      } catch (err) {
        setSendResult(err instanceof Error ? err.message : "Greška pri slanju");
      }
    });
  }

  function downloadCsv() {
    const link = document.createElement("a");
    link.href = `/api/admin/outreach/${campaign.id}/export`;
    link.download = "";
    link.click();
  }

  return (
    <>
      {/* Template editor */}
      <section className="surface rounded-[2rem] p-5">
        <h2 className="admin-panel-heading">Template editor</h2>
        <p className="admin-panel-subtitle mt-1">
          Placeholder-i: <code>{"{firmName}"}</code>, <code>{"{cityLine}"}</code>,{" "}
          <code>{"{magicLink}"}</code>, <code>{"{awardTitle}"}</code>,{" "}
          <code>{"{articleTitle}"}</code>
        </p>
        <div className="mt-4 grid gap-3">
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Naziv kampanje
            </span>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="mt-1 w-full rounded-lg border border-border bg-white px-3 py-2 text-sm"
            />
          </label>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Subject template
            </span>
            <input
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              className="mt-1 w-full rounded-lg border border-border bg-white px-3 py-2 text-sm font-mono"
            />
          </label>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Body text (plain text — HTML verzija se ne menja iz UI)
            </span>
            <textarea
              value={bodyText}
              onChange={(e) => setBodyText(e.target.value)}
              rows={12}
              className="mt-1 w-full rounded-lg border border-border bg-white px-3 py-2 text-xs font-mono"
            />
          </label>
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={saveTemplate}
              disabled={isPending}
              className="rounded-lg bg-foreground px-5 py-2 text-sm font-bold text-white disabled:opacity-50"
            >
              {isPending ? "Čuvam…" : "💾 Sačuvaj template"}
            </button>
            <button
              type="button"
              onClick={previewEmail}
              className="rounded-lg border border-border bg-white px-5 py-2 text-sm font-bold text-foreground"
            >
              👁 Preview (prva firma)
            </button>
            {savedMsg ? (
              <span className="text-xs text-emerald-700">{savedMsg}</span>
            ) : null}
          </div>
        </div>
      </section>

      {/* Audience preview */}
      <section className="surface rounded-[2rem] p-5">
        <div className="flex items-center justify-between gap-3">
          <h2 className="admin-panel-heading">Audience ({audience.length})</h2>
          <button
            type="button"
            onClick={downloadCsv}
            className="rounded-lg border border-border bg-white px-4 py-2 text-xs font-bold text-foreground hover:border-[#c2410c]"
          >
            📊 Download CSV
          </button>
        </div>
        <p className="admin-panel-subtitle mt-1">
          Filteri se mogu menjati u Audience Filter sekciji ispod.
        </p>
        {audience.length === 0 ? (
          <p className="mt-4 text-sm text-muted-foreground">
            Nema firmi za ovaj filter.
          </p>
        ) : (
          <div className="mt-4 max-h-[400px] overflow-y-auto">
            <table className="admin-data-table w-full">
              <thead>
                <tr>
                  <th>Firma</th>
                  <th>Email</th>
                  <th>Grad</th>
                  <th>Industrija</th>
                  <th className="text-right">Health</th>
                </tr>
              </thead>
              <tbody>
                {audience.slice(0, 50).map((c) => (
                  <tr key={c.id}>
                    <td className="text-xs">
                      <strong>{c.name}</strong>
                      {c.isVerified ? <span className="ml-1 text-emerald-600">✓</span> : null}
                    </td>
                    <td className="text-xs">{c.email}</td>
                    <td className="text-xs">{c.cityName ?? "—"}</td>
                    <td className="text-xs">{c.industryName ?? "—"}</td>
                    <td className="text-right text-xs tabular-nums">{c.healthScore ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            {audience.length > 50 ? (
              <p className="mt-3 text-center text-xs text-muted-foreground">
                Prikazano prvih 50 od {audience.length}. CSV export sadrži sve.
              </p>
            ) : null}
          </div>
        )}
      </section>

      {/* Send bulk */}
      <section className="surface rounded-[2rem] border-2 border-[#c2410c]/30 bg-gradient-to-br from-[#fff4f0] to-white p-6">
        <h2 className="admin-panel-heading">📨 Pošalji kampanju</h2>
        <p className="admin-panel-subtitle mt-1">
          Šaljemo <strong>{audience.length}</strong> personalizovanih email-ova
          sa magic linkovima. Status: <strong>{campaign.status}</strong>.
        </p>
        <div className="mt-5 flex items-center gap-3">
          <button
            type="button"
            onClick={sendCampaign}
            disabled={isPending || campaign.status === "SENDING" || audience.length === 0}
            className="rounded-xl bg-[#c2410c] px-6 py-3 text-sm font-bold text-white hover:bg-[#c8421f] disabled:opacity-50"
          >
            {isPending ? "Šaljem…" : `🚀 Pošalji svim (${audience.length})`}
          </button>
          {sendResult ? (
            <span className="text-sm font-semibold text-emerald-700">{sendResult}</span>
          ) : null}
        </div>
        <p className="mt-3 text-[0.7rem] text-muted-foreground">
          ⚠️ Trenutno nema undo. Svaki primljeni email kreira OwnerLoginToken
          (30 dana važenja).
        </p>
      </section>
    </>
  );
}
