import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/dashboard/ui/card";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/dashboard/ui/tooltip";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/dashboard/ui/select";
import {
  Instagram,
  Loader2,
  Users,
  DollarSign,
  Eye,
  Repeat,
  MousePointer,
  BarChart,
  Target,
  ShoppingCart,
  MessageCircle,
  Hash,
} from "lucide-react";
import { Button } from "@/components/dashboard/ui/button";
import { Skeleton } from "@/components/dashboard/ui/skeleton";

// Helper functions for formatting
const formatCurrency = (value, decimalPlaces = 2) =>
  new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: decimalPlaces,
    maximumFractionDigits: decimalPlaces,
  }).format(value || 0);

const formatNumber = (value, decimalPlaces = 0) => {
  return new Intl.NumberFormat("en-US", {
    minimumFractionDigits: decimalPlaces,
    maximumFractionDigits: decimalPlaces,
  }).format(value || 0);
};

const formatPercent = (value, decimalPlaces = 2) =>
  `${(value || 0).toFixed(decimalPlaces)}%`;

const summaryCard = (label, value, options = {}) => {
  const {
    isMonetary = false,
    isPercentage = false,
    decimalPlaces = 0,
    icon: Icon,
    iconColor,
  } = options;

  let displayValue;
  if (isMonetary) {
    displayValue = formatCurrency(value, decimalPlaces);
  } else if (isPercentage) {
    displayValue = formatPercent(value, decimalPlaces);
  } else {
    displayValue = formatNumber(value, decimalPlaces);
  }

  return (
    <Card className="h-full">
      <CardContent className="pt-6 h-full">
        <div className="flex justify-between items-start">
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-muted-foreground">{label}</p>
            <p className="text-2xl font-bold">{displayValue}</p>
          </div>
          {Icon && (
            <Icon className={`h-5 w-5 flex-shrink-0 ml-2 ${iconColor || "text-blue-500"}`} />
          )}
        </div>
      </CardContent>
    </Card>
  );
};

const MetricCell = ({ value, label, sublabel, isMonetary = false, isPercentage = false, decimalPlaces = 0 }) => {
  const formattedValue = isMonetary
    ? formatCurrency(value, decimalPlaces)
    : isPercentage
    ? formatPercent(value, decimalPlaces)
    : formatNumber(value, decimalPlaces);

  return (
    <td className="p-2 text-center align-top">
      <div className="text-blue-600 dark:text-blue-400 text-lg font-semibold">
        {formattedValue}
      </div>
      {(label || sublabel) && (
        <div className="text-muted-foreground text-sm">
          {label || sublabel}
        </div>
      )}
    </td>
  );
};

const getActionValue = (campaign, actionType) => {
  if (actionType === "impressions" || actionType === "reach") {
    return campaign.metrics[actionType] || 0;
  }

  const actions = campaign.metrics.actions;
  if (Array.isArray(actions)) {
    const action = actions.find((a) => a.action_type === actionType);
    return action ? parseInt(action.value) || 0 : 0;
  }

  return 0;
};

const CampaignName = ({ name }) => {
  if (name.startsWith("Instagram post: ")) {
    return (
      <div className="flex items-center space-x-2">
        <Instagram className="w-4 h-4" />
        <span>{name.replace("Instagram post: ", "")}</span>
      </div>
    );
  }
  return <span>{name}</span>;
};

const getObjectiveAction = (campaignObjective) => {
  const objectiveMap = {
    OUTCOME_AWARENESS: { action_type: "impressions", label: "Impressions" },
    OUTCOME_ENGAGEMENT: { action_type: "post_engagement", label: "Post Engagements" },
    OUTCOME_TRAFFIC: { action_type: "link_click", label: "Link Clicks" },
    OUTCOME_LEADS: { action_type: "lead", label: "Leads" },
    OUTCOME_SALES: { action_type: "purchase", label: "Purchases" },
    MESSAGES: { action_type: "messages", label: "Messages" },
  };

  return objectiveMap[campaignObjective] || { action_type: "link_click", label: "Link Clicks" };
};

