"use client";

import { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import {
  Megaphone,
  Plus,
  Trash2,
  Edit3,
  Loader2,
  Eye,
  EyeOff,
  X,
  Save,
  AlertCircle,
  ToggleLeft,
  ToggleRight,
  ImageIcon,
  MousePointerClick,
  TrendingUp,
} from "lucide-react";
import { cn } from "@/lib/utils";
import ImageUpload from "@/components/admin/ImageUpload";
import { resolveUploadUrl } from "@/lib/uploadUrl";
import { getAdminToken } from "@/lib/adminAuth";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";

const SLOT_OPTIONS = [
  { value: "leaderboard-top",  label: "Top Leaderboard",      size: "970×90",  desc: "Between navbar and hero" },
  { value: "between-popular",  label: "After Popular Cars",   size: "728×90",  desc: "Section divider ad" },
  { value: "between-electric", label: "After Electric Cars",  size: "728×90",  desc: "Section divider ad" },
  { value: "between-news",     label: "After News Section",   size: "728×90",  desc: "Below latest news" },
  { value: "sidebar-right",    label: "Desktop Sidebar",      size: "300×600", desc: "Sticky right sidebar on listing pages" },
  { value: "article-inline",   label: "Article Inline",       size: "468×60",  desc: "Inserted every 3 paragraphs in blogs/news" },
];

interface AdSlot {
  id: string;
  slot: string;
  title?: string;
  description?: string;
  image?: string;
  imageMobile?: string;
  thumbnailImage?: string;
  targetUrl?: string;
  altText?: string;
  active: boolean;
  priority?: number;
  startDate?: string;
  endDate?: string;
  createdAt?: string;
  // Analytics
  views?:  number;
  clicks?: number;
  ctr?:    number;
}

interface AdAnalyticsSummary {
  totalViews:  number;
  totalClicks: number;
  overallCtr:  number;
}

const EMPTY: Partial<AdSlot> = {
  slot: "leaderboard-top",
  title: "",
  description: "",
  image: "",
  imageMobile: "",
  thumbnailImage: "",
  targetUrl: "",
  altText: "",
  active: true,
  priority: 0,
  startDate: "",
  endDate: "",
};

async function apiFetch(path: string, opts: RequestInit = {}) {
  const token = getAdminToken();
  const res = await fetch(`${API}${path}`, {
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...((opts.headers as Record<string, string>) || {}),
    },
    ...opts,
  });
  if (!res.ok) throw new Error(await res.text());
  if (res.status === 204) return null;
  return res.json();
}

// ── Modal ──────────────────────────────────────────────────────────────────────

