"use client";

import { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import { Link2, Copy, Trash2, ImageIcon, Wand2, ExternalLink, Store } from "lucide-react";
import { api, auth } from "@/lib/api";
import { PageHeader, Card, Button, Input, FormField, EmptyState, Skeleton, Badge } from "@/components/ui";
import { useToast } from "@/components/toast";

type Info = { couponCode: string | null; referralLink: string | null };
type SavedLink = { url: string; tracked: string };
type Asset = { id: string; type: string; title: string; url: string; category: string | null };
type Brand = { campaignId: string | null; name: string; url: string; couponCode: string | null };

export default function MarketingPage() {
  const toast = useToast();
  const [info, setInfo] = useState<Info | null>(null);
  const [productUrl, setProductUrl] = useState("");
  const [saved, setSaved] = useState<SavedLink[]>([]);
  const [assets, setAssets] = useState<Asset[]>([]);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [products, setProducts] = useState<{ title: string; url: string }[] | null>(null);
  const [prodQuery, setProdQuery] = useState("");

  const storeKey = "pn_saved_links";

  const browseProducts = async () => {
    const id = auth.get()?.id;
    if (!id) return;
    setProducts([]);
    try {
      const r = await api.get(`/affiliates/${id}/products${prodQuery ? `?q=${encodeURIComponent(prodQuery)}` : ""}`);
      setProducts(r?.products || []);
    } catch {
      setProducts([]);
    }
  };

  const load = useCallback(async () => {
    const id = auth.get()?.id;
    if (!id) return;
    setInfo(await api.get(`/affiliates/${id}`));
    api.get("/admin/assets").then(setAssets).catch(() => {});
    // Per-brand tracking links (one /click link per campaign the affiliate promotes).
    api.get(`/affiliates/${id}/links`).then((r) => setBrands(r?.brands || [])).catch(() => {});
    try {
      setSaved(JSON.parse(localStorage.getItem(storeKey) || "[]"));
    } catch {
      setSaved([]);
    }
  }, []);

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

  const persist = (list: SavedLink[]) => {
    setSaved(list);
    localStorage.setItem(storeKey, JSON.stringify(list));
  };

  const [generating, setGenerating] = useState(false);

  const generate = async () => {
    const url = productUrl.trim();
    if (!/^https?:\/\//.test(url)) {
      toast.error("Paste a full product URL (https://…).");
      return;
    }
    const id = auth.get()?.id;
    if (!id) return;
    setGenerating(true);
    try {
      // Real Marcadeo deep link — a tracked /click URL to this specific page.
      const r = await api.post(`/affiliates/${id}/deep-link`, { url });
      persist([{ url, tracked: r.url }, ...saved.filter((s) => s.url !== url)]);
      setProductUrl("");
      toast.success("Tracked link generated & saved.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setGenerating(false);
    }
  };

  const copy = (t: string) => {
    navigator.clipboard?.writeText(t);
    toast.success("Link copied.");
  };
  const shorten = async (url: string) => {
    const id = auth.get()?.id;
    if (!id) return;
    try {
      const r = await api.post(`/affiliates/${id}/shorten`, { url });
      navigator.clipboard?.writeText(r.shortUrl);
      toast.success(`Short link copied: ${r.shortUrl}`);
    } catch (e) {
      toast.error((e as Error).message);
    }
  };
  const remove = (url: string) => persist(saved.filter((s) => s.url !== url));

  if (!info) return <div className="space-y-4"><Skeleton className="h-8 w-40" /><Skeleton className="h-40" /></div>;

  return (
    <div>
      <PageHeader title="Marketing Tools" subtitle="Generate trackable links and grab creative assets" />

      <div className="space-y-4">
        <Card title="Your brand links" subtitle="Each brand/campaign has its own tracking link — share the one you're promoting">
          {brands.length === 0 ? (
            <EmptyState icon={<Store className="h-6 w-6" />} title="No brand links yet" description="When a brand/campaign is set up for you, its tracking link appears here." />
          ) : (
            <ul className="divide-y divide-gray-50">
              {brands.map((b) => (
                <li key={b.campaignId ?? b.name} className="flex items-center gap-3 py-3">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <p className="truncate text-sm font-medium text-gray-900">{b.name}</p>
                      {b.couponCode ? <Badge tone="brand">{b.couponCode}</Badge> : null}
                    </div>
                    <p className="truncate text-xs text-gray-400">{b.url}</p>
                  </div>
                  <Button size="sm" variant="secondary" icon={<Copy className="h-3.5 w-3.5" />} onClick={() => copy(b.url)}>Copy link</Button>
                  <Button size="sm" variant="secondary" onClick={() => shorten(b.url)}>Shorten</Button>
                </li>
              ))}
            </ul>
          )}
        </Card>

        <Card title="Product link generator" subtitle="Turn any product page into a trackable referral link">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
            <div className="flex-1">
              <FormField label="Product URL" hint="Paste a product link from the store">
                <Input value={productUrl} onChange={(e) => setProductUrl(e.target.value)} placeholder="https://store.myshopify.com/products/…" />
              </FormField>
            </div>
            <Button icon={<Wand2 className="h-4 w-4" />} onClick={generate} loading={generating}>Generate link</Button>
          </div>
          <p className="mt-3 text-xs text-gray-400">
            Your code <Badge tone="brand">{info.couponCode}</Badge> is added automatically so every click and sale is tracked to you.
          </p>

          {/* Or browse store products to deep-link */}
          <div className="mt-4 border-t border-gray-100 pt-4">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-end">
              <div className="flex-1">
                <FormField label="Or browse products" hint="Pick a product to generate its tracked link">
                  <Input value={prodQuery} onChange={(e) => setProdQuery(e.target.value)} placeholder="Search products…" />
                </FormField>
              </div>
              <Button variant="secondary" onClick={browseProducts}>Browse</Button>
            </div>
            {products !== null && (
              products.length === 0 ? (
                <p className="mt-2 text-xs text-gray-400">No products found (or store not connected yet).</p>
              ) : (
                <ul className="mt-2 max-h-48 divide-y divide-gray-50 overflow-y-auto rounded-lg border border-gray-100">
                  {products.map((p) => (
                    <li key={p.url} className="flex items-center justify-between gap-2 px-3 py-2">
                      <span className="truncate text-sm text-gray-700">{p.title}</span>
                      <Button size="sm" variant="secondary" onClick={() => { setProductUrl(p.url); }}>Use</Button>
                    </li>
                  ))}
                </ul>
              )
            )}
          </div>
        </Card>

        <Card title="Your saved links">
          {saved.length === 0 ? (
            <EmptyState icon={<Link2 className="h-6 w-6" />} title="No links yet" description="Generate a product link above and it'll be saved here." />
          ) : (
            <ul className="divide-y divide-gray-50">
              {saved.map((s) => (
                <li key={s.url} className="flex items-center gap-3 py-3">
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm text-gray-700">{s.url}</p>
                    <p className="truncate text-xs text-gray-400">{s.tracked}</p>
                  </div>
                  <Button size="sm" variant="secondary" icon={<Copy className="h-3.5 w-3.5" />} onClick={() => copy(s.tracked)}>Copy</Button>
                  <button onClick={() => remove(s.url)} className="text-gray-400 hover:text-red-600"><Trash2 className="h-4 w-4" /></button>
                </li>
              ))}
            </ul>
          )}
        </Card>

        <Card title="Creative assets" subtitle="Banners & images shared by the brand">
          {assets.length === 0 ? (
            <EmptyState icon={<ImageIcon className="h-6 w-6" />} title="No assets yet" description="When the brand uploads banners, images or videos, they'll appear here for you to download and share." />
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {assets.map((a) => {
                const isImg = a.type === "IMAGE" || a.type === "BANNER";
                return (
                  <div key={a.id} className="overflow-hidden rounded-xl border border-gray-200">
                    <div className="flex h-32 items-center justify-center bg-gray-50">
                      {isImg ? (
                        <Image src={a.url} alt={a.title} width={280} height={128} className="h-full w-full object-cover" unoptimized />
                      ) : (
                        <ExternalLink className="h-7 w-7 text-gray-300" />
                      )}
                    </div>
                    <div className="p-3">
                      <div className="flex items-center justify-between gap-2">
                        <p className="truncate text-sm font-medium text-gray-900">{a.title}</p>
                        <Badge tone="neutral">{a.type}</Badge>
                      </div>
                      <div className="mt-2 flex items-center gap-3">
                        <a href={a.url} target="_blank" className="text-xs text-[var(--brand)] hover:underline">Open ↗</a>
                        <button onClick={() => { navigator.clipboard?.writeText(a.url); toast.success("Asset link copied."); }} className="inline-flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700">
                          <Copy className="h-3 w-3" /> Copy link
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}
