// @File: src/pages/admin/cms/CmsVisitorCampaigns.tsx
// @Desc: Campaigns + referral-links admin page. Admin can create/edit/pause/
//        delete campaigns and copy each campaign's referral URL.
import { FormEvent, useCallback, useEffect, useState } from "react";
import {
  Check,
  Copy,
  Edit3,
  Loader2,
  Megaphone,
  Pause,
  Play,
  Plus,
  RefreshCw,
  Trash2,
  X,
} from "lucide-react";
import CmsLayout from "./CmsLayout";
import { Badge, Field, PageHeader, SectionCard, Select, TextArea, TextInput } from "./ui";
import {
  vmCreateCampaign,
  vmDeleteCampaign,
  vmListCampaigns,
  vmUpdateCampaign,
  type VmCampaignItem,
  type VmCampaignPayload,
} from "@/lib/adminApi";

const EMPTY_FORM: VmCampaignPayload = {
  name: "",
  utm_source: "",
  utm_medium: "",
  utm_campaign: "",
  utm_term: "",
  utm_content: "",
  landing_page: "/",
  target_url: "",
  status: "active",
  notes: "",
};

function StatusBadge({ status }: { status: string }) {
  if (status === "active") return <Badge tone="green">Active</Badge>;
  if (status === "paused") return <Badge tone="yellow">Paused</Badge>;
  return <Badge tone="slate">Archived</Badge>;
}

