import { useQuery } from "@tanstack/react-query";
import DonutChart from "../DonutChart";
import { formatMetricValue } from "../platformMetrics";

interface Props {
  channelId: string;
}

async function fetchSub(channelId: string, sub: string) {
  const baseUrl = (window as any).viralyWP.restUrl.replace(/\/+$/, "");
  const nonce = (window as any).viralyWP.restNonce;
  const res = await fetch(`${baseUrl}/analytics/youtube/${channelId}/${sub}?timeframe=Last30Days`, {
    credentials: "same-origin",
    headers: { "X-WP-Nonce": nonce, "Content-Type": "application/json" },
  });
  try { return await res.json(); } catch { return null; }
}

const DEVICE_COLORS: Record<string, string> = {
  MOBILE: "#3B82F6", DESKTOP: "#10B981", TABLET: "#9333EA",
  TV: "#EF4444", GAME_CONSOLE: "#F59E0B",
};

const DEVICE_LABELS: Record<string, string> = {
  MOBILE: "Mobile", DESKTOP: "Desktop", TABLET: "Tablet",
  TV: "TV", GAME_CONSOLE: "Console",
};

const SOURCE_ICONS: Record<string, string> = {
  YT_SEARCH: "fa-solid fa-magnifying-glass",
  RELATED_VIDEO: "fa-solid fa-film",
  EXT_URL: "fa-solid fa-arrow-up-right-from-square",
  NOTIFICATION: "fa-solid fa-bell",
  SUBSCRIBER: "fa-solid fa-rss",
  PLAYLIST: "fa-solid fa-list",
  ADVERTISING: "fa-solid fa-bullhorn",
  SHORTS: "fa-solid fa-mobile-screen",
  HASHTAGS: "fa-solid fa-hashtag",
};

const SOURCE_LABELS: Record<string, string> = {
  YT_SEARCH: "YouTube Search", RELATED_VIDEO: "Suggested Videos",
  EXT_URL: "External", NOTIFICATION: "Notifications",
  SUBSCRIBER: "Subscribers", PLAYLIST: "Playlists",
  ADVERTISING: "Advertising", SHORTS: "Shorts",
  HASHTAGS: "Hashtags", YT_CHANNEL: "Channel Page",
  YT_OTHER_PAGE: "Other Pages", END_SCREEN: "End Screens",
  NO_LINK_EMBEDDED: "Embedded", NO_LINK_OTHER: "Direct/Unknown",
};

