"use client";

import { useMemo, useState } from "react";
import type { MarketingMetaConnection, MetaSyncStatus, SocialInsight } from "@/lib/marketing";
import { formatCompactNumber } from "@/lib/marketing/labels";

type SocialPanelProps = {
  insights: SocialInsight[];
  metaConnection: MarketingMetaConnection | null;
  metaSyncStatus: MetaSyncStatus;
  latestSyncMessage?: string | null;
  onConnect: (input: { accountId: string; pageId: string; pageName: string; pageAccessToken: string; tokenExpiresAt?: string | null }) => Promise<void>;
  onDisconnect: () => Promise<void>;
  onSync: () => Promise<void>;
  isSyncing: boolean;
};

function statusLabel(status: MetaSyncStatus): string {
  if (status === "ready") {
    return "Conectada";
  }

  if (status === "syncing") {
    return "Sincronizando";
  }

  if (status === "error") {
    return "Error";
  }

  return "Desconectada";
}

function statusClassname(status: MetaSyncStatus): string {
  if (status === "ready") {
    return "bg-benell-green/15 text-benell-green";
  }

  if (status === "syncing") {
    return "bg-benell-amber/20 text-benell-amber";
  }

  if (status === "error") {
    return "bg-benell-red/15 text-benell-red";
  }

  return "bg-benell-surface-muted text-benell-text-soft";
}

function formatDeltaPercent(current: number, previous: number | null): string {
  if (previous === null || previous <= 0) {
    return "n/d";
  }

  const delta = ((current - previous) / previous) * 100;
  const sign = delta > 0 ? "+" : "";
  return `${sign}${delta.toFixed(1)}%`;
}

