import { formatMetricValue } from "./platformMetrics";

interface Props {
  platformType: string;
  data: any;
  isLoading: boolean;
  hasError: boolean;
}

interface StatItem {
  label: string;
  value: number | string;
  icon: string;
  change?: number;
}

function extractStats(platformType: string, data: any): StatItem[] {
  if (!data) return [];

  switch (platformType) {
    case "Instagram": {
      // Response: { data: { currentPeriod: {...}, previousPeriod: {...} }, error: null }
      const current = data?.data?.currentPeriod;
      const prev = data?.data?.previousPeriod;
      if (!current) return [];
      return [
        { label: "Reach", value: current.reach || 0, icon: "fa-solid fa-eye", change: prev ? current.reach - prev.reach : undefined },
        { label: "Engaged", value: current.accountsEngaged || 0, icon: "fa-solid fa-users", change: prev ? current.accountsEngaged - prev.accountsEngaged : undefined },
        { label: "Interactions", value: current.totalInteractions || 0, icon: "fa-solid fa-hand-pointer", change: prev ? current.totalInteractions - prev.totalInteractions : undefined },
        { label: "Views", value: current.views || 0, icon: "fa-solid fa-play" },
        { label: "Follows", value: current.follows || 0, icon: "fa-solid fa-user-plus" },
        { label: "Unfollows", value: current.unfollows || 0, icon: "fa-solid fa-user-minus" },
      ];
    }

    case "Facebook": {
      // Response: { current: { pageImpressions, pagePostsImpressions, ... }, previous: {...}, daily: [...] }
      const current = data?.current;
      const prev = data?.previous;
      if (!current) return [];
      return [
        { label: "Page Impressions", value: current.pageImpressions || 0, icon: "fa-solid fa-eye", change: prev ? (current.pageImpressions || 0) - (prev.pageImpressions || 0) : undefined },
        { label: "Post Impressions", value: current.pagePostsImpressions || 0, icon: "fa-solid fa-newspaper", change: prev ? (current.pagePostsImpressions || 0) - (prev.pagePostsImpressions || 0) : undefined },
        { label: "Engagement", value: current.pagePostEngagements || 0, icon: "fa-solid fa-hand-pointer", change: prev ? (current.pagePostEngagements || 0) - (prev.pagePostEngagements || 0) : undefined },
        { label: "Reactions", value: current.pageActionsPostReactionsTotal || 0, icon: "fa-solid fa-thumbs-up" },
        { label: "New Followers", value: current.pageDailyFollows || 0, icon: "fa-solid fa-user-plus" },
        { label: "Video Views", value: current.pageVideoViews || 0, icon: "fa-solid fa-play" },
      ];
    }

    case "YouTube": {
      // Response: { data: { views, likes, comments, ... }, error: null }
      const d = data?.data;
      if (!d) return [];
      return [
        { label: "Views", value: d.views || 0, icon: "fa-solid fa-play" },
        { label: "Watch Time (min)", value: d.estimatedMinutesWatched || 0, icon: "fa-solid fa-clock" },
        { label: "Likes", value: d.likes || 0, icon: "fa-solid fa-thumbs-up" },
        { label: "Subs Gained", value: d.subscribersGained || 0, icon: "fa-solid fa-user-plus" },
        { label: "Subs Lost", value: d.subscribersLost || 0, icon: "fa-solid fa-user-minus" },
        { label: "Comments", value: d.comments || 0, icon: "fa-solid fa-comment" },
      ];
    }

    case "Twitter": {
      // Response: { followersCount, friendsCount, statusesCount, favoritesCount, listedCount, ... }
      return [
        { label: "Followers", value: data.followersCount || 0, icon: "fa-solid fa-users" },
        { label: "Following", value: data.friendsCount || 0, icon: "fa-solid fa-user-group" },
        { label: "Tweets", value: data.statusesCount || 0, icon: "fa-solid fa-message" },
        { label: "Favourited", value: data.favoritesCount || 0, icon: "fa-solid fa-heart" },
        { label: "Listed", value: data.listedCount || 0, icon: "fa-solid fa-list" },
      ];
    }

    case "TikTok": {
      // Response: { followers, following, likes, videos, isVerified }
      return [
        { label: "Followers", value: data.followers || 0, icon: "fa-solid fa-users" },
        { label: "Following", value: data.following || 0, icon: "fa-solid fa-user-group" },
        { label: "Likes", value: data.likes || 0, icon: "fa-solid fa-heart" },
        { label: "Videos", value: data.videos || 0, icon: "fa-solid fa-video" },
      ];
    }

    case "Threads": {
      // Response: { data: [{ name, title, totalValue: { value }, values: [{ value, endTime }] }], error: null }
      const items = data?.data;
      if (!Array.isArray(items)) return [];
      const iconMap: Record<string, string> = {
        followers_count: "fa-solid fa-users",
        views: "fa-solid fa-eye",
        likes: "fa-solid fa-heart",
        replies: "fa-solid fa-reply",
        reposts: "fa-solid fa-retweet",
        quotes: "fa-solid fa-quote-right",
      };
      return items.map((item: any) => ({
        label: item.title || item.name || "Metric",
        value: item.totalValue?.value ?? item.values?.[item.values.length - 1]?.value ?? 0,
        icon: iconMap[item.name] || "fa-solid fa-chart-simple",
      })).slice(0, 6);
    }

    case "Bluesky": {
      // Response: { followers, follows, posts, lists, starterPacks }
      return [
        { label: "Followers", value: data.followers || 0, icon: "fa-solid fa-users" },
        { label: "Following", value: data.follows || 0, icon: "fa-solid fa-user-group" },
        { label: "Posts", value: data.posts || 0, icon: "fa-solid fa-message" },
        { label: "Lists", value: data.lists || 0, icon: "fa-solid fa-list" },
      ];
    }

    case "Mastodon": {
      // Response: { followers, follows, followRequests, statuses, locked, lastPostedAt, createdAt }
      return [
        { label: "Followers", value: data.followers || 0, icon: "fa-solid fa-users" },
        { label: "Following", value: data.follows || 0, icon: "fa-solid fa-user-group" },
        { label: "Posts", value: data.statuses || 0, icon: "fa-solid fa-message" },
        { label: "Follow Requests", value: data.followRequests || 0, icon: "fa-solid fa-user-clock" },
      ];
    }

    case "Pinterest": {
      // Response: { data: { "KEY": { summaryMetrics: { IMPRESSION, PIN_CLICK, SAVE, ... }, dailyMetrics: [...] } }, error: null }
      const wrapper = data?.data;
      if (!wrapper) return [];
      // Get the first key's summaryMetrics
      const firstKey = Object.keys(wrapper)[0];
      const metrics = wrapper[firstKey]?.summaryMetrics;
      if (!metrics) return [];
      const stats: StatItem[] = [];
      if (metrics.IMPRESSION != null) stats.push({ label: "Impressions", value: metrics.IMPRESSION, icon: "fa-solid fa-eye" });
      if (metrics.PIN_CLICK != null) stats.push({ label: "Pin Clicks", value: metrics.PIN_CLICK, icon: "fa-solid fa-mouse-pointer" });
      if (metrics.SAVE != null) stats.push({ label: "Saves", value: metrics.SAVE, icon: "fa-solid fa-bookmark" });
      if (metrics.OUTBOUND_CLICK != null) stats.push({ label: "Outbound Clicks", value: metrics.OUTBOUND_CLICK, icon: "fa-solid fa-arrow-up-right-from-square" });
      if (metrics.ENGAGEMENT != null) stats.push({ label: "Engagement", value: metrics.ENGAGEMENT, icon: "fa-solid fa-hand-pointer" });
      if (metrics.PROFILE_VISIT != null) stats.push({ label: "Profile Visits", value: metrics.PROFILE_VISIT, icon: "fa-solid fa-user" });
      return stats.slice(0, 6);
    }

    case "LinkedIn": {
      // Response: { data: [{ organizationalEntity, timeRange, followerGains: { organicFollowerGain, paidFollowerGain } }], error: null }
      const items = data?.data;
      if (!Array.isArray(items) || items.length === 0) return [];
      // Sum gains over the period
      let organicTotal = 0;
      let paidTotal = 0;
      items.forEach((item: any) => {
        organicTotal += item.followerGains?.organicFollowerGain || 0;
        paidTotal += item.followerGains?.paidFollowerGain || 0;
      });
      return [
        { label: "Organic Follower Gains", value: organicTotal, icon: "fa-solid fa-users" },
        { label: "Paid Follower Gains", value: paidTotal, icon: "fa-solid fa-bullhorn" },
        { label: "Total Gains", value: organicTotal + paidTotal, icon: "fa-solid fa-chart-line" },
      ];
    }

    default:
      return [];
  }
}