const calculateBudget = (campaign) => {
  if (campaign.daily_budget) {
    return { value: campaign.daily_budget / 100, type: "day" };
  }
  if (campaign.lifetime_budget) {
    return { value: campaign.lifetime_budget / 100, type: "lifetime" };
  }

  const adsets = campaign.adsets?.data || [];
  const dailyTotal = adsets.reduce((sum, adset) => sum + (adset.daily_budget || 0), 0);
  const lifetimeTotal = adsets.reduce((sum, adset) => sum + (adset.lifetime_budget || 0), 0);

  if (dailyTotal > 0) return { value: dailyTotal / 100, type: "day" };
  if (lifetimeTotal > 0) return { value: lifetimeTotal / 100, type: "lifetime" };

  return { value: 0, type: "day" };
};

const processMetrics = (campaign) => {
  const insights = campaign.insights?.data?.[0] || {};
  const spend = parseFloat(insights.spend || 0);
  const impressions = parseInt(insights.impressions || 0);
  const clicks = parseInt(insights.clicks || 0);
  const reach = parseInt(insights.reach || 0);
  const cpc = parseFloat(insights.cpc || 0);
  const ctr = parseFloat(insights.ctr || 0);
  const cpm = parseFloat(insights.cpm || 0);
  const frequency = parseFloat(insights.frequency || 0);

  // Purchase value and total purchases
  const purchaseValue = (insights.action_values || [])
    .filter(({ action_type }) => action_type === "purchase")
    .reduce((sum, { value }) => sum + parseFloat(value || 0), 0);

  const totalPurchases = (insights.actions || [])
    .filter(({ action_type }) => action_type === "purchase")
    .reduce((sum, { value }) => sum + parseInt(value || 0), 0);

  // Aggregate unique actions
  const actionMap = new Map();
  (insights.actions || []).forEach(({ action_type, value }) => {
    const currentValue = actionMap.get(action_type) || 0;
    actionMap.set(action_type, currentValue + parseInt(value || 0));
  });

  const actions = Array.from(actionMap.entries()).map(([action_type, value]) => ({
    action_type,
    value,
  }));

  // Map of cost per action
  const costPerActionMap = new Map();
  (insights.cost_per_action_type || []).forEach(({ action_type, value }) => {
    costPerActionMap.set(action_type, parseFloat(value || 0));
  });

  // Total post engagements
  const totalPostEngagements = actionMap.get("post_engagement") || 0;

  return {
    spend,
    impressions,
    clicks,
    reach,
    frequency,
    ctr,
    cpm,
    cpc,
    actions,
    costPerActionMap,
    purchaseValue,
    totalPurchases,
    totalPostEngagements,
  };
};

const processCampaignData = (campaign) => {
  const metrics = processMetrics(campaign);
  const budget = calculateBudget(campaign);
  const { action_type, label } = getObjectiveAction(campaign.objective);

  // Get cost per result from costPerActionMap
  const costPerResult = metrics.costPerActionMap.get(action_type) || 0;

  return {
    id: campaign.id,
    name: campaign.name,
    status: campaign.status,
    objective: label,
    objectiveActionType: action_type,
    budget: budget.value,
    budgetType: budget.type,
    metrics: {
      ...metrics,
      costPerResult,
    },
  };
};

const SkeletonMetricCard = () => (
  <Card className="h-full">
    <CardContent className="pt-6 h-full">
      <div className="flex justify-between items-start">
        <div className="flex-1 min-w-0">
          <Skeleton className="h-4 w-24 mb-4 bg-muted" />
          <div className="flex items-baseline gap-2">
            <Skeleton className="h-8 w-20 bg-muted" />
          </div>
        </div>
        <Skeleton className="h-5 w-5 rounded-full bg-muted" />
      </div>
    </CardContent>
  </Card>
);

