"use client";
import { useMemo, useState } from "react";
import { ChevronLeft, ChevronRight, Copy, ImagePlus, Link2, Plus, Sparkles, Trash2 } from "lucide-react";
import { Badge, Button, Card, Empty, Field, Input, PageHeader, Segmented, Select, Sheet, Tabs, Textarea, api, cx, useAction, useUI } from "@/components/ui";
import { compact, fmtDate, useApi } from "@/components/hooks";

const STATUS_TONE: Record<string, string> = { draft: "gray", in_review: "amber", approved: "blue", scheduled: "violet", published: "green", failed: "red" };
const CH_COLOR: Record<string, string> = { facebook: "#1877F2", instagram: "#C13584", linkedin: "#0A66C2", tiktok: "#111" };
const startOfWeek = (d: Date) => { const x = new Date(d); x.setHours(0, 0, 0, 0); x.setDate(x.getDate() - ((x.getDay() + 6) % 7)); return x; };
const key = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;

export default function ContentPage() {
  const [tab, setTab] = useState<"calendar" | "assets">("calendar");
  return (
    <>
      <PageHeader title="Content & social" subtitle="Plan, approve and auto-publish to Facebook, Instagram, LinkedIn and TikTok" />
      <div className="mb-3"><Tabs value={tab} onChange={setTab} tabs={[{ value: "calendar", label: "Calendar" }, { value: "assets", label: "Assets & brand kit" }]} /></div>
      {tab === "calendar" ? <Calendar /> : <Assets />}
    </>
  );
}