export default function AnalyticsProfileStats({ platformType, data, isLoading, hasError }: Props) {
  if (isLoading) {
    return (
      <div className="vr-flex vr-items-center vr-justify-center vr-gap-2 vr-py-6 vr-text-gray-400 vr-text-xs">
        <div className="vr-w-4 vr-h-4 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
        Loading profile analytics...
      </div>
    );
  }

  if (hasError || !data) return null;

  const stats = extractStats(platformType, data);
  if (stats.length === 0) return null;

  return (
    <div>
      <h4 className="vr-text-xs vr-font-semibold vr-text-gray-700 vr-mb-3">Profile Overview</h4>
      <div className={`vr-grid vr-gap-3 vr-grid-cols-2 ${stats.length === 3 ? "sm:vr-grid-cols-3" : stats.length <= 4 ? "sm:vr-grid-cols-4" : "sm:vr-grid-cols-3"}`}>
        {stats.map((stat, i) => (
          <div key={i} className="vr-text-center vr-py-4 vr-bg-gray-50 vr-rounded-lg">
            <i className={`${stat.icon} vr-text-gray-300 vr-mb-1.5`} style={{ fontSize: "13px" }} />
            <p className="vr-text-xl vr-font-bold vr-text-gray-900">
              {typeof stat.value === "number" ? formatMetricValue(stat.value) : stat.value}
            </p>
            <p className="vr-text-xs vr-text-gray-500">{stat.label}</p>
            {stat.change !== undefined && stat.change !== 0 && (
              <p className={`vr-text-xs vr-font-medium vr-mt-0.5 ${stat.change > 0 ? "vr-text-emerald-600" : "vr-text-red-500"}`}>
                {stat.change > 0 ? "+" : ""}{formatMetricValue(stat.change)}
              </p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