export default function SocialPanel({
  insights,
  metaConnection,
  metaSyncStatus,
  latestSyncMessage,
  onConnect,
  onDisconnect,
  onSync,
  isSyncing,
}: SocialPanelProps) {
  const [range, setRange] = useState<"7d" | "30d">("7d");
  const [isMetaModalOpen, setIsMetaModalOpen] = useState(false);
  const [draft, setDraft] = useState({
    accountId: metaConnection?.accountId ?? "",
    pageId: metaConnection?.pageId ?? "",
    pageName: metaConnection?.pageName ?? "",
    pageAccessToken: "",
    tokenExpiresAt: metaConnection?.tokenExpiresAt?.slice(0, 10) ?? "",
  });

  const byChannel = useMemo(() => {
    const map = new Map<string, SocialInsight>();
    for (const insight of insights) {
      map.set(`${insight.channel}:${insight.range}`, insight);
    }

    const instagram = map.get(`instagram:${range}`) ?? null;
    const facebook = map.get(`facebook:${range}`) ?? null;

    return {
      instagram,
      facebook,
    };
  }, [insights, range]);

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
      <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
        <div>
          <h2 className="text-h2 font-semibold">Social Media</h2>
          <p className="text-label mt-1 text-benell-text-soft">Métricas calculadas en backend + sync diario 06:00 y manual con Meta.</p>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <span className={`rounded-pill px-3 py-2 text-label font-semibold ${statusClassname(metaSyncStatus)}`}>
            Meta: {statusLabel(metaSyncStatus)}
          </span>
          <div className="rounded-pill border border-benell-stroke bg-white p-1">
            <button
              type="button"
              onClick={() => setRange("7d")}
              className={`rounded-pill px-3 py-1 text-label font-semibold ${range === "7d" ? "bg-benell-brown text-white" : "text-benell-text-soft"}`}
            >
              7 días
            </button>
            <button
              type="button"
              onClick={() => setRange("30d")}
              className={`rounded-pill px-3 py-1 text-label font-semibold ${range === "30d" ? "bg-benell-brown text-white" : "text-benell-text-soft"}`}
            >
              30 días
            </button>
          </div>
          <button
            type="button"
            onClick={() => setIsMetaModalOpen(true)}
            className="rounded-pill border border-benell-stroke bg-white px-3 py-2 text-label font-semibold text-benell-text"
          >
            Configurar Meta
          </button>
          <button
            type="button"
            disabled={isSyncing || !metaConnection}
            onClick={() => {
              void onSync();
            }}
            className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
          >
            {isSyncing ? "Sincronizando..." : "Sync ahora"}
          </button>
        </div>
      </div>

      {metaConnection ? (
        <p className="text-caption mb-3 text-benell-text-soft">
          Página: {metaConnection.pageName} ({metaConnection.pageId}) · Última sync: {metaConnection.lastSyncedAt ? new Date(metaConnection.lastSyncedAt).toLocaleString("es-MX") : "nunca"}
        </p>
      ) : (
        <p className="text-caption mb-3 text-benell-text-soft">Sin conexión de Meta configurada todavía.</p>
      )}

      {latestSyncMessage ? <p className="text-caption mb-3 text-benell-text-soft">{latestSyncMessage}</p> : null}

      <div className="grid gap-3 md:grid-cols-2">
        {(["instagram", "facebook"] as const).map((channel) => {
          const insight = byChannel[channel];
          const metricRows = [
            {
              key: "reach",
              label: "Reach",
              current: insight?.reach ?? 0,
              previous: insight?.previousReach ?? null,
            },
            {
              key: "views",
              label: "Views",
              current: insight?.impressions ?? 0,
              previous: insight?.previousImpressions ?? null,
            },
            {
              key: "interactions",
              label: "Interacciones",
              current: insight?.interactions ?? 0,
              previous: insight?.previousInteractions ?? null,
            },
            {
              key: "followers_delta",
              label: "Delta followers",
              current: insight?.followerDelta ?? 0,
              previous: insight?.previousFollowerDelta ?? null,
            },
          ].filter((row) => row.current > 0 || (row.previous ?? 0) > 0);

          return (
            <article key={channel} className="rounded-xl border border-benell-stroke bg-white p-4">
              <p className="text-label font-semibold text-benell-text-soft">{channel === "instagram" ? "Instagram" : "Facebook"}</p>
              <p className="text-h3 mt-1 font-semibold text-tabular">{formatCompactNumber(insight?.followersEnd ?? 0)} followers</p>
              <p className="text-label mt-1 text-benell-text-soft">
                Inicio: {formatCompactNumber(insight?.followersStart ?? 0)} · Growth: {(insight?.followerGrowthPct ?? 0).toFixed(2)}%
              </p>
              <p className="text-label mt-2 text-benell-text-soft">
                Engagement rate: {(insight?.engagementRatePct ?? 0).toFixed(2)}%
                {insight ? ` · Vs prev: ${formatDeltaPercent(insight.engagementRatePct, insight.previousEngagementRatePct)}` : ""}
              </p>
              {metricRows.length > 0 ? (
                <div className="mt-2 space-y-1">
                  {metricRows.map((row) => (
                    <p key={row.key} className="text-label text-benell-text-soft">
                      {row.label}: {formatCompactNumber(row.current)}
                      {row.previous !== null ? ` · Prev: ${formatCompactNumber(row.previous)} (${formatDeltaPercent(row.current, row.previous)})` : ""}
                    </p>
                  ))}
                </div>
              ) : (
                <p className="text-label mt-1 text-benell-text-soft">Sin métricas con valor en este rango.</p>
              )}
            </article>
          );
        })}
      </div>

      {isMetaModalOpen ? (
        <div className="fixed inset-0 z-50">
          <button
            type="button"
            className="absolute inset-0 bg-black/30"
            onClick={() => setIsMetaModalOpen(false)}
            aria-label="Cerrar modal"
          />
          <div className="absolute left-1/2 top-1/2 w-[92vw] max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-xl">
            <h3 className="text-h3 font-semibold">Conexión de Meta</h3>
            <p className="text-body mt-2 text-benell-text-soft">Configura cuenta/página y token para sincronizar métricas reales.</p>

            <div className="mt-4 grid grid-cols-1 gap-2">
              <input
                value={draft.accountId}
                onChange={(event) => setDraft((prev) => ({ ...prev, accountId: event.target.value }))}
                placeholder="Account ID"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              />
              <input
                value={draft.pageId}
                onChange={(event) => setDraft((prev) => ({ ...prev, pageId: event.target.value }))}
                placeholder="Page ID"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              />
              <input
                value={draft.pageName}
                onChange={(event) => setDraft((prev) => ({ ...prev, pageName: event.target.value }))}
                placeholder="Page name"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              />
              <input
                value={draft.pageAccessToken}
                onChange={(event) => setDraft((prev) => ({ ...prev, pageAccessToken: event.target.value }))}
                placeholder="Page access token"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              />
              <input
                type="date"
                value={draft.tokenExpiresAt}
                onChange={(event) => setDraft((prev) => ({ ...prev, tokenExpiresAt: event.target.value }))}
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
              />
            </div>

            <div className="mt-4 flex flex-wrap justify-end gap-2">
              <button
                type="button"
                onClick={() => {
                  void onDisconnect();
                  setIsMetaModalOpen(false);
                }}
                className="rounded-pill border border-benell-stroke bg-white px-3 py-2 text-label font-semibold"
              >
                Desconectar
              </button>
              <button
                type="button"
                onClick={() => {
                  void onConnect({
                    accountId: draft.accountId,
                    pageId: draft.pageId,
                    pageName: draft.pageName,
                    pageAccessToken: draft.pageAccessToken,
                    tokenExpiresAt: draft.tokenExpiresAt || null,
                  });
                  setIsMetaModalOpen(false);
                }}
                className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
              >
                Guardar conexión
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </section>
  );
}