function Calendar() {
  const posts = useApi<{ data: any[] }>("/content/posts");
  const team = useApi<{ perms: Record<string, string>; timezone: string }>("/team");
  const [view, setView] = useState<"month" | "week" | "list">("month");
  const [cursor, setCursor] = useState(() => new Date());
  const [edit, setEdit] = useState<any | null>(null);
  const [drag, setDrag] = useState<string | null>(null);
  const { push } = useUI();
  const canEdit = ["C", "A"].includes(team.data?.perms?.content ?? "");
  const byDay = useMemo(() => {
    const m = new Map<string, any[]>();
    for (const p of posts.data?.data ?? []) if (p.scheduledAt) { const k = key(new Date(p.scheduledAt)); m.set(k, [...(m.get(k) ?? []), p]); }
    return m;
  }, [posts.data]);
  const days = useMemo(() => {
    if (view === "week") { const s = startOfWeek(cursor); return Array.from({ length: 7 }, (_, i) => new Date(s.getFullYear(), s.getMonth(), s.getDate() + i)); }
    const first = new Date(cursor.getFullYear(), cursor.getMonth(), 1);
    const s = startOfWeek(first);
    return Array.from({ length: 42 }, (_, i) => new Date(s.getFullYear(), s.getMonth(), s.getDate() + i));
  }, [cursor, view]);
  const shift = (n: number) => setCursor((c) => (view === "week" ? new Date(c.getFullYear(), c.getMonth(), c.getDate() + 7 * n) : new Date(c.getFullYear(), c.getMonth() + n, 1)));
  const reschedule = async (postId: string, day: Date) => {
    const p = posts.data?.data.find((x) => x.id === postId);
    if (!p || p.status === "published") return;
    const old = p.scheduledAt ? new Date(p.scheduledAt) : new Date(day.setHours(11, 0, 0, 0));
    const next = new Date(day.getFullYear(), day.getMonth(), day.getDate(), old.getHours(), old.getMinutes());
    try { await api(`/content/posts/${postId}`, { method: "PATCH", body: { scheduled_at: next.toISOString() } }); push("ok", `Moved to ${next.toDateString()}`); posts.reload(); } catch (e) { push("error", (e as Error).message); }
  };
  const today = key(new Date());

  return (
    <>
      <div className="mb-3 flex flex-wrap items-center gap-2">
        <Button size="sm" variant="ghost" icon={<ChevronLeft className="h-4 w-4" />} onClick={() => shift(-1)} aria-label="Previous" />
        <span className="min-w-[160px] text-center text-[15px] font-semibold">{view === "week" ? `Week of ${startOfWeek(cursor).toLocaleDateString(undefined, { day: "numeric", month: "short" })}` : cursor.toLocaleDateString(undefined, { month: "long", year: "numeric" })}</span>
        <Button size="sm" variant="ghost" icon={<ChevronRight className="h-4 w-4" />} onClick={() => shift(1)} aria-label="Next" />
        <Button size="sm" onClick={() => setCursor(new Date())}>Today</Button>
        <div className="ml-auto flex items-center gap-2">
          <Segmented value={view} onChange={setView} options={[{ value: "month", label: "Month" }, { value: "week", label: "Week" }, { value: "list", label: "List" }]} />
          {canEdit && <Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setEdit({ channels: ["facebook", "instagram"], body: "", status: "draft", media: [] })}>New post</Button>}
        </div>
      </div>
      {view === "list" ? (
        <Card bodyClass="p-0">
          <table className="table-mac">
            <thead><tr><th>Post</th><th>Channels</th><th>Campaign</th><th>Status</th><th>Scheduled</th><th className="text-right">Reach</th><th className="text-right">Engagement</th></tr></thead>
            <tbody>{(posts.data?.data ?? []).map((p) => (
              <tr key={p.id} className="cursor-pointer" onClick={() => setEdit(p)}>
                <td className="max-w-[320px] truncate">{p.body}</td><td>{p.channels.map((c: string) => <span key={c} className="mr-1 inline-block h-2.5 w-2.5 rounded-full" style={{ background: CH_COLOR[c] }} title={c} />)}</td>
                <td className="text-ink-3">{p.campaign ?? "—"}</td><td><Badge tone={STATUS_TONE[p.status]}>{p.status.replace("_", " ")}</Badge></td><td className="text-ink-3">{fmtDate(p.scheduledAt, team.data?.timezone)}</td>
                <td className="text-right">{p.metrics?.reach ? compact(p.metrics.reach) : "—"}</td><td className="text-right">{p.metrics?.engagement ? compact(p.metrics.engagement) : "—"}</td>
              </tr>
            ))}</tbody>
          </table>
          {!posts.data?.data.length && <Empty title="No posts" />}
        </Card>
      ) : (
        <div className="card overflow-hidden">
          <div className="grid grid-cols-7 border-b border-line bg-sunken text-center text-[11px] font-semibold uppercase tracking-wide text-ink-3">{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => <div key={d} className="py-2">{d}</div>)}</div>
          <div className="grid grid-cols-7">
            {days.map((d) => {
              const k = key(d);
              const items = byDay.get(k) ?? [];
              const outside = view === "month" && d.getMonth() !== cursor.getMonth();
              return (
                <div key={k} onDragOver={(e) => canEdit && e.preventDefault()} onDrop={() => { if (drag) reschedule(drag, new Date(d)); setDrag(null); }}
                  onDoubleClick={() => canEdit && setEdit({ channels: ["facebook"], body: "", status: "draft", media: [], scheduledAt: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 11).toISOString() })}
                  className={cx("border-b border-r border-line/70 p-1.5", view === "week" ? "min-h-[360px]" : "min-h-[112px]", outside && "bg-sunken/50")}>
                  <div className={cx("mb-1 grid h-6 w-6 place-items-center rounded-full text-[12px]", k === today ? "bg-brand font-semibold text-white" : outside ? "text-ink-3" : "")}>{d.getDate()}</div>
                  <div className="space-y-1">
                    {items.map((p) => (
                      <button key={p.id} draggable={canEdit && p.status !== "published"} onDragStart={() => setDrag(p.id)} onClick={() => setEdit(p)}
                        className="block w-full truncate rounded-[6px] border-l-[3px] bg-panel px-1.5 py-1 text-left text-[11.5px] shadow-[0_0_0_.5px_rgb(var(--line))] hover:bg-sunken" style={{ borderLeftColor: CH_COLOR[p.channels[0]] ?? "#888" }}>
                        <span className="mr-1 text-ink-3">{new Date(p.scheduledAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</span>{p.body}
                        <div className="mt-0.5"><Badge tone={STATUS_TONE[p.status]} className="!px-1.5 !text-[10px]">{p.status.replace("_", " ")}</Badge></div>
                      </button>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
      <p className="mt-2 text-[11.5px] text-ink-3">Drag a post to another day to reschedule · double-click a day to create a post. Unscheduled drafts appear in List view.</p>
      {edit && <PostSheet post={edit} perms={team.data?.perms ?? {}} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); posts.reload(); }} />}
    </>
  );
}

function PostSheet({ post, perms, onClose, onSaved }: { post: any; perms: Record<string, string>; onClose: () => void; onSaved: () => void }) {
  const [f, setF] = useState({ channels: post.channels as string[], campaign: post.campaign ?? "", body: post.body ?? "", media: post.media ?? [], scheduled_at: post.scheduledAt ? new Date(new Date(post.scheduledAt).getTime() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 16) : "" });
  const assets = useApi<{ data: any[] }>("/assets");
  const { busy, run } = useAction();
  const { push } = useUI();
  const [gen, setGen] = useState(false);
  const isNew = !post.id;
  const published = post.status === "published";
  const canEdit = perms.content === "C";
  const canApprove = perms.content === "A" || perms.content === "C";
  const body = { channels: f.channels, campaign: f.campaign || undefined, body: f.body, media: f.media, scheduled_at: f.scheduled_at ? new Date(f.scheduled_at).toISOString() : null };
  const save = () => run(async () => { if (isNew) await api("/content/posts", { body }); else await api(`/content/posts/${post.id}`, { method: "PATCH", body }); onSaved(); }, "Saved");
  const transition = (to: string, note?: string) => run(async () => {
    if (!isNew && !published && canEdit) await api(`/content/posts/${post.id}`, { method: "PATCH", body });
    await api(`/content/posts/${post.id}/transition`, { body: { to, note } }); onSaved();
  }, to === "in_review" ? "Sent for review" : to === "approved" ? "Approved" : to === "scheduled" ? "Scheduled — publishes automatically" : "Moved to draft");
  const approvalLink = post.approvalToken ? `${location.origin}/approve/${post.approvalToken}` : null;
  return (
    <Sheet open onClose={onClose} width={720} title={isNew ? "New post" : published ? "Published post" : "Edit post"}
      footer={<>
        {!isNew && <Badge tone={STATUS_TONE[post.status]} className="mr-auto">{post.status.replace("_", " ")}</Badge>}
        <Button onClick={onClose}>Close</Button>
        {!published && canEdit && <Button loading={busy} onClick={save}>Save draft</Button>}
        {!isNew && post.status === "draft" && canEdit && <Button variant="tinted" loading={busy} onClick={() => transition("in_review")}>Send for review</Button>}
        {!isNew && post.status === "in_review" && canApprove && <><Button loading={busy} onClick={() => transition("draft", "Changes requested")}>Request changes</Button><Button variant="primary" loading={busy} onClick={() => transition("approved")}>Approve</Button></>}
        {!isNew && post.status === "approved" && canEdit && <Button variant="primary" loading={busy} onClick={() => transition("scheduled")}>Schedule</Button>}
        {!isNew && post.status === "scheduled" && canEdit && <Button loading={busy} onClick={() => transition("draft")}>Unschedule</Button>}
      </>}>
      <div className="grid gap-4 md:grid-cols-[1fr_250px]">
        <div className="space-y-3">
          <div className="flex flex-wrap gap-2">{["facebook", "instagram", "linkedin", "tiktok"].map((c) => (
            <button key={c} disabled={published} onClick={() => setF({ ...f, channels: f.channels.includes(c) ? f.channels.filter((x) => x !== c) : [...f.channels, c] })} className={cx("rounded-full border px-3 py-1 text-[12.5px] capitalize", f.channels.includes(c) ? "border-transparent text-white" : "border-line text-ink-2")} style={f.channels.includes(c) ? { background: CH_COLOR[c] } : {}}>{c}</button>
          ))}</div>
          <Field label={<span className="flex justify-between">Caption<button type="button" className="inline-flex items-center gap-1 text-[11.5px] text-violet hover:underline" disabled={gen || published} onClick={async () => { setGen(true); try { const r = await api("/ai/generate", { body: { kind: "caption", brief: f.body || f.campaign || "Social post promoting our latest offer", language: /[ঀ-৿]/.test(f.body) ? "bn" : "en", variants: 3 } }); setF({ ...f, body: r.data.variants[0]?.content ?? f.body }); } catch (e) { push("error", (e as Error).message); } finally { setGen(false); } }}><Sparkles className="h-3 w-3" />{gen ? "Writing…" : "AI caption"}</button></span>}>
            <Textarea className="min-h-[140px]" disabled={published} value={f.body} onChange={(e) => setF({ ...f, body: e.target.value })} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Campaign"><Input disabled={published} value={f.campaign} onChange={(e) => setF({ ...f, campaign: e.target.value })} /></Field>
            <Field label="Publish at (your local time)"><input type="datetime-local" disabled={published} className="field" value={f.scheduled_at} onChange={(e) => setF({ ...f, scheduled_at: e.target.value })} /></Field>
          </div>
          <Field label="Media from asset library">
            <div className="flex flex-wrap gap-2">
              {f.media.map((m: any, i: number) => <div key={i} className="relative"><img src={m.url} alt="" className="h-16 w-16 rounded-[8px] object-cover" />{!published && <button aria-label="Remove" onClick={() => setF({ ...f, media: f.media.filter((_: any, j: number) => j !== i) })} className="absolute -right-1 -top-1 grid h-5 w-5 place-items-center rounded-full bg-ink text-white"><Trash2 className="h-3 w-3" /></button>}</div>)}
              {!published && <Select className="w-[200px]" value="" onChange={(e) => { const a = assets.data?.data.find((x) => x.id === e.target.value); if (a) setF({ ...f, media: [...f.media, { assetId: a.id, url: a.url, type: a.type }] }); }}><option value="">+ Add asset…</option>{assets.data?.data.filter((a) => a.type !== "document").map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}</Select>}
            </div>
          </Field>
          {post.approvalNote && <p className="rounded-[8px] bg-warn/10 p-2.5 text-[12px]">Note: {post.approvalNote}</p>}
          {approvalLink && post.status === "in_review" && (
            <div className="flex items-center gap-2 rounded-[8px] border border-line p-2.5 text-[12px]"><Link2 className="h-3.5 w-3.5 text-ink-3" /><span className="flex-1 truncate">Client approval link (no login needed)</span><Button size="sm" icon={<Copy className="h-3 w-3" />} onClick={() => { navigator.clipboard.writeText(approvalLink); push("ok", "Link copied"); }}>Copy</Button></div>
          )}
        </div>
        <div>
          <div className="label mb-1.5">Preview</div>
          <div className="overflow-hidden rounded-[12px] border border-line bg-panel">
            <div className="flex items-center gap-2 p-2.5"><img src="/icon.svg" alt="" className="h-7 w-7" /><div className="text-[12px] font-semibold">Your Page</div></div>
            {f.media[0] && <img src={f.media[0].url} alt="" className="aspect-square w-full object-cover" />}
            <p className="whitespace-pre-wrap p-2.5 text-[12px]">{f.body || <span className="text-ink-3">Caption…</span>}</p>
            {published && <div className="flex justify-between border-t border-line px-2.5 py-2 text-[11px] text-ink-3"><span>Reach {compact(post.metrics?.reach)}</span><span>❤ {compact(post.metrics?.likes)}</span><span>💬 {compact(post.metrics?.comments)}</span><span>↗ {compact(post.metrics?.shares)}</span></div>}
          </div>
          {published && <p className="mt-2 text-[11px] text-ink-3">Post IDs: {Object.entries(post.externalPostIds).map(([k, v]) => `${k}: ${v}`).join(", ")}</p>}
        </div>
      </div>
    </Sheet>
  );
}

function Assets() {
  const a = useApi<{ data: any[]; brandKits: any[] }>("/assets");
  const team = useApi<{ perms: Record<string, string> }>("/team");
  const [folder, setFolder] = useState("");
  const [add, setAdd] = useState(false);
  const { confirm } = useUI();
  const canEdit = team.data?.perms?.content === "C";
  const folders = [...new Set((a.data?.data ?? []).map((x) => x.folder))];
  const kit = a.data?.brandKits?.[0];
  return (
    <div className="grid gap-4 xl:grid-cols-[1fr_340px]">
      <Card title="Asset library" actions={<>
        <Select className="w-[170px]" value={folder} onChange={(e) => setFolder(e.target.value)}><option value="">All folders</option>{folders.map((f) => <option key={f}>{f}</option>)}</Select>
        {canEdit && <Button size="sm" variant="primary" icon={<ImagePlus className="h-3.5 w-3.5" />} onClick={() => setAdd(true)}>Add</Button>}
      </>}>
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
          {(a.data?.data ?? []).filter((x) => !folder || x.folder === folder).map((x) => (
            <div key={x.id} className="group overflow-hidden rounded-[10px] border border-line">
              {x.type === "document" ? <div className="grid aspect-square place-items-center bg-sunken text-[12px] text-ink-3">Document</div> : x.type === "video" ? <video src={x.url} className="aspect-square w-full object-cover" /> : <img src={x.url} alt={x.name} className="aspect-square w-full object-cover" />}
              <div className="flex items-center gap-1 p-2"><div className="min-w-0 flex-1"><div className="truncate text-[12px] font-medium">{x.name}</div><div className="truncate text-[10.5px] text-ink-3">{x.folder} · {x.tags.join(", ")}</div></div>
                {canEdit && <button aria-label="Delete" className="text-ink-3 opacity-0 hover:text-bad group-hover:opacity-100" onClick={async () => { if (await confirm({ title: `Delete ${x.name}?`, danger: true, confirmLabel: "Delete" })) { await api(`/assets/${x.id}`, { method: "DELETE" }); a.reload(); } }}><Trash2 className="h-3.5 w-3.5" /></button>}
              </div>
            </div>
          ))}
        </div>
        {!a.data?.data.length && <Empty title="No assets yet" />}
      </Card>
      <BrandKit kit={kit} canEdit={canEdit} onSaved={a.reload} />
      {add && <AddAsset onClose={() => setAdd(false)} onDone={() => { setAdd(false); a.reload(); }} />}
    </div>
  );
}

function AddAsset({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [f, setF] = useState({ name: "", url: "", type: "image", folder: "General", tags: "" });
  const { busy, run } = useAction();
  const onFile = (file: File) => {
    if (file.size > 4 * 1024 * 1024) { alert("Files up to 4 MB — for larger media paste a CDN/S3 URL"); return; }
    const r = new FileReader();
    r.onload = () => setF((x) => ({ ...x, url: String(r.result), name: x.name || file.name, type: file.type.startsWith("video") ? "video" : file.type.startsWith("image") ? "image" : "document" }));
    r.readAsDataURL(file);
  };
  return (
    <Sheet open onClose={onClose} width={480} title="Add asset" footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { await api("/assets", { body: { ...f, tags: f.tags.split(",").map((t) => t.trim()).filter(Boolean) } }); onDone(); }, "Asset added")}>Add</Button></>}>
      <div className="space-y-3">
        <label className="flex cursor-pointer items-center justify-center rounded-[10px] border-2 border-dashed border-line p-5 text-[12.5px] text-ink-3 hover:border-brand/50">{f.url.startsWith("data:") ? "File ready ✓" : "Upload a file (≤ 4 MB)"}<input type="file" className="hidden" accept="image/*,video/*,application/pdf" onChange={(e) => e.target.files?.[0] && onFile(e.target.files[0])} /></label>
        <Field label="…or paste a URL"><Input value={f.url.startsWith("data:") ? "" : f.url} onChange={(e) => setF({ ...f, url: e.target.value })} placeholder="https://cdn.example.com/image.jpg" /></Field>
        <div className="grid grid-cols-2 gap-3"><Field label="Name"><Input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field><Field label="Type"><Select value={f.type} onChange={(e) => setF({ ...f, type: e.target.value })}><option value="image">Image</option><option value="video">Video</option><option value="logo">Logo</option><option value="document">Document</option></Select></Field></div>
        <div className="grid grid-cols-2 gap-3"><Field label="Folder"><Input value={f.folder} onChange={(e) => setF({ ...f, folder: e.target.value })} /></Field><Field label="Tags"><Input value={f.tags} onChange={(e) => setF({ ...f, tags: e.target.value })} placeholder="hero, exterior" /></Field></div>
      </div>
    </Sheet>
  );
}

function BrandKit({ kit, canEdit, onSaved }: { kit: any; canEdit: boolean; onSaved: () => void }) {
  const [f, setF] = useState({ name: kit?.name ?? "Brand kit", colors: (kit?.colors ?? ["#2563EB", "#000000", "#F7F7FA", "#7C6CF0"]).join(", "), fonts: (kit?.fonts ?? ["Syne", "Kanit"]).join(", "), logos: (kit?.logos ?? []).join("\n"), voice: kit?.voice ?? "" });
  const { busy, run } = useAction();
  const colors = f.colors.split(",").map((c: string) => c.trim()).filter((c: string) => /^#[0-9a-fA-F]{6}$/.test(c));
  return (
    <Card title="Brand kit" subtitle="Used by AI generation, pages and reports">
      <div className="space-y-3">
        <div className="flex gap-1.5">{colors.map((c: string) => <span key={c} className="h-8 flex-1 rounded-[6px] shadow-[inset_0_0_0_.5px_rgb(0_0_0/.15)]" style={{ background: c }} title={c} />)}</div>
        <Field label="Colours (hex)"><Input disabled={!canEdit} value={f.colors} onChange={(e) => setF({ ...f, colors: e.target.value })} /></Field>
        <Field label="Fonts"><Input disabled={!canEdit} value={f.fonts} onChange={(e) => setF({ ...f, fonts: e.target.value })} /></Field>
        <Field label="Logo URLs (one per line)"><Textarea disabled={!canEdit} className="min-h-[50px]" value={f.logos} onChange={(e) => setF({ ...f, logos: e.target.value })} /></Field>
        <Field label="Brand voice" hint="AI copy follows this voice"><Textarea disabled={!canEdit} value={f.voice} onChange={(e) => setF({ ...f, voice: e.target.value })} /></Field>
        {canEdit && <Button variant="primary" className="w-full" loading={busy} onClick={() => run(async () => { await api("/brand-kit", { method: "PUT", body: { name: f.name, colors, fonts: f.fonts.split(",").map((x: string) => x.trim()).filter(Boolean), logos: f.logos.split("\n").map((x: string) => x.trim()).filter(Boolean), voice: f.voice } }); onSaved(); }, "Brand kit saved")}>Save brand kit</Button>}
      </div>
    </Card>
  );
}