export default function CmsVisitorCampaigns() {
  const [items, setItems] = useState<VmCampaignItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busyId, setBusyId] = useState<number | null>(null);
  const [copiedId, setCopiedId] = useState<number | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<VmCampaignItem | null>(null);
  const [form, setForm] = useState<VmCampaignPayload>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await vmListCampaigns();
      setItems(list);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load campaigns");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY_FORM);
    setDialogOpen(true);
  };

  const openEdit = (item: VmCampaignItem) => {
    setEditing(item);
    setForm({
      name: item.name,
      utm_source: item.utm_source,
      utm_medium: item.utm_medium ?? "",
      utm_campaign: item.utm_campaign,
      utm_term: item.utm_term ?? "",
      utm_content: item.utm_content ?? "",
      landing_page: item.landing_page,
      target_url: item.target_url ?? "",
      start_date: item.start_date ?? "",
      end_date: item.end_date ?? "",
      status: (item.status as "active" | "paused" | "archived") || "active",
      notes: item.notes ?? "",
    });
    setDialogOpen(true);
  };

  const closeDialog = () => {
    setDialogOpen(false);
    setEditing(null);
    setForm(EMPTY_FORM);
  };

  const setField = <K extends keyof VmCampaignPayload>(key: K, value: VmCampaignPayload[K]) => {
    setForm((prev) => ({ ...prev, [key]: value }));
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    try {
      const payload: VmCampaignPayload = {
        ...form,
        utm_medium: form.utm_medium || null,
        utm_term: form.utm_term || null,
        utm_content: form.utm_content || null,
        target_url: form.target_url || null,
        notes: form.notes || null,
        start_date: form.start_date || null,
        end_date: form.end_date || null,
      };
      if (editing) {
        await vmUpdateCampaign(editing.id, payload);
      } else {
        await vmCreateCampaign(payload);
      }
      closeDialog();
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const togglePause = async (item: VmCampaignItem) => {
    setBusyId(item.id);
    try {
      await vmUpdateCampaign(item.id, {
        status: item.status === "active" ? "paused" : "active",
      });
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Update failed");
    } finally {
      setBusyId(null);
    }
  };

  const doDelete = async (item: VmCampaignItem) => {
    if (!window.confirm(`Delete campaign "${item.name}"?`)) return;
    setBusyId(item.id);
    try {
      await vmDeleteCampaign(item.id);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Delete failed");
    } finally {
      setBusyId(null);
    }
  };

  const copyUrl = async (item: VmCampaignItem) => {
    try {
      await navigator.clipboard.writeText(item.referral_url);
      setCopiedId(item.id);
      setTimeout(() => setCopiedId((cur) => (cur === item.id ? null : cur)), 1500);
    } catch {
      /* ignore */
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        title="Campaigns"
        description="Generate referral URLs with UTM parameters and track clicks, signups, and orders."
        icon={<Megaphone className="w-6 h-6" />}
      />

      <SectionCard
        title="All campaigns"
        actions={
          <div className="flex items-center gap-2">
            <button
              onClick={() => void load()}
              className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-300 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-50 transition"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
              Refresh
            </button>
            <button
              onClick={openCreate}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-bold hover:bg-[#0a8048] transition"
            >
              <Plus className="w-4 h-4" />
              New Campaign
            </button>
          </div>
        }
      >
        {error && (
          <div className="p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
            {error}
          </div>
        )}

        <div className="overflow-x-auto -mx-5 md:-mx-6">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-left text-[11px] uppercase tracking-wider text-slate-500">
              <tr>
                <th className="px-4 py-3">Campaign</th>
                <th className="px-4 py-3">Source / Medium</th>
                <th className="px-4 py-3">Clicks</th>
                <th className="px-4 py-3">Unique</th>
                <th className="px-4 py-3">Conversions</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Referral URL</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {items.length === 0 && !loading && (
                <tr>
                  <td colSpan={8} className="px-4 py-10 text-center text-slate-500">
                    No campaigns yet. Click <span className="font-semibold">New Campaign</span> to create one.
                  </td>
                </tr>
              )}
              {items.map((item) => (
                <tr key={item.id} className="border-t border-slate-100 align-top">
                  <td className="px-4 py-3">
                    <div className="font-semibold text-slate-900">{item.name}</div>
                    <div className="text-[11px] text-slate-400">
                      Landing: <span className="font-mono">{item.landing_page}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-slate-700">{item.utm_source}</div>
                    <div className="text-[11px] text-slate-400">{item.utm_medium || "—"}</div>
                    <div className="text-[11px] text-slate-400">
                      utm_campaign=<span className="font-mono">{item.utm_campaign}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 font-semibold text-slate-900">{item.total_clicks}</td>
                  <td className="px-4 py-3 text-slate-700">{item.unique_visitors}</td>
                  <td className="px-4 py-3">
                    <div className="text-slate-700">{item.conversions}</div>
                    <div className="text-[11px] text-slate-400">
                      L{item.leads} · S{item.signups} · O{item.orders}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={item.status} />
                  </td>
                  <td className="px-4 py-3 max-w-[280px]">
                    <div className="flex items-center gap-2">
                      <code
                        className="flex-1 truncate text-[11px] bg-slate-50 border border-slate-200 px-2 py-1 rounded"
                        title={item.referral_url}
                      >
                        {item.referral_url}
                      </code>
                      <button
                        onClick={() => void copyUrl(item)}
                        className="shrink-0 p-1.5 rounded-md border border-slate-200 hover:bg-slate-100"
                        title="Copy URL"
                      >
                        {copiedId === item.id ? (
                          <Check className="w-3.5 h-3.5 text-emerald-600" />
                        ) : (
                          <Copy className="w-3.5 h-3.5 text-slate-500" />
                        )}
                      </button>
                    </div>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => void togglePause(item)}
                        disabled={busyId === item.id || item.status === "archived"}
                        className="p-1.5 rounded-md hover:bg-slate-100 text-slate-600 disabled:opacity-40"
                        title={item.status === "active" ? "Pause" : "Resume"}
                      >
                        {item.status === "active" ? (
                          <Pause className="w-4 h-4" />
                        ) : (
                          <Play className="w-4 h-4" />
                        )}
                      </button>
                      <button
                        onClick={() => openEdit(item)}
                        className="p-1.5 rounded-md hover:bg-slate-100 text-slate-600"
                        title="Edit"
                      >
                        <Edit3 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => void doDelete(item)}
                        disabled={busyId === item.id}
                        className="p-1.5 rounded-md hover:bg-red-50 text-red-500 disabled:opacity-40"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>

      {dialogOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4 overflow-y-auto">
          <form
            onSubmit={handleSubmit}
            className="bg-white rounded-2xl shadow-xl w-full max-w-2xl my-8"
          >
            <div className="flex items-center justify-between p-5 border-b border-slate-100">
              <div>
                <h3 className="text-lg font-bold text-slate-900">
                  {editing ? "Edit Campaign" : "New Campaign"}
                </h3>
                <p className="text-xs text-slate-500">
                  Generates a referral URL with UTM parameters.
                </p>
              </div>
              <button
                type="button"
                onClick={closeDialog}
                className="p-1.5 rounded-md hover:bg-slate-100 text-slate-500"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-5 grid grid-cols-1 md:grid-cols-2 gap-4 max-h-[70vh] overflow-y-auto">
              <div className="md:col-span-2">
                <Field label="Name" required>
                  <TextInput
                    required
                    value={form.name}
                    onChange={(e) => setField("name", e.target.value)}
                    placeholder="Cloud Hosting - Facebook Spring"
                  />
                </Field>
              </div>
              <Field label="utm_source" required>
                <TextInput
                  required
                  value={form.utm_source}
                  onChange={(e) => setField("utm_source", e.target.value)}
                  placeholder="facebook"
                />
              </Field>
              <Field label="utm_medium">
                <TextInput
                  value={form.utm_medium ?? ""}
                  onChange={(e) => setField("utm_medium", e.target.value)}
                  placeholder="paid"
                />
              </Field>
              <Field label="utm_campaign" required>
                <TextInput
                  required
                  value={form.utm_campaign}
                  onChange={(e) => setField("utm_campaign", e.target.value)}
                  placeholder="cloud-hosting"
                />
              </Field>
              <Field label="utm_term">
                <TextInput
                  value={form.utm_term ?? ""}
                  onChange={(e) => setField("utm_term", e.target.value)}
                  placeholder="cheap+hosting"
                />
              </Field>
              <Field label="utm_content">
                <TextInput
                  value={form.utm_content ?? ""}
                  onChange={(e) => setField("utm_content", e.target.value)}
                  placeholder="banner_a"
                />
              </Field>
              <Field label="Landing Page">
                <TextInput
                  value={form.landing_page ?? "/"}
                  onChange={(e) => setField("landing_page", e.target.value)}
                  placeholder="/cloud-hosting"
                />
              </Field>
              <Field label="Start Date">
                <TextInput
                  type="date"
                  value={(form.start_date ?? "").slice(0, 10)}
                  onChange={(e) => setField("start_date", e.target.value || null)}
                />
              </Field>
              <Field label="End Date">
                <TextInput
                  type="date"
                  value={(form.end_date ?? "").slice(0, 10)}
                  onChange={(e) => setField("end_date", e.target.value || null)}
                />
              </Field>
              <Field label="Status">
                <Select
                  value={form.status ?? "active"}
                  onChange={(e) =>
                    setField("status", e.target.value as "active" | "paused" | "archived")
                  }
                >
                  <option value="active">Active</option>
                  <option value="paused">Paused</option>
                  <option value="archived">Archived</option>
                </Select>
              </Field>
              <div className="md:col-span-2">
                <Field label="Target URL" hint="Optional external destination">
                  <TextInput
                    value={form.target_url ?? ""}
                    onChange={(e) => setField("target_url", e.target.value)}
                    placeholder="https://example.com/landing"
                  />
                </Field>
              </div>
              <div className="md:col-span-2">
                <Field label="Notes">
                  <TextArea
                    rows={3}
                    value={form.notes ?? ""}
                    onChange={(e) => setField("notes", e.target.value)}
                  />
                </Field>
              </div>
            </div>

            <div className="flex items-center justify-end gap-2 p-5 border-t border-slate-100">
              <button
                type="button"
                onClick={closeDialog}
                className="px-4 py-2 rounded-lg border border-slate-300 text-slate-700 text-sm font-semibold hover:bg-slate-50 transition"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className="px-5 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-bold hover:bg-[#0a8048] transition disabled:opacity-60 inline-flex items-center gap-2"
              >
                {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                {editing ? "Save changes" : "Create Campaign"}
              </button>
            </div>
          </form>
        </div>
      )}
    </CmsLayout>
  );
}