export default function YouTubeAnalytics({ channelId }: Props) {
  const { data: deviceData, isLoading: deviceLoading } = useQuery({
    queryKey: ["yt-device", channelId],
    queryFn: () => fetchSub(channelId, "device"),
    staleTime: 600_000,
  });

  const { data: trafficData, isLoading: trafficLoading } = useQuery({
    queryKey: ["yt-traffic", channelId],
    queryFn: () => fetchSub(channelId, "traffic-source"),
    staleTime: 600_000,
  });

  const { data: demoData, isLoading: demoLoading } = useQuery({
    queryKey: ["yt-demographics", channelId],
    queryFn: () => fetchSub(channelId, "demographics"),
    staleTime: 600_000,
  });

  const { data: geoData, isLoading: geoLoading } = useQuery({
    queryKey: ["yt-geo", channelId],
    queryFn: () => fetchSub(channelId, "geo"),
    staleTime: 600_000,
  });

  // Device breakdown donuts
  const devices = buildDeviceData(deviceData);

  // Traffic sources
  const sources = buildTrafficSources(trafficData);

  // Demographics
  const demographics = buildDemographics(demoData);

  // Top countries
  const countries = buildCountries(geoData);

  return (
    <div className="vr-space-y-6">
      {/* Device Breakdown */}
      {!deviceLoading && devices.views.length > 0 && (
        <div>
          <h4 className="vr-text-xs vr-font-semibold vr-text-gray-700 vr-mb-3">Device Breakdown</h4>
          <div className="vr-grid vr-grid-cols-2 vr-gap-4">
            <DonutChart
              data={devices.views}
              title="Views by Device"
              centerValue={formatMetricValue(devices.totalViews)}
              centerLabel="Total Views"
              size={160}
            />
            <DonutChart
              data={devices.watchTime}
              title="Watch Time by Device"
              centerValue={formatMetricValue(devices.totalWatchTime) + "m"}
              centerLabel="Total Minutes"
              size={160}
            />
          </div>
        </div>
      )}

      {/* Traffic Sources */}
      {!trafficLoading && sources.length > 0 && (
        <div>
          <h4 className="vr-text-xs vr-font-semibold vr-text-gray-700 vr-mb-3">Traffic Sources</h4>
          <div className="vr-space-y-2">
            {sources.slice(0, 10).map((source, i) => (
              <div key={i} className="vr-flex vr-items-center vr-gap-3">
                <div className="vr-w-5 vr-flex vr-justify-center vr-flex-shrink-0">
                  <i className={SOURCE_ICONS[source.key] || "fa-solid fa-globe"} style={{ fontSize: "11px", color: "#9ca3af" }} />
                </div>
                <span className="vr-text-xs vr-text-gray-700 vr-w-32 vr-truncate vr-flex-shrink-0">
                  {SOURCE_LABELS[source.key] || source.key}
                </span>
                <div className="vr-flex-1 vr-h-3.5 vr-bg-gray-100 vr-rounded-full vr-overflow-hidden">
                  <div
                    className="vr-h-full vr-rounded-full"
                    style={{ width: `${Math.max(source.pct, 2)}%`, backgroundColor: "#E03058" }}
                  />
                </div>
                <span className="vr-text-xs vr-text-gray-500 vr-w-16 vr-text-right vr-flex-shrink-0">
                  {formatMetricValue(source.views)} ({source.pct.toFixed(0)}%)
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="vr-grid vr-grid-cols-1 sm:vr-grid-cols-2 vr-gap-5">
        {/* Demographics */}
        {!demoLoading && demographics.length > 0 && (
          <div>
            <h5 className="vr-text-xs vr-font-semibold vr-text-gray-600 vr-mb-2">Audience Demographics</h5>
            <div className="vr-space-y-1.5">
              {demographics.map((d, i) => (
                <div key={i} className="vr-flex vr-items-center vr-gap-2">
                  <span className="vr-text-xs vr-text-gray-600 vr-w-16 vr-text-right vr-flex-shrink-0">{d.label}</span>
                  <div className="vr-flex-1 vr-h-3.5 vr-bg-gray-100 vr-rounded-full vr-overflow-hidden">
                    <div className="vr-h-full vr-rounded-full" style={{ width: `${Math.max(d.pct, 2)}%`, backgroundColor: "#3B82F6" }} />
                  </div>
                  <span className="vr-text-xs vr-text-gray-500 vr-w-10 vr-flex-shrink-0">{d.pct.toFixed(1)}%</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Top Countries */}
        {!geoLoading && countries.length > 0 && (
          <div>
            <h5 className="vr-text-xs vr-font-semibold vr-text-gray-600 vr-mb-2">Top Countries</h5>
            <div className="vr-space-y-1.5">
              {countries.slice(0, 8).map((c, i) => (
                <div key={i} className="vr-flex vr-items-center vr-gap-2">
                  <span className="vr-text-xs vr-text-gray-600 vr-w-16 vr-text-right vr-flex-shrink-0 vr-truncate">{c.label}</span>
                  <div className="vr-flex-1 vr-h-3.5 vr-bg-gray-100 vr-rounded-full vr-overflow-hidden">
                    <div className="vr-h-full vr-rounded-full" style={{ width: `${Math.max(c.pct, 2)}%`, backgroundColor: "#E03058" }} />
                  </div>
                  <span className="vr-text-xs vr-text-gray-500 vr-w-12 vr-flex-shrink-0 vr-text-right">{formatMetricValue(c.views)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function buildDeviceData(data: any) {
  const items = data?.data;
  if (!Array.isArray(items)) return { views: [], watchTime: [], totalViews: 0, totalWatchTime: 0 };

  const totalViews = items.reduce((s: number, d: any) => s + (d.views || 0), 0);
  const totalWatchTime = items.reduce((s: number, d: any) => s + (d.estimatedMinutesWatched || 0), 0);

  const views = items.map((d: any) => ({
    label: DEVICE_LABELS[d.deviceType] || d.deviceType || "Unknown",
    value: d.views || 0,
    color: DEVICE_COLORS[d.deviceType] || "#6b7280",
  })).filter((d: any) => d.value > 0);

  const watchTime = items.map((d: any) => ({
    label: DEVICE_LABELS[d.deviceType] || d.deviceType || "Unknown",
    value: d.estimatedMinutesWatched || 0,
    color: DEVICE_COLORS[d.deviceType] || "#6b7280",
  })).filter((d: any) => d.value > 0);

  return { views, watchTime, totalViews, totalWatchTime };
}

function buildTrafficSources(data: any) {
  const items = data?.data;
  if (!Array.isArray(items)) return [];

  const totalViews = items.reduce((s: number, d: any) => s + (d.views || 0), 0);
  return items
    .map((d: any) => ({
      key: d.trafficSource || d.insightTrafficSourceType || "OTHER",
      views: d.views || 0,
      pct: totalViews > 0 ? ((d.views || 0) / totalViews) * 100 : 0,
    }))
    .sort((a: any, b: any) => b.views - a.views);
}

function buildDemographics(data: any) {
  const items = data?.data;
  if (!Array.isArray(items)) return [];

  return items
    .map((d: any) => ({
      label: d.dimensionKey || "Unknown",
      pct: d.viewerPercentage || 0,
    }))
    .sort((a: any, b: any) => b.pct - a.pct);
}

function buildCountries(data: any) {
  const items = data?.data;
  if (!Array.isArray(items)) return [];

  const totalViews = items.reduce((s: number, d: any) => s + (d.views || 0), 0);
  return items
    .map((d: any) => ({
      label: d.countryCode || "Unknown",
      views: d.views || 0,
      pct: totalViews > 0 ? ((d.views || 0) / totalViews) * 100 : 0,
    }))
    .sort((a: any, b: any) => b.views - a.views);
}