function AdModal({
  initial,
  onSave,
  onClose,
}: {
  initial: Partial<AdSlot>;
  onSave: (data: Partial<AdSlot>) => Promise<void>;
  onClose: () => void;
}) {
  const [form,    setForm]    = useState<Partial<AdSlot>>(initial);
  const [saving,  setSaving]  = useState(false);
  const [error,   setError]   = useState("");

  const set = (k: keyof AdSlot, v: string | boolean | number) =>
    setForm((f) => ({ ...f, [k]: v }));

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.slot) { setError("Slot is required"); return; }
    setSaving(true); setError("");
    try   { await onSave(form); onClose(); }
    catch (err: unknown) { setError(err instanceof Error ? err.message : "Save failed"); }
    finally { setSaving(false); }
  }

  const selectedSlot = SLOT_OPTIONS.find((s) => s.value === form.slot);

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4 pt-[env(safe-area-inset-top,0px)] pb-[env(safe-area-inset-bottom,0px)] bg-black/50 backdrop-blur-sm">
      <div className="bg-white rounded-t-3xl sm:rounded-3xl w-full max-w-xl max-h-[min(100dvh,100%)] shadow-2xl overflow-hidden flex flex-col min-w-0">
        {/* Header */}
        <div className="flex items-center justify-between gap-3 px-4 sm:px-6 py-4 border-b border-gray-100 shrink-0 min-w-0">
          <h2 className="text-base font-black text-gray-900 min-w-0 truncate">
            {initial.id ? "Edit Ad" : "Create Ad"}
          </h2>
          <button onClick={onClose} className="p-2.5 min-h-11 min-w-11 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors shrink-0" aria-label="Close">
            <X className="w-4 h-4 text-gray-500" />
          </button>
        </div>

        <form onSubmit={submit} className="p-4 sm:p-6 space-y-5 overflow-y-auto overscroll-contain flex-1 min-h-0 max-h-[min(80vh,calc(100dvh-5rem))]">
          {error && (
            <div className="flex items-start gap-2 bg-red-50 border border-red-200 rounded-xl px-3 py-2.5 text-sm text-red-700 min-w-0">
              <AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
              <span className="min-w-0 break-words">{error}</span>
            </div>
          )}

          {/* Slot selector */}
          <div>
            <label className="text-xs font-bold text-gray-600 mb-1 block">Ad Slot *</label>
            <select
              value={form.slot || "leaderboard-top"}
              onChange={(e) => set("slot", e.target.value)}
              className="w-full min-w-0 px-3 py-2.5 min-h-11 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400"
            >
              {SLOT_OPTIONS.map((s) => (
                <option key={s.value} value={s.value}>{s.label} ({s.size})</option>
              ))}
            </select>
            {selectedSlot && <p className="text-xs text-gray-400 mt-1">{selectedSlot.desc}</p>}
          </div>

          {/* Title & Description */}
          <TxtField label="Title" value={form.title || ""}
            onChange={(v) => set("title", v)} placeholder="e.g. Summer Sale — Hyundai" />
          <TxtField label="Description" value={form.description || ""}
            onChange={(v) => set("description", v)}
            placeholder="Short tagline shown on hover preview" />

          {/* Desktop image */}
          <ImageUpload
            label="Desktop Ad Image"
            value={form.image || ""}
            category="ad"
            variant="desktop"
            aspectRatio="970/250"
            onChange={(r) => setForm((f) => ({
              ...f,
              image:          r.desktopUrl,
              imageMobile:    f.imageMobile || r.mobileUrl,
              thumbnailImage: r.thumbnailUrl,
            }))}
            onClear={() => setForm((f) => ({ ...f, image: "", thumbnailImage: "" }))}
          />

          {/* Mobile image */}
          <ImageUpload
            label="Mobile Ad Image (optional — auto-generated if blank)"
            value={form.imageMobile || ""}
            category="ad"
            variant="mobile"
            aspectRatio="4/1"
            onChange={(r) => set("imageMobile", r.mobileUrl)}
            onClear={() => set("imageMobile", "")}
          />

          {/* Target URL */}
          <TxtField label="Click URL" value={form.targetUrl || ""}
            onChange={(v) => set("targetUrl", v)}
            placeholder="https://advertiser.com/landing-page" />

          {/* Alt text */}
          <TxtField label="Alt Text (accessibility)" value={form.altText || ""}
            onChange={(v) => set("altText", v)} placeholder="Advertisement" />

          {/* Priority */}
          <div>
            <label className="text-xs font-bold text-gray-600 mb-1 block">Priority (lower = higher priority)</label>
            <input type="number" value={form.priority ?? 0}
              onChange={(e) => set("priority", parseInt(e.target.value) || 0)}
              className="w-full min-w-0 px-3 py-2.5 min-h-11 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400"
            />
          </div>

          {/* Date range */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 min-w-0">
            <div className="min-w-0">
              <label className="text-xs font-bold text-gray-600 mb-1 block">Start Date</label>
              <input type="date" value={form.startDate || ""}
                onChange={(e) => set("startDate", e.target.value)}
                className="w-full min-w-0 max-w-full px-3 py-2.5 min-h-11 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400"
              />
            </div>
            <div className="min-w-0">
              <label className="text-xs font-bold text-gray-600 mb-1 block">End Date</label>
              <input type="date" value={form.endDate || ""}
                onChange={(e) => set("endDate", e.target.value)}
                className="w-full min-w-0 max-w-full px-3 py-2.5 min-h-11 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400"
              />
            </div>
          </div>

          {/* Active toggle */}
          <div className="min-w-0">
            <label className="text-xs font-bold text-gray-600 mb-1 block">Status</label>
            <button type="button" onClick={() => set("active", !form.active)}
              className={cn(
                "flex items-center gap-2 px-3 py-2.5 min-h-11 w-full sm:w-auto rounded-xl text-sm font-semibold border transition-colors text-left min-w-0",
                form.active
                  ? "border-green-200 bg-green-50 text-green-700"
                  : "border-gray-200 bg-gray-50 text-gray-500"
              )}
            >
              {form.active ? <ToggleRight className="w-4 h-4 shrink-0" /> : <ToggleLeft className="w-4 h-4 shrink-0" />}
              <span className="min-w-0 break-words">{form.active ? "Active — will show on site" : "Inactive — hidden from site"}</span>
            </button>
          </div>

          <div className="flex flex-col-reverse sm:flex-row gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 py-2.5 min-h-11 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-50 transition-colors"
            >Cancel</button>
            <button type="submit" disabled={saving}
              className="flex-1 py-2.5 min-h-11 rounded-xl bg-gradient-to-r from-orange-500 to-pink-500 text-white text-sm font-black hover:opacity-90 disabled:opacity-50 transition-all flex items-center justify-center gap-2"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              {saving ? "Saving…" : "Save Ad"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function TxtField({ label, value, onChange, placeholder }: {
  label: string; value: string;
  onChange: (v: string) => void; placeholder?: string;
}) {
  return (
    <div>
      <label className="text-xs font-bold text-gray-600 mb-1 block">{label}</label>
      <input type="text" value={value} onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="w-full min-w-0 px-3 py-2.5 min-h-11 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400 placeholder-gray-300"
      />
    </div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────────────

export default function AdminAdsPage() {
  const [ads,       setAds]       = useState<AdSlot[]>([]);
  const [analytics, setAnalytics] = useState<AdAnalyticsSummary | null>(null);
  const [loading,   setLoading]   = useState(true);
  const [modal,     setModal]     = useState<Partial<AdSlot> | null>(null);
  const [toast,     setToast]     = useState("");

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(""), 3000); };

  const load = useCallback(async () => {
    try {
      const [list, stats] = await Promise.all([
        apiFetch("/api/ads"),
        apiFetch("/api/ads/analytics").catch(() => null),
      ]);
      setAds(list.ads || []);
      if (stats) {
        const statsMap: Record<string, Pick<AdSlot, "views" | "clicks" | "ctr">> = {};
        for (const a of (stats.ads || [])) statsMap[a.id] = { views: a.views, clicks: a.clicks, ctr: a.ctr };
        setAds((prev) => prev.map((a) => ({ ...a, ...statsMap[a.id] })));
        setAnalytics({ totalViews: stats.totalViews, totalClicks: stats.totalClicks, overallCtr: stats.overallCtr });
      }
    } catch { showToast("Failed to load ad slots"); }
    finally { setLoading(false); }
  }, []);

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

  async function handleSave(form: Partial<AdSlot>) {
    if (form.id) {
      await apiFetch(`/api/ads/${form.id}`, { method: "PATCH", body: JSON.stringify(form) });
      showToast("Ad updated");
    } else {
      await apiFetch("/api/ads", { method: "POST", body: JSON.stringify(form) });
      showToast("Ad created");
    }
    await load();
  }

  async function toggleActive(ad: AdSlot) {
    await apiFetch(`/api/ads/${ad.id}/toggle`, { method: "PATCH" });
    showToast(`Ad ${ad.active ? "deactivated" : "activated"}`);
    await load();
  }

  async function deleteAd(id: string) {
    if (!confirm("Delete this ad permanently?")) return;
    await apiFetch(`/api/ads/${id}`, { method: "DELETE" });
    showToast("Ad deleted");
    await load();
  }

  const slotInfo = (slot: string) =>
    SLOT_OPTIONS.find((s) => s.value === slot) || { label: slot, size: "", desc: "" };

  return (
    <div className="p-4 sm:p-6 max-w-4xl mx-auto min-w-0 overflow-x-hidden pb-[env(safe-area-inset-bottom,0px)]">
      {toast && (
        <div className="fixed top-[max(1.5rem,env(safe-area-inset-top,0px))] left-4 right-4 sm:left-auto sm:right-6 z-50 max-w-sm ml-auto bg-gray-900 text-white text-sm font-semibold px-5 py-3 rounded-2xl shadow-xl animate-fade-in break-words">
          {toast}
        </div>
      )}

      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6 min-w-0">
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-10 h-10 rounded-2xl bg-gradient-to-br from-orange-500 to-pink-500 flex items-center justify-center shrink-0">
            <Megaphone className="w-5 h-5 text-white" />
          </div>
          <div className="min-w-0">
            <h1 className="text-xl font-black text-gray-900 truncate">Advertisement Manager</h1>
            <p className="text-sm text-gray-500">Upload images · set schedules · manage placements</p>
          </div>
        </div>
        <button onClick={() => setModal(EMPTY)}
          className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-11 w-full sm:w-auto bg-gradient-to-r from-orange-500 to-pink-500 text-white text-sm font-black rounded-2xl hover:opacity-90 transition-all shadow-md shrink-0"
        >
          <Plus className="w-4 h-4" /> Add Ad
        </button>
      </div>

      {/* Analytics summary strip */}
      {analytics && (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4 min-w-0">
          {[
            { icon: Eye,               label: "Impressions", val: analytics.totalViews.toLocaleString(),  color: "text-orange-600",  bg: "bg-orange-50"  },
            { icon: MousePointerClick, label: "Clicks",      val: analytics.totalClicks.toLocaleString(), color: "text-green-600",   bg: "bg-green-50"   },
            { icon: TrendingUp,        label: "Overall CTR", val: `${analytics.overallCtr}%`,             color: "text-violet-600",  bg: "bg-violet-50"  },
          ].map(({ icon: Icon, label, val, color, bg }) => (
            <div key={label} className="rounded-2xl border border-gray-100 p-3 flex items-center gap-3 bg-white shadow-sm min-w-0">
              <div className={cn("w-9 h-9 rounded-xl flex items-center justify-center shrink-0", bg)}>
                <Icon className={cn("w-4 h-4", color)} />
              </div>
              <div className="min-w-0">
                <p className="text-[10px] text-gray-400 font-semibold uppercase tracking-wide truncate">{label}</p>
                <p className={cn("text-lg font-black truncate", color)}>{val}</p>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Slot reference */}
      <div className="grid grid-cols-1 min-[360px]:grid-cols-2 md:grid-cols-3 gap-2 mb-6 min-w-0">
        {SLOT_OPTIONS.map((s) => (
          <div key={s.value} className="bg-gray-50 border border-gray-100 rounded-xl px-3 py-2.5 min-w-0">
            <p className="text-xs font-bold text-gray-700 break-words">{s.label}</p>
            <p className="text-[10px] text-gray-400 mt-0.5 break-words">{s.size} — {s.desc}</p>
          </div>
        ))}
      </div>

      {/* List */}
      {loading ? (
        <div className="flex items-center justify-center h-40">
          <Loader2 className="w-6 h-6 text-orange-500 animate-spin" />
        </div>
      ) : ads.length === 0 ? (
        <div className="text-center py-16 px-4 bg-white rounded-3xl border border-gray-100 min-w-0">
          <Megaphone className="w-10 h-10 mx-auto mb-3 text-gray-200" />
          <p className="font-bold text-gray-500">No ads configured</p>
          <p className="text-sm text-gray-400 mt-1 break-words">
            Create ad slots to start monetizing. Placeholders show automatically until ads are live.
          </p>
          <button onClick={() => setModal(EMPTY)}
            className="mt-4 inline-flex items-center justify-center gap-2 px-4 py-2.5 min-h-11 bg-orange-50 text-orange-600 text-sm font-bold rounded-xl hover:bg-orange-100 transition-colors"
          >
            <Plus className="w-4 h-4" /> Create First Ad
          </button>
        </div>
      ) : (
        <div className="space-y-3">
          {ads.map((ad) => {
            const info = slotInfo(ad.slot);
            const thumb = ad.thumbnailImage || ad.image;
            return (
              <div key={ad.id} className={cn(
                "bg-white rounded-2xl border p-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4 transition-all min-w-0",
                ad.active ? "border-gray-100 shadow-sm" : "border-gray-100 opacity-60"
              )}>
                {/* Thumbnail */}
                <div className="w-full max-w-[5rem] h-12 sm:w-20 rounded-xl overflow-hidden bg-gray-50 border border-gray-100 shrink-0 flex items-center justify-center">
                  {thumb ? (
                    <Image src={resolveUploadUrl(thumb)} alt={ad.title || ad.slot} width={80} height={48}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <ImageIcon className="w-5 h-5 text-gray-300" />
                  )}
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap min-w-0">
                    <p className="text-sm font-bold text-gray-900 truncate max-w-full">
                      {ad.title || info.label}
                    </p>
                    <span className="text-[10px] font-black bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full shrink-0">
                      {info.size}
                    </span>
                    <span className={cn(
                      "text-[10px] font-black px-2 py-0.5 rounded-full shrink-0",
                      ad.active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500"
                    )}>
                      {ad.active ? "ACTIVE" : "INACTIVE"}
                    </span>
                    {!ad.image && (
                      <span className="text-[10px] font-semibold bg-amber-50 text-amber-600 px-2 py-0.5 rounded-full shrink-0">
                        placeholder
                      </span>
                    )}
                    {ad.imageMobile && (
                      <span className="text-[10px] font-semibold bg-emerald-50 text-emerald-600 px-2 py-0.5 rounded-full shrink-0">
                        mobile ✓
                      </span>
                    )}
                    {(ad.views !== undefined) && (
                      <>
                        <span className="text-[10px] text-orange-600 bg-orange-50 px-1.5 py-0.5 rounded font-semibold shrink-0">
                          👁 {(ad.views || 0).toLocaleString()}
                        </span>
                        <span className="text-[10px] text-green-600 bg-green-50 px-1.5 py-0.5 rounded font-semibold shrink-0">
                          🖱 {(ad.clicks || 0).toLocaleString()}
                        </span>
                        <span className="text-[10px] text-violet-600 bg-violet-50 px-1.5 py-0.5 rounded font-semibold shrink-0">
                          CTR {ad.ctr ?? 0}%
                        </span>
                      </>
                    )}
                  </div>
                  <p className="text-[10px] text-gray-400 mt-0.5 font-mono truncate">{ad.slot}</p>
                  {ad.targetUrl && <p className="text-xs text-blue-500 truncate mt-0.5">{ad.targetUrl}</p>}
                  {(ad.startDate || ad.endDate) && (
                    <p className="text-[10px] text-gray-400 mt-0.5 break-words">
                      {ad.startDate && `From: ${ad.startDate}`}
                      {ad.startDate && ad.endDate && " · "}
                      {ad.endDate && `Until: ${ad.endDate}`}
                    </p>
                  )}
                </div>

                <div className="flex items-center gap-1 shrink-0 self-end sm:self-auto">
                  <button onClick={() => toggleActive(ad)} title={ad.active ? "Deactivate" : "Activate"}
                    className="p-2.5 min-h-11 min-w-11 flex items-center justify-center rounded-xl hover:bg-gray-100 transition-colors">
                    {ad.active ? <Eye className="w-4 h-4 text-green-600" /> : <EyeOff className="w-4 h-4 text-gray-400" />}
                  </button>
                  <button onClick={() => setModal(ad)} title="Edit"
                    className="p-2.5 min-h-11 min-w-11 flex items-center justify-center rounded-xl hover:bg-blue-50 transition-colors">
                    <Edit3 className="w-4 h-4 text-blue-600" />
                  </button>
                  <button onClick={() => deleteAd(ad.id)} title="Delete"
                    className="p-2.5 min-h-11 min-w-11 flex items-center justify-center rounded-xl hover:bg-red-50 transition-colors">
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {modal !== null && (
        <AdModal initial={modal} onSave={handleSave} onClose={() => setModal(null)} />
      )}
    </div>
  );
}
