import { useState, useEffect } from "react";
import { useSelect, useDispatch } from "@wordpress/data";
import { PluginDocumentSettingPanel } from "@wordpress/edit-post";
import { ToggleControl, Button, Spinner, Notice, TextareaControl, RadioControl, DateTimePicker } from "@wordpress/components";

const PLATFORM_ICONS: Record<string, string> = {
  Facebook: "📘", Instagram: "📷", TikTok: "🎵", Twitter: "𝕏",
  LinkedIn: "💼", Pinterest: "📌", YouTube: "▶️", Threads: "🧵",
  Bluesky: "🦋", Mastodon: "🐘",
};

interface Channel { id: string; name: string; type: string; status: string; username?: string }
interface PerChannelOverride { enabled: boolean; caption: string }

interface AutopostSettings {
  enabled: boolean;
  platforms: string[];
  template: string;
  timing: string;
  delayValue: number;
  delayUnit: string;
  scheduledTime: string;
  includeImage: boolean;
}

function renderTemplate(template: string, title: string, excerpt: string, link: string): string {
  return template
    .replace(/\{TITLE\}/g, title || "Post Title")
    .replace(/\{EXCERPT\}/g, excerpt || "")
    .replace(/\{POST_LINK\}/g, link || "")
    .replace(/\{AUTHOR\}/g, "")
    .replace(/\{TAGS\}/g, "")
    .replace(/\{CATEGORIES\}/g, "")
    .replace(/\{SITE_NAME\}/g, "")
    .replace(/\{SITE_URL\}/g, "")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
}

/** Strip HTML tags for plain text content */
function stripHtml(html: string): string {
  // Use DOMParser for safe HTML text extraction (no script execution)
  try {
    const doc = new DOMParser().parseFromString(html, "text/html");
    return (doc.body.textContent || "").trim();
  } catch {
    return html.replace(/<[^>]*>/g, "").trim();
  }
}

