import DonutChart from "../DonutChart";
import MetricsOverTimeChart from "../MetricsOverTimeChart";
import { formatMetricValue } from "../platformMetrics";

interface Props {
  profileData: any;
}

const REACTION_COLORS: Record<string, string> = {
  Like: "#3B82F6", Love: "#EF4444", Wow: "#F59E0B",
  Haha: "#10B981", Sorry: "#8B5CF6", Anger: "#DC2626",
};

export default function FacebookAnalytics({ profileData }: Props) {
  if (!profileData?.current) return null;

  const current = profileData.current;
  const daily = profileData.daily;

  // Reactions breakdown
  const reactions = [
    { label: "Like", value: current.pageActionsPostReactionsLikeTotal || 0, color: REACTION_COLORS.Like },
    { label: "Love", value: current.pageActionsPostReactionsLoveTotal || 0, color: REACTION_COLORS.Love },
    { label: "Wow", value: current.pageActionsPostReactionsWowTotal || 0, color: REACTION_COLORS.Wow },
    { label: "Haha", value: current.pageActionsPostReactionsHahaTotal || 0, color: REACTION_COLORS.Haha },
    { label: "Sorry", value: current.pageActionsPostReactionsSorryTotal || 0, color: REACTION_COLORS.Sorry },
    { label: "Anger", value: current.pageActionsPostReactionsAngerTotal || 0, color: REACTION_COLORS.Anger },
  ].filter((r) => r.value > 0);

  const totalReactions = current.pageActionsPostReactionsTotal || reactions.reduce((s, r) => s + r.value, 0);

  // Organic vs Paid
  const organicReach = current.pagePostsImpressionsOrganicUnique || 0;
  const paidReach = current.pagePostsImpressionsPaidUnique || 0;
  const organicPaid = [
    { label: "Organic", value: organicReach, color: "#6B7280" },
    { label: "Paid", value: paidReach, color: "#3B82F6" },
  ].filter((s) => s.value > 0);

  // Video stats
  const videoViews = current.pageVideoViews || 0;
  const videoWatchTime = current.pageVideoViewTime || 0;
  const videoCompletion = videoViews > 0 ? ((current.pageVideoCompleteViews30s || 0) / videoViews * 100) : 0;

  // Daily time series
  const timeSeries = buildDailyTimeSeries(daily);

  return (
    <div className="vr-space-y-6">
      {/* Follower Growth Trend */}
      {timeSeries.length >= 3 && (
        <MetricsOverTimeChart
          data={timeSeries}
          metrics={[
            { key: "follows", label: "New Followers", color: "#22c55e" },
            { key: "unfollows", label: "Unfollows", color: "#ef4444" },
            { key: "impressions", label: "Impressions", color: "#3b82f6" },
            { key: "engagement", label: "Engagement", color: "#f59e0b" },
          ]}
          title="Follower Growth & Engagement"
          description="Daily breakdown of follower changes and engagement"
        />
      )}

      <div className="vr-grid vr-grid-cols-1 sm:vr-grid-cols-2 lg:vr-grid-cols-3 vr-gap-5">
        {/* Reactions Breakdown */}
        {reactions.length > 0 && (
          <DonutChart
            data={reactions}
            title="Reactions Breakdown"
            centerValue={formatMetricValue(totalReactions)}
            centerLabel="Total"
            size={160}
          />
        )}

        {/* Organic vs Paid */}
        {organicPaid.length > 0 && (
          <DonutChart
            data={organicPaid}
            title="Reach: Organic vs Paid"
            centerValue={formatMetricValue(organicReach + paidReach)}
            centerLabel="Total Reach"
            size={160}
          />
        )}

        {/* Video Performance */}
        {videoViews > 0 && (
          <div>
            <h5 className="vr-text-xs vr-font-semibold vr-text-gray-600 vr-mb-3">Video Performance</h5>
            <div className="vr-space-y-3">
              <div className="vr-flex vr-items-center vr-justify-between vr-text-xs">
                <span className="vr-text-gray-500">Total Views</span>
                <span className="vr-font-bold vr-text-gray-900">{formatMetricValue(videoViews)}</span>
              </div>
              <div className="vr-flex vr-items-center vr-justify-between vr-text-xs">
                <span className="vr-text-gray-500">Watch Time</span>
                <span className="vr-font-bold vr-text-gray-900">{formatMetricValue(Math.round(videoWatchTime / 60))} min</span>
              </div>
              <div className="vr-flex vr-items-center vr-justify-between vr-text-xs">
                <span className="vr-text-gray-500">30s Completion</span>
                <span className="vr-font-bold vr-text-gray-900">{videoCompletion.toFixed(1)}%</span>
              </div>
              <div className="vr-flex vr-items-center vr-justify-between vr-text-xs">
                <span className="vr-text-gray-500">Click-to-Play</span>
                <span className="vr-font-bold vr-text-gray-900">{formatMetricValue(current.pageVideoViewsClickToPlay || 0)}</span>
              </div>
              <div className="vr-flex vr-items-center vr-justify-between vr-text-xs">
                <span className="vr-text-gray-500">Autoplay</span>
                <span className="vr-font-bold vr-text-gray-900">{formatMetricValue(current.pageVideoViewsAutoplayed || 0)}</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function buildDailyTimeSeries(daily: any[]) {
  if (!Array.isArray(daily)) return [];
  return daily
    .map((d: any) => ({
      date: d.date || "",
      follows: d.pageDailyFollows || 0,
      unfollows: d.pageDailyUnfollows || 0,
      impressions: d.pageImpressions || 0,
      engagement: d.pagePostEngagements || 0,
    }))
    .slice(-60); // Max 60 points
}