const SkeletonTable = () => (
  <div className="h-full max-h-[400px] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600 pr-2">
    <table className="min-w-full">
      <thead>
        <tr className="border-b border-gray-200 dark:border-gray-800">
          <th className="p-2 sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10">
            <Skeleton className="h-4 w-32 bg-muted" />
          </th>
          {[...Array(8)].map((_, i) => (
            <th key={i} className="p-2 text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10">
              <Skeleton className="h-4 w-20 mx-auto bg-muted" />
            </th>
          ))}
        </tr>
      </thead>
      <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
        {[...Array(5)].map((_, rowIndex) => (
          <tr key={rowIndex} className="hover:bg-muted/50 transition-colors">
            <td className="p-2">
              <div className="flex items-center gap-2">
                <Skeleton className="h-4 w-4 bg-muted" />
                <div className="space-y-2">
                  <Skeleton className="h-4 w-48 bg-muted" />
                  <Skeleton className="h-3 w-64 bg-muted" />
                  <Skeleton className="h-3 w-32 bg-muted" />
                </div>
              </div>
            </td>
            {[...Array(8)].map((_, colIndex) => (
              <td key={colIndex} className="p-2 text-center">
                <div className="flex flex-col items-center gap-1">
                  <Skeleton className="h-4 w-16 bg-muted" />
                  <Skeleton className="h-3 w-24 bg-muted" />
                </div>
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const MetaCampaigns = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [campaigns, setCampaigns] = useState([]);
  const [timeframe, setTimeframe] = useState("7");
  const [summaryMetrics, setSummaryMetrics] = useState(null);
  const [sortConfig, setSortConfig] = useState({
    key: "spend",
    direction: "desc",
  });

  const handleSort = (key) => {
    setSortConfig((prev) => ({
      key,
      direction: prev.key === key && prev.direction === "desc" ? "asc" : "desc",
    }));
  };

  const computeDateRange = (timeframe) => {
    // Create date in Eastern Time
    const now = new Date();
    const easternTime = new Date(
      now.toLocaleString("en-US", { timeZone: "America/New_York" })
    );
    easternTime.setHours(0, 0, 0, 0); // Set to start of day

    let sinceDate, untilDate;

    if (timeframe === "today") {
      // For today, both dates should be the current date in Eastern Time
      sinceDate = untilDate = new Date(easternTime);
    } else {
      // For other periods, calculate the date range
      untilDate = new Date(easternTime);
      untilDate.setDate(untilDate.getDate() - 1); // Yesterday

      sinceDate = new Date(untilDate);
      sinceDate.setDate(sinceDate.getDate() - parseInt(timeframe) + 1);
    }

    return {
      since: sinceDate.toISOString().split("T")[0],
      until: untilDate.toISOString().split("T")[0],
    };
  };

  useEffect(() => {
    const fetchMetaAdsData = async () => {
      try {
        setLoading(true);
        setError(null);

        const { since, until } = computeDateRange(timeframe);

        const [campaignData, accountInsights] = await Promise.all([
          fetch(`/api/meta/campaigns?since=${since}&until=${until}`),
          fetch(`/api/meta/account-insights?since=${since}&until=${until}`)
        ]);

        const [campaignsJson, accountJson] = await Promise.all([
          campaignData.json(),
          accountInsights.json()
        ]);

        // Process campaigns with the new processing logic
        const processedCampaigns = campaignsJson.map(processCampaignData);
        const activeCampaigns = processedCampaigns.filter(c => c.metrics.spend > 0);
        setCampaigns(activeCampaigns);

        if (activeCampaigns.length > 0) {
          const totalSpend = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.spend, 0);
          const totalImpressions = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.impressions, 0);
          const totalReach = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.reach, 0);
          const totalPurchases = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.totalPurchases, 0);
          const totalPurchaseValue = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.purchaseValue, 0);
          const totalLinkClicks = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.clicks, 0);
          const totalPostEngagements = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.totalPostEngagements, 0);
          
          const numCampaigns = activeCampaigns.length;
          const avgFrequency = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.frequency, 0) / numCampaigns;
          const avgCpm = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.cpm, 0) / numCampaigns;
          const avgCtr = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.ctr, 0) / numCampaigns;
          const avgCpc = activeCampaigns.reduce((sum, camp) => sum + camp.metrics.cpc, 0) / numCampaigns;

          setSummaryMetrics({
            totalSpend,
            totalPurchaseValue,
            totalLinkClicks,
            totalImpressions,
            totalReach,
            totalPurchases,
            avgFrequency,
            avgCpm,
            avgCtr,
            avgCpc,
            totalPostEngagements,
            totalCampaigns: numCampaigns,
          });
        }
      } catch (err) {
        console.error("Meta Ads fetch error:", err);
        setError(`Failed to fetch Meta Ads data: ${err.message}`);
      } finally {
        setLoading(false);
      }
    };

    fetchMetaAdsData();
  }, [timeframe]);

  // Sort campaigns
  const sortedCampaigns = [...campaigns].sort((a, b) => {
    const direction = sortConfig.direction === "desc" ? -1 : 1;
    
    switch (sortConfig.key) {
      case "date":
        // Add date sorting using campaign ID (Meta IDs are chronological)
        return direction * (parseInt(b.id) - parseInt(a.id));
      case "spend":
        return direction * ((a.metrics.spend || 0) - (b.metrics.spend || 0));
      case "reach":
        return direction * ((a.metrics.reach || 0) - (b.metrics.reach || 0));
      case "impressions":
        return direction * ((a.metrics.impressions || 0) - (b.metrics.impressions || 0));
      case "cpm":
        return direction * ((a.metrics.cpm || 0) - (b.metrics.cpm || 0));
      case "ctr":
        return direction * ((a.metrics.ctr || 0) - (b.metrics.ctr || 0));
      case "results":
        return direction * ((getActionValue(a, a.objectiveActionType) || 0) - (getActionValue(b, b.objectiveActionType) || 0));
      case "value":
        return direction * ((a.metrics.purchaseValue || 0) - (b.metrics.purchaseValue || 0));
      case "engagements":
        return direction * ((a.metrics.totalPostEngagements || 0) - (b.metrics.totalPostEngagements || 0));
      default:
        return 0;
    }
  });

  if (loading) {
    return (
      <Card className="h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <CardHeader className="pb-2">
          <div className="flex justify-between items-start mb-6">
            <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              Meta Ads Performance
            </CardTitle>
            <Select disabled value="7">
              <SelectTrigger className="w-[130px] bg-white dark:bg-gray-800">
                <SelectValue placeholder="Select range" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="7">Last 7 days</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
            {[...Array(12)].map((_, i) => (
              <SkeletonMetricCard key={i} />
            ))}
          </div>
        </CardHeader>
        <CardContent className="p-4">
          <SkeletonTable />
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <CardContent className="p-4">
          <div className="p-4 m-6 text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/10 rounded-lg border border-red-200 dark:border-red-900/20">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <CardHeader className="pb-2">
        <div className="flex justify-between items-start mb-6">
          <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
            Meta Ads Performance
          </CardTitle>
          <Select value={timeframe} onValueChange={setTimeframe}>
            <SelectTrigger className="w-[130px] bg-white dark:bg-gray-800">
              <SelectValue placeholder="Select range" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="today">Today</SelectItem>
              <SelectItem value="7">Last 7 days</SelectItem>
              <SelectItem value="14">Last 14 days</SelectItem>
              <SelectItem value="30">Last 30 days</SelectItem>
              <SelectItem value="90">Last 90 days</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
          {[
            {
              label: "Active Campaigns",
              value: summaryMetrics?.totalCampaigns,
              options: { icon: Target, iconColor: "text-purple-500" },
            },
            {
              label: "Total Spend",
              value: summaryMetrics?.totalSpend,
              options: { isMonetary: true, decimalPlaces: 0, icon: DollarSign, iconColor: "text-green-500" },
            },
            {
              label: "Total Reach",
              value: summaryMetrics?.totalReach,
              options: { icon: Users, iconColor: "text-blue-500" },
            },
            {
              label: "Total Impressions",
              value: summaryMetrics?.totalImpressions,
              options: { icon: Eye, iconColor: "text-indigo-500" },
            },
            {
              label: "Avg Frequency",
              value: summaryMetrics?.avgFrequency,
              options: { decimalPlaces: 2, icon: Repeat, iconColor: "text-cyan-500" },
            },
            {
              label: "Total Engagements",
              value: summaryMetrics?.totalPostEngagements,
              options: { icon: MessageCircle, iconColor: "text-pink-500" },
            },
            {
              label: "Avg CPM",
              value: summaryMetrics?.avgCpm,
              options: { isMonetary: true, decimalPlaces: 2, icon: DollarSign, iconColor: "text-emerald-500" },
            },
            {
              label: "Avg CTR",
              value: summaryMetrics?.avgCtr,
              options: { isPercentage: true, decimalPlaces: 2, icon: BarChart, iconColor: "text-orange-500" },
            },
            {
              label: "Avg CPC",
              value: summaryMetrics?.avgCpc,
              options: { isMonetary: true, decimalPlaces: 2, icon: MousePointer, iconColor: "text-rose-500" },
            },
            {
              label: "Total Link Clicks",
              value: summaryMetrics?.totalLinkClicks,
              options: { icon: MousePointer, iconColor: "text-amber-500" },
            },
            {
              label: "Total Purchases",
              value: summaryMetrics?.totalPurchases,
              options: { icon: ShoppingCart, iconColor: "text-teal-500" },
            },
            {
              label: "Purchase Value",
              value: summaryMetrics?.totalPurchaseValue,
              options: { isMonetary: true, decimalPlaces: 0, icon: DollarSign, iconColor: "text-lime-500" },
            },
          ].map((card) => (
            <div key={card.label} className="h-full">
              {summaryCard(card.label, card.value, card.options)}
            </div>
          ))}
        </div>
      </CardHeader>

      <CardContent className="overflow-y-auto pl-4 max-h-[400px] mb-4">
        <table className="w-full">
          <thead>
            <tr className="border-b border-gray-200 dark:border-gray-800">
              <th className="p-2 text-left font-medium sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant="ghost"
                  className="pl-0 justify-start w-full h-8"
                  onClick={() => handleSort("date")}
                >
                  Campaign
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "spend" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("spend")}
                >
                  Spend
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "reach" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("reach")}
                >
                  Reach
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "impressions" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("impressions")}
                >
                  Impressions
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "cpm" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("cpm")}
                >
                  CPM
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "ctr" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("ctr")}
                >
                  CTR
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "results" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("results")}
                >
                  Results
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "value" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("value")}
                >
                  Value
                </Button>
              </th>
              <th className="p-2 font-medium text-center sticky top-0 bg-white dark:bg-gray-900/60 backdrop-blur-sm z-10 text-gray-900 dark:text-gray-100">
                <Button
                  variant={sortConfig.key === "engagements" ? "default" : "ghost"}
                  className="w-full justify-center h-8"
                  onClick={() => handleSort("engagements")}
                >
                  Engagements
                </Button>
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
            {sortedCampaigns.map((campaign) => (
              <tr
                key={campaign.id}
                className="hover:bg-muted/50 transition-colors"
              >
                <td className="p-2 align-top">
                  <div>
                    <div className="font-medium text-gray-900 dark:text-gray-100 break-words min-w-[200px] max-w-[300px]">
                      <CampaignName name={campaign.name} />
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {campaign.objective}
                    </div>
                  </div>
                </td>

                <MetricCell
                  value={campaign.metrics.spend}
                  isMonetary
                  decimalPlaces={2}
                  sublabel={
                    campaign.budget
                      ? `${formatCurrency(campaign.budget, 0)}/${campaign.budgetType}`
                      : "Budget: Ad set"
                  }
                />

                <MetricCell 
                  value={campaign.metrics.reach}
                  label={`${formatNumber(campaign.metrics.frequency, 2)}x freq`}
                />

                <MetricCell
                  value={campaign.metrics.impressions}
                />

                <MetricCell
                  value={campaign.metrics.cpm}
                  isMonetary
                  decimalPlaces={2}
                />

                <MetricCell
                  value={campaign.metrics.ctr}
                  isPercentage
                  decimalPlaces={2}
                  label={`${formatCurrency(campaign.metrics.cpc, 2)} CPC`}
                />

                <MetricCell
                  value={getActionValue(campaign, campaign.objectiveActionType)}
                  label={campaign.objective}
                />

                <MetricCell
                  value={campaign.metrics.purchaseValue}
                  isMonetary
                  decimalPlaces={2}
                  sublabel={campaign.metrics.costPerResult ? `${formatCurrency(campaign.metrics.costPerResult)}/result` : null}
                />

                <MetricCell 
                  value={campaign.metrics.totalPostEngagements}
                />
              </tr>
            ))}
          </tbody>
        </table>
      </CardContent>
    </Card>
  );
};

export default MetaCampaigns; 