export default function ViralyEditorPanel() {
  const [channels, setChannels] = useState<Channel[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [overrides, setOverrides] = useState<Record<string, PerChannelOverride>>({});
  const [globalEnabled, setGlobalEnabled] = useState(true);
  const [autopostSettings, setAutopostSettings] = useState<AutopostSettings | null>(null);
  const [sharing, setSharing] = useState(false);
  const [shareResult, setShareResult] = useState<{ sent: number; failed: number } | null>(null);
  const [shareMode, setShareMode] = useState<"now" | "schedule">("now");
  const [scheduleDate, setScheduleDate] = useState<string | null>(null);
  const [generatingAi, setGeneratingAi] = useState<string | null>(null);
  const [userTouched, setUserTouched] = useState(false);
  const [showOverrides, setShowOverrides] = useState(false);

  const { postId, postStatus, postTitle, postExcerpt, postContent, postLink } = useSelect((select: any) => {
    const editor = select("core/editor");
    return {
      postId: editor.getCurrentPostId(),
      postStatus: editor.getCurrentPostAttribute("status") || "draft",
      postTitle: editor.getCurrentPostAttribute("title") || "",
      postExcerpt: editor.getCurrentPostAttribute("excerpt") || "",
      postContent: editor.getEditedPostContent() || "",
      postLink: editor.getPermalink() || "",
    };
  }, []);

  const { editPost } = useDispatch("core/editor");

  const { savedMeta, autopostResults, wasAutoposted } = useSelect((select: any) => {
    const meta = select("core/editor").getEditedPostAttribute("meta") || {};
    return {
      savedMeta: meta._viraly_social_sharing || "",
      autopostResults: meta._viraly_autopost_results || [],
      wasAutoposted: meta._viraly_autoposted === "1",
    };
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const baseUrl = (window as any).viralyEditor.restUrl;
        const nonce = (window as any).viralyEditor.restNonce;
        const headers = { "X-WP-Nonce": nonce };

        const [channelsRes, settingsRes] = await Promise.all([
          fetch(baseUrl + "channels", { credentials: "same-origin", headers }),
          fetch(baseUrl + "settings", { credentials: "same-origin", headers }),
        ]);

        const channelsData = await channelsRes.json();
        const settings = await settingsRes.json();

        if (settings && !settings.error) {
          setAutopostSettings({
            enabled: settings.enabled || false,
            platforms: Array.isArray(settings.platforms) ? settings.platforms : [],
            template: settings.template || "{TITLE}\n\n{EXCERPT}\n\n{POST_LINK}",
            timing: settings.timing || "instant",
            delayValue: settings.delayValue || 5,
            delayUnit: settings.delayUnit || "minutes",
            scheduledTime: settings.scheduledTime || "09:00",
            includeImage: settings.includeImage !== false,
          });
        }

        if (Array.isArray(channelsData)) {
          const active = channelsData.filter((ch: Channel) => ch.status === "Active");
          setChannels(active);

          const selectedPlatforms: string[] = Array.isArray(settings?.platforms) ? settings.platforms : [];
          const autopostEnabled = settings?.enabled ?? false;

          const initial: Record<string, PerChannelOverride> = {};
          active.forEach((ch: Channel) => {
            const enabledByDefault = selectedPlatforms.length > 0
              ? selectedPlatforms.includes(ch.id)
              : autopostEnabled;
            initial[ch.id] = { enabled: enabledByDefault, caption: "" };
          });

          if (!savedMeta) {
            setGlobalEnabled(autopostEnabled);
          }

          if (savedMeta) {
            try {
              const saved = JSON.parse(savedMeta);
              if (saved.globalEnabled !== undefined) setGlobalEnabled(saved.globalEnabled);
              if (saved.channels) {
                Object.keys(saved.channels).forEach((id) => {
                  if (initial[id]) initial[id] = { ...initial[id], ...saved.channels[id] };
                });
              }
              // If user previously customized, show overrides expanded
              setShowOverrides(true);
            } catch {}
          }

          setOverrides(initial);
        }
      } catch {
        setError("Failed to load profiles");
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (channels.length === 0 || !userTouched) return;
    editPost({
      meta: { _viraly_social_sharing: JSON.stringify({ globalEnabled, channels: overrides }) },
    });
  }, [overrides, globalEnabled, userTouched]);

  const toggleChannel = (channelId: string) => {
    setUserTouched(true);
    setOverrides((prev) => ({ ...prev, [channelId]: { ...prev[channelId], enabled: !prev[channelId]?.enabled } }));
  };

  const setCaption = (channelId: string, caption: string) => {
    setUserTouched(true);
    setOverrides((prev) => ({ ...prev, [channelId]: { ...prev[channelId], caption } }));
  };

  const enabledCount = Object.values(overrides).filter((o) => o.enabled).length;
  const enabledChannels = channels.filter((ch) => overrides[ch.id]?.enabled);
  const isPublished = postStatus === "publish";
  const isAutopostOn = autopostSettings?.enabled ?? false;

  // Build the content AI will use — title + excerpt + first ~500 chars of content
  const plainContent = stripHtml(postContent);
  const aiContext = [postTitle, postExcerpt, plainContent.slice(0, 500)].filter(Boolean).join("\n\n");

  // Rendered template preview
  const autoExcerpt = postExcerpt || plainContent.slice(0, 160);
  const templatePreview = autopostSettings
    ? renderTemplate(autopostSettings.template, postTitle, autoExcerpt, postLink)
    : "";

  const timingDesc = (() => {
    if (!autopostSettings?.enabled) return "";
    switch (autopostSettings.timing) {
      case "instant": return "instantly on publish";
      case "delayed": return `${autopostSettings.delayValue} ${autopostSettings.delayUnit} after publish`;
      case "scheduled": return `at ${autopostSettings.scheduledTime} daily`;
      default: return "";
    }
  })();

  if (loading) {
    return (
      <div style={{ textAlign: "center", padding: "20px 0" }}>
        <Spinner />
        <p style={{ fontSize: "12px", color: "#6e6e73", marginTop: "8px" }}>Loading...</p>
      </div>
    );
  }

  if (error) return <Notice status="error" isDismissible={false}>{error}</Notice>;

  if (channels.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "16px 0" }}>
        <p style={{ fontSize: "13px", color: "#6e6e73", margin: "0 0 12px" }}>No social profiles connected.</p>
        <Button variant="secondary" href={(window as any).viralyEditor.adminUrl + "?page=viraly&tab=profiles"} style={{ width: "100%" }}>
          Connect Social Profiles
        </Button>
      </div>
    );
  }

  const successCount = Array.isArray(autopostResults) ? autopostResults.filter((r: any) => r.status === "success").length : 0;
  const failedCount = Array.isArray(autopostResults) ? autopostResults.filter((r: any) => r.status === "error").length : 0;

  return (
    <div>
      {/* Previous share results */}
      {wasAutoposted && autopostResults.length > 0 && (
        <div style={{ marginBottom: "12px", padding: "10px 12px", background: successCount > 0 && failedCount === 0 ? "#ecfdf5" : "#fef2f2", borderRadius: "6px", border: `1px solid ${successCount > 0 && failedCount === 0 ? "#d1fae5" : "#fecaca"}` }}>
          <p style={{ fontSize: "12px", fontWeight: 600, color: successCount > 0 && failedCount === 0 ? "#065f46" : "#991b1b", margin: "0 0 6px" }}>
            {successCount > 0 && failedCount === 0
              ? `✓ Shared to ${successCount} profile${successCount !== 1 ? "s" : ""}`
              : failedCount > 0 && successCount === 0
                ? `✕ Failed (${failedCount} profile${failedCount !== 1 ? "s" : ""})`
                : `Shared to ${successCount}, failed on ${failedCount}`}
          </p>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
            {autopostResults.map((r: any, i: number) => (
              <span key={i} style={{ fontSize: "10px", padding: "2px 8px", borderRadius: "10px", background: r.status === "success" ? "#d1fae5" : "#fecaca", color: r.status === "success" ? "#065f46" : "#991b1b", fontWeight: 500 }}>
                {PLATFORM_ICONS[r.type] || "🌐"} {r.type}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Master toggle */}
      <ToggleControl
        label={isPublished ? "Share this post" : isAutopostOn ? "Share on publish" : "Enable sharing for this post"}
        checked={globalEnabled}
        onChange={(val: boolean) => { setUserTouched(true); setGlobalEnabled(val); }}
        __nextHasNoMarginBottom
      />

      {globalEnabled && (
        <>
          {/* Post Preview — what will actually be posted */}
          {!isPublished && templatePreview && (
            <div style={{ margin: "10px 0", padding: "10px 12px", background: "#f9fafb", border: "1px solid #e5e7eb", borderRadius: "8px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "6px" }}>
                <span style={{ fontSize: "10px", fontWeight: 600, color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.05em" }}>
                  Post Preview
                </span>
                {timingDesc && (
                  <span style={{ fontSize: "10px", color: "#E03058", fontWeight: 500 }}>
                    ⏱ {timingDesc}
                  </span>
                )}
              </div>
              <p style={{ fontSize: "12px", color: "#374151", margin: 0, whiteSpace: "pre-line", lineHeight: 1.5, maxHeight: "80px", overflow: "hidden" }}>
                {templatePreview}
              </p>
              {autopostSettings?.includeImage && (
                <span style={{ fontSize: "10px", color: "#9ca3af", marginTop: "4px", display: "block" }}>
                  📷 Featured image will be included
                </span>
              )}
            </div>
          )}

          {/* Profiles that will receive this post */}
          <div style={{ margin: "8px 0" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "6px" }}>
              <span style={{ fontSize: "11px", color: "#6b7280" }}>
                Posting to {enabledCount} profile{enabledCount !== 1 ? "s" : ""}:
              </span>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "4px" }}>
              {enabledChannels.map((ch) => (
                <span key={ch.id} style={{ display: "inline-flex", alignItems: "center", gap: "4px", fontSize: "11px", fontWeight: 500, color: "#374151", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: "12px", padding: "2px 8px 2px 4px" }}>
                  {PLATFORM_ICONS[ch.type] || "🌐"} {ch.name}
                </span>
              ))}
              {enabledCount === 0 && (
                <span style={{ fontSize: "11px", color: "#E03058" }}>No profiles selected</span>
              )}
            </div>
          </div>

          {/* Customize button */}
          <Button
            variant="tertiary"
            onClick={() => setShowOverrides(!showOverrides)}
            style={{ fontSize: "11px", padding: "4px 0", width: "100%", justifyContent: "center", marginTop: "4px" }}
          >
            {showOverrides ? "▲ Hide per-profile settings" : "▼ Customize per-profile captions & selection"}
          </Button>

          {/* Expandable per-profile overrides */}
          {showOverrides && (
            <div style={{ display: "flex", flexDirection: "column", gap: "8px", marginTop: "8px" }}>
              {channels.map((ch) => {
                const override = overrides[ch.id];
                if (!override) return null;

                return (
                  <div key={ch.id} style={{ border: `1px solid ${override.enabled ? "#E03058" : "#e0e0e0"}`, borderRadius: "8px", padding: "10px", background: override.enabled ? "#fef5f8" : "#fafafa", transition: "all 0.2s" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                      <span style={{ fontSize: "16px", flexShrink: 0 }}>{PLATFORM_ICONS[ch.type] || "🌐"}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: "12px", fontWeight: 600, color: "#1d1d1f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{ch.name}</div>
                        {ch.username && <div style={{ fontSize: "10px", color: "#86868b" }}>@{ch.username}</div>}
                      </div>
                      <ToggleControl checked={override.enabled} onChange={() => toggleChannel(ch.id)} __nextHasNoMarginBottom />
                    </div>

                    {override.enabled && (
                      <div style={{ marginTop: "8px" }}>
                        <TextareaControl
                          placeholder={templatePreview ? `Template:\n${templatePreview.slice(0, 100)}...` : `Caption for ${ch.type}...`}
                          value={override.caption}
                          onChange={(val: string) => setCaption(ch.id, val)}
                          rows={2}
                          __nextHasNoMarginBottom
                          style={{ fontSize: "11px" }}
                          help={!override.caption ? "Leave empty to use template" : undefined}
                        />
                        <Button
                          variant="tertiary"
                          disabled={generatingAi === ch.id}
                          style={{ fontSize: "11px", padding: "2px 8px", marginTop: "2px" }}
                          onClick={async () => {
                            setGeneratingAi(ch.id);
                            try {
                              const res = await fetch(
                                (window as any).viralyEditor.restUrl + "ai/generate-caption",
                                {
                                  method: "POST", credentials: "same-origin",
                                  headers: { "X-WP-Nonce": (window as any).viralyEditor.restNonce, "Content-Type": "application/json" },
                                  body: JSON.stringify({
                                    content: aiContext || postTitle || "social media post",
                                    command: "WriteNew",
                                    channelType: ch.type,
                                    tone: "Neutral",
                                    action: "caption",
                                  }),
                                }
                              );
                              const data = await res.json();
                              const caption = data.text || data.caption || data.content;
                              if (caption) setCaption(ch.id, caption);
                            } catch {}
                            setGeneratingAi(null);
                          }}
                        >
                          {generatingAi === ch.id ? "⏳ Generating..." : "✨ AI Generate"}
                        </Button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}

          {/* Draft notice */}
          {postStatus === "draft" && (
            <div style={{ marginTop: "10px", fontSize: "11px", color: "#86868b", textAlign: "center" }}>
              Will post when you hit <strong>Publish</strong>.
            </div>
          )}

          {/* Published: manual share controls */}
          {isPublished && (
            <div style={{ marginTop: "12px" }}>
              {shareResult && (
                <Notice status={shareResult.failed === 0 ? "success" : "warning"} isDismissible onDismiss={() => setShareResult(null)}>
                  <span style={{ fontSize: "12px" }}>
                    {shareResult.failed === 0
                      ? shareMode === "schedule"
                        ? `Scheduled to ${shareResult.sent} profile${shareResult.sent !== 1 ? "s" : ""}`
                        : `Shared to ${shareResult.sent} profile${shareResult.sent !== 1 ? "s" : ""}`
                      : `Sent ${shareResult.sent}, failed ${shareResult.failed}.`}
                  </span>
                </Notice>
              )}

              <RadioControl
                selected={shareMode}
                options={[{ label: "Share Now", value: "now" }, { label: "Schedule", value: "schedule" }]}
                onChange={(val: string) => setShareMode(val as "now" | "schedule")}
                __nextHasNoMarginBottom
              />

              {shareMode === "schedule" && (
                <div style={{ marginTop: "8px", border: "1px solid #e0e0e0", borderRadius: "8px", padding: "8px", background: "#fafafa" }}>
                  <DateTimePicker currentDate={scheduleDate || undefined} onChange={(date: string | null) => setScheduleDate(date)} is12Hour __nextRemoveHelpButton __nextRemoveResetButton />
                </div>
              )}

              <Button
                variant="primary"
                isBusy={sharing}
                disabled={sharing || enabledCount === 0 || (shareMode === "schedule" && !scheduleDate)}
                style={{ width: "100%", justifyContent: "center", backgroundColor: "#E03058", borderColor: "#E03058", marginTop: "10px" }}
                onClick={async () => {
                  setSharing(true);
                  setShareResult(null);
                  try {
                    const payload: any = { overrides: { globalEnabled, channels: overrides } };
                    if (shareMode === "schedule" && scheduleDate) payload.scheduledAt = scheduleDate;
                    const res = await fetch((window as any).viralyEditor.restUrl + "share/" + postId, {
                      method: "POST", credentials: "same-origin",
                      headers: { "X-WP-Nonce": (window as any).viralyEditor.restNonce, "Content-Type": "application/json" },
                      body: JSON.stringify(payload),
                    });
                    const data = await res.json();
                    if (data.success) setShareResult({ sent: data.sent, failed: data.failed });
                    else setShareResult({ sent: 0, failed: 1 });
                  } catch { setShareResult({ sent: 0, failed: 1 }); }
                  finally { setSharing(false); }
                }}
              >
                {sharing ? "Sharing..." : shareMode === "schedule"
                  ? `Schedule to ${enabledCount} Profile${enabledCount !== 1 ? "s" : ""}`
                  : `Share Now to ${enabledCount} Profile${enabledCount !== 1 ? "s" : ""}`}
              </Button>

              {enabledCount === 0 && (
                <p style={{ fontSize: "11px", color: "#E03058", marginTop: "6px", textAlign: "center" }}>Enable at least one profile</p>
              )}
            </div>
          )}

          {/* Settings link */}
          <div style={{ marginTop: "10px", textAlign: "center" }}>
            <a href={(window as any).viralyEditor.adminUrl + "?page=viraly&tab=autopost"} target="_blank" style={{ fontSize: "11px", color: "#86868b", textDecoration: "none" }}>
              Edit Blog to Social settings →
            </a>
          </div>
        </>
      )}
    </div>
  );
}
