"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import {
  SOCIAL_PLATFORM_LIST,
  SOCIAL_PLATFORMS,
  type SocialPlatformId,
} from "@/lib/social/platforms";
import type { SocialPost } from "@/lib/social/post-types";
import {
  extractCaptionsFromResponse,
  extractHashtagsFromCaption,
} from "@/lib/agents/extract-caption";

/**
 * Storage key mirrored from `social-calendar.tsx` and `release-to-social.ts`.
 * Writing to the same v2 key keeps the social composer in sync.
 */
const POSTS_KEY_V2 = "sag.social.posts.v2";

/** Default platform spread when the agent did not specify any. */
const DEFAULT_PLATFORMS: SocialPlatformId[] = ["instagram", "x", "tiktok", "youtube"];

interface SendToSocialButtonProps {
  /** Raw assistant message text from the Marketing Agent. */
  caption: string;
  /** Optional platform hints already detected by the caller. */
  suggestedPlatforms?: SocialPlatformId[];
  /** Optional entity slug if the caller knows which org this caption is for. */
  entitySlug?: string;
}

function newPostId(): string {
  try {
    if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
      return `post-${crypto.randomUUID()}`;
    }
  } catch {
    // fall through
  }
  return `post-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}

/**
 * Schedule for tomorrow at 10:00 local — Glenn must explicitly choose a
 * different time later when promoting from Draft to Scheduled. Mirrors the
 * convention used by `releaseToSocialDraft`.
 */
function tomorrowAt10Local(): string {
  const d = new Date();
  d.setDate(d.getDate() + 1);
  d.setHours(10, 0, 0, 0);
  return d.toISOString();
}

/**
 * Best-effort detection of which SAG entity the message is about. Matches
 * against organization name + slug + dba (if present). Falls back to the
 * `entitySlug` prop, then the SAG parent.
 */
function detectEntitySlug(text: string, fallback: string | undefined): string {
  const haystack = text.toLowerCase();
  for (const org of ALL_ORGANIZATIONS) {
    const candidates = [org.name, org.slug, org.dba].filter(
      (s): s is string => typeof s === "string" && s.length > 0
    );
    if (candidates.some((c) => haystack.includes(c.toLowerCase()))) {
      return org.slug;
    }
  }
  if (fallback) return fallback;
  return ALL_ORGANIZATIONS[0]?.slug ?? "south-armz-global";
}

/**
 * Write a new Draft SocialPost to `sag.social.posts.v2`. Returns the id of
 * the new post on success, or `null` if storage isn't writable.
 */
function writeDraftPost(post: SocialPost): string | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = window.localStorage.getItem(POSTS_KEY_V2);
    const current = raw ? (JSON.parse(raw) as SocialPost[]) : [];
    const next = [post, ...current];
    window.localStorage.setItem(POSTS_KEY_V2, JSON.stringify(next));
    return post.id;
  } catch {
    return null;
  }
}

interface SentState {
  postId: string;
  captionIndex: number;
}

export function SendToSocialButton({
  caption,
  suggestedPlatforms,
  entitySlug,
}: SendToSocialButtonProps) {
  const [open, setOpen] = useState(false);
  const [sent, setSent] = useState<SentState[]>([]);
  const [error, setError] = useState<string>("");

  // Extract caption candidates from the message text. Memoized — pure helper.
  const candidates = useMemo(() => extractCaptionsFromResponse(caption), [caption]);

  // Per-caption form state. Each candidate gets its own entity + platforms.
  const [forms, setForms] = useState(() =>
    candidates.map((c) => ({
      organizationSlug: detectEntitySlug(c.caption, entitySlug),
      platforms:
        (suggestedPlatforms && suggestedPlatforms.length > 0
          ? suggestedPlatforms
          : c.platforms.length > 0
            ? c.platforms
            : DEFAULT_PLATFORMS) as SocialPlatformId[],
    }))
  );

  function togglePlatform(captionIdx: number, p: SocialPlatformId) {
    setForms((prev) =>
      prev.map((f, i) => {
        if (i !== captionIdx) return f;
        const has = f.platforms.includes(p);
        return {
          ...f,
          platforms: has ? f.platforms.filter((x) => x !== p) : [...f.platforms, p],
        };
      })
    );
  }

  function setEntity(captionIdx: number, slug: string) {
    setForms((prev) =>
      prev.map((f, i) => (i === captionIdx ? { ...f, organizationSlug: slug } : f))
    );
  }

  function sendOne(captionIdx: number) {
    const form = forms[captionIdx];
    const cand = candidates[captionIdx];
    if (!form || !cand) return;
    if (form.platforms.length === 0) {
      setError("Pick at least one platform before sending.");
      return;
    }

    const hashtags = extractHashtagsFromCaption(cand.caption);
    const post: SocialPost = {
      id: newPostId(),
      organizationSlug: form.organizationSlug,
      content: cand.caption,
      platforms: form.platforms,
      scheduledAt: tomorrowAt10Local(),
      media: [],
      hashtags,
      status: "Draft",
      createdAt: new Date().toISOString(),
    };

    const id = writeDraftPost(post);
    if (!id) {
      setError("Couldn't write to local storage. Is the browser in private mode?");
      return;
    }
    setError("");
    setSent((prev) => [...prev, { postId: id, captionIndex: captionIdx }]);
  }

  // Nothing to do if the message had no usable text.
  if (candidates.length === 0) return null;

  return (
    <div className="mt-2">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => setOpen((v) => !v)}
        className="text-xs h-7 px-2"
      >
        {open ? "Hide" : "→ Send to social composer"}
        {candidates.length > 1 ? ` (${candidates.length} captions)` : ""}
      </Button>

      {open && (
        <div className="mt-2 rounded-md border bg-background/80 p-3 space-y-3">
          {candidates.map((cand, idx) => {
            const form = forms[idx];
            const wasSent = sent.find((s) => s.captionIndex === idx);
            if (!form) return null;
            return (
              <div
                key={idx}
                className="rounded-md border bg-muted/30 p-3 text-xs space-y-2"
              >
                <div className="font-mono text-[11px] whitespace-pre-wrap leading-relaxed text-foreground/90 max-h-32 overflow-y-auto">
                  {cand.caption}
                </div>

                <div className="flex flex-wrap items-center gap-2">
                  <label className="text-[10px] text-muted-foreground uppercase tracking-wider">
                    Entity
                  </label>
                  <select
                    value={form.organizationSlug}
                    onChange={(e) => setEntity(idx, e.target.value)}
                    className="h-8 rounded-md border border-input bg-background px-2 text-xs"
                    disabled={!!wasSent}
                  >
                    {ALL_ORGANIZATIONS.map((o) => (
                      <option key={o.slug} value={o.slug}>
                        {o.emoji} {o.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="text-[10px] text-muted-foreground uppercase tracking-wider">
                    Platforms
                  </label>
                  <div className="mt-1 flex flex-wrap gap-1">
                    {SOCIAL_PLATFORM_LIST.map((p) => {
                      const active = form.platforms.includes(p.id);
                      return (
                        <button
                          key={p.id}
                          type="button"
                          onClick={() => togglePlatform(idx, p.id)}
                          disabled={!!wasSent}
                          className={`text-[11px] px-2 py-1 rounded-full border transition-colors inline-flex items-center gap-1 ${
                            active
                              ? "bg-foreground text-background border-foreground"
                              : "border-input text-muted-foreground hover:bg-accent"
                          } ${wasSent ? "opacity-60 cursor-not-allowed" : ""}`}
                        >
                          <span>{SOCIAL_PLATFORMS[p.id].icon}</span>
                          {p.label}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div className="flex items-center justify-between gap-2 pt-1">
                  {wasSent ? (
                    <span className="text-[11px] text-green-700 dark:text-green-400 inline-flex items-center gap-2">
                      Sent to /app/social as Draft.
                      <Link
                        href="/app/social"
                        className="underline hover:no-underline"
                      >
                        Open &#x2197;
                      </Link>
                    </span>
                  ) : (
                    <span className="text-[10px] text-muted-foreground">
                      Schedules for tomorrow 10:00 local. You&apos;ll review before posting.
                    </span>
                  )}
                  <Button
                    type="button"
                    variant="brand"
                    size="sm"
                    onClick={() => sendOne(idx)}
                    disabled={!!wasSent}
                    className="h-7 px-3 text-xs"
                  >
                    {wasSent ? "Sent" : "Send"}
                  </Button>
                </div>
              </div>
            );
          })}

          {error && (
            <p className="text-[11px] text-destructive">{error}</p>
          )}
        </div>
      )}
    </div>
  );
}
