"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { AddPostDialog } from "@/components/dashboard/social-media/add-post-dialog";
import { UpdateStatisticsDialog } from "@/components/dashboard/social-media/update-statistics-dialog";
import { PlatformIcon, getPlatformIcon } from "@/components/icons";
import {
  DataTable,
  PublicationItem,
  StatMetric,
  type DataTableColumn,
} from "@/components/shared";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useSocialMediaAccount, useSocialMediaMutations } from "@/hooks/use-social-media";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { cn } from "@/lib/utils";
import type { AccountStatistics, ManualPostInput, UpdateManualStatisticsInput, SocialMediaPost } from "@/types";
import {
  BarChart3,
  CalendarClock,
  Edit,
  Eye,
  FileText,
  Heart,
  MessageCircle,
  Plus,
  Repeat2,
  TrendingUp,
  Users,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import Image from "next/image";
import { useParams } from "next/navigation";
import type { ComponentType } from "react";
import { useState } from "react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  LabelList,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip as RechartsTooltip,
  XAxis,
  YAxis,
} from "recharts";

type MetricTile = {
  label: string;
  value: string | number;
  icon: ComponentType<{ className?: string }>;
  tone?: "default" | "success" | "warning";
};

type DistributionItem = {
  label: string;
  value: number;
  meta?: string;
};

type ChartItem = DistributionItem & {
  color: string;
};

const CHART_COLORS = [
  "#2f7d4f",
  "#6f9f7a",
  "#d6a84f",
  "#3f7d93",
  "#8b6fcb",
  "#c76f55",
];

const PLATFORM_SPECIFIC_LABELS: Record<string, { ar: string; en: string }> = {
  quotes_count: { ar: "عدد الاقتباسات", en: "Quotes Count" },
  bookmarks: { ar: "الحفظ", en: "Bookmarks" },
  saves: { ar: "الحفظ", en: "Saves" },
  profile_visits: { ar: "زيارات الملف", en: "Profile Visits" },
  link_clicks: { ar: "نقرات الرابط", en: "Link Clicks" },
  clicks: { ar: "النقرات", en: "Clicks" },
  ctr: { ar: "نسبة النقر", en: "CTR" },
  page_visits: { ar: "زيارات الصفحة", en: "Page Visits" },
  screenshots: { ar: "لقطات الشاشة", en: "Screenshots" },
  story_completions: { ar: "إكمال القصة", en: "Story Completions" },
  unique_views: { ar: "المشاهدات الفريدة", en: "Unique Views" },
  story_completion_rate: { ar: "معدل إكمال القصة", en: "Story Completion Rate" },
};

function toFiniteNumber(value: unknown): number {
  const numericValue =
    typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));

  return Number.isFinite(numericValue) ? numericValue : 0;
}

function formatStatKey(key: string, locale: string) {
  const localized = PLATFORM_SPECIFIC_LABELS[key]?.[locale === "ar" ? "ar" : "en"];

  return localized ?? key.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
}

function formatNumber(value: unknown) {
  return toFiniteNumber(value).toLocaleString();
}

function formatPercent(value: unknown) {
  return `${toFiniteNumber(value).toFixed(2)}%`;
}

function MetricTileCard({ metric }: { metric: MetricTile }) {
  const Icon = metric.icon;

  return (
    <div
      className={cn(
        "rounded-lg border bg-background p-4",
        metric.tone === "success" && "border-emerald-200 bg-emerald-50/60 dark:border-emerald-900 dark:bg-emerald-950/20",
        metric.tone === "warning" && "border-amber-200 bg-amber-50/60 dark:border-amber-900 dark:bg-amber-950/20",
      )}
    >
      <div className="flex items-center justify-between gap-3">
        <p className="text-xs font-medium text-muted-foreground">{metric.label}</p>
        <Icon className="size-4 shrink-0 text-muted-foreground" />
      </div>
      <p className="mt-3 truncate text-xl font-semibold text-foreground">
        {typeof metric.value === "number" ? metric.value.toLocaleString() : metric.value}
      </p>
    </div>
  );
}

export function HeaderKpi({
  label,
  value,
  icon: Icon,
  tone = "default",
}: {
  label: string;
  value: string | number;
  icon: ComponentType<{ className?: string }>;
  tone?: "default" | "success";
}) {
  return (
    <div className="flex items-center gap-3 px-4 py-4 sm:px-5">
      <div
        className={cn(
          "flex size-9 shrink-0 items-center justify-center rounded-lg",
          tone === "success"
            ? "bg-primary/10 text-primary"
            : "bg-muted text-muted-foreground",
        )}
      >
        <Icon className="size-4" />
      </div>
      <div className="min-w-0">
        <p className="truncate text-xs font-medium text-muted-foreground">
          {label}
        </p>
        <p className="mt-0.5 truncate text-lg font-semibold tabular-nums text-foreground">
          {typeof value === "number" ? value.toLocaleString() : value}
        </p>
      </div>
    </div>
  );
}

function withChartColors(items: DistributionItem[]): ChartItem[] {
  return items.map((item, index) => ({
    ...item,
    color: CHART_COLORS[index % CHART_COLORS.length],
  }));
}

function ChartEmptyState({ label }: { label: string }) {
  return (
    <div className="flex h-[260px] items-center justify-center rounded-lg border border-dashed bg-muted/20 px-4 text-center text-sm text-muted-foreground">
      {label}
    </div>
  );
}

function DonutDistributionChart({
  title,
  items,
  emptyLabel,
  locale,
}: {
  title: string;
  items: DistributionItem[];
  emptyLabel: string;
  locale: string;
}) {
  const data = withChartColors(items);
  const total = data.reduce((sum, item) => sum + item.value, 0);

  return (
    <section className="rounded-lg border bg-background p-4 shadow-sm">
      <div className="flex items-center justify-between gap-3">
        <h3 className="text-sm font-medium">{title}</h3>
        {total > 0 ? (
          <span className="text-xs font-medium text-muted-foreground">
            {total.toLocaleString(locale)}%
          </span>
        ) : null}
      </div>

      {data.length === 0 ? (
        <ChartEmptyState label={emptyLabel} />
      ) : (
        <div className="mt-4 grid items-center gap-4 lg:grid-cols-[minmax(0,1fr)_190px]">
          <div className="relative order-2 h-[210px] min-w-0 lg:order-1">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={data}
                  dataKey="value"
                  nameKey="label"
                  cx="50%"
                  cy="50%"
                  innerRadius="62%"
                  outerRadius="88%"
                  paddingAngle={3}
                  stroke="var(--card)"
                  strokeWidth={3}
                >
                  {data.map((item) => (
                    <Cell key={item.label} fill={item.color} />
                  ))}
                </Pie>
                <RechartsTooltip
                  formatter={(value: number | string) => `${formatNumber(value)}%`}
                  contentStyle={{
                    backgroundColor: "var(--card)",
                    border: "1px solid var(--border)",
                    borderRadius: "10px",
                    color: "var(--card-foreground)",
                  }}
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
              <div className="text-center">
                <span className="block text-2xl font-semibold text-foreground">
                  {total.toLocaleString(locale)}%
                </span>
                <span className="text-xs text-muted-foreground">{data.length}</span>
              </div>
            </div>
          </div>

          <div className="order-1 flex min-w-0 flex-col justify-center gap-2 lg:order-2">
            {data.map((item) => (
              <div key={item.label} className="flex items-center gap-2 rounded-lg bg-muted/30 px-3 py-2.5">
                <span
                  className="h-2.5 w-5 shrink-0 rounded-full"
                  style={{ backgroundColor: item.color }}
                />
                <span className="min-w-0 flex-1 truncate text-sm text-foreground">
                  {item.label}
                </span>
                <span className="shrink-0 text-sm font-semibold tabular-nums">
                  {item.value.toLocaleString(locale)}%
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

function ColumnDistributionChart({
  title,
  items,
  emptyLabel,
  locale,
  isRtl,
}: {
  title: string;
  items: DistributionItem[];
  emptyLabel: string;
  locale: string;
  isRtl: boolean;
}) {
  const data = withChartColors(items).map((item) => ({
    ...item,
    displayLabel: item.meta ? `${item.label} (${item.meta})` : item.label,
  }));
  const chartData = isRtl ? [...data].reverse() : data;

  return (
    <section className="rounded-lg border bg-background p-4 shadow-sm">
      <h3 className="text-sm font-medium">{title}</h3>

      {data.length === 0 ? (
        <div className="mt-4">
          <ChartEmptyState label={emptyLabel} />
        </div>
      ) : (
        <div className="mt-4 h-[260px]">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={chartData}
              margin={{ top: 24, right: 10, left: 4, bottom: 8 }}
            >
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--border)" />
              <XAxis
                dataKey="displayLabel"
                axisLine={false}
                tickLine={false}
                reversed={isRtl}
                tick={{ fill: "var(--muted-foreground)", fontSize: 12 }}
              />
              <YAxis
                axisLine={false}
                tickLine={false}
                orientation={isRtl ? "right" : "left"}
                width={42}
                domain={[0, 100]}
                tick={{ fill: "var(--muted-foreground)", fontSize: 12 }}
                tickFormatter={(value) => `${Number(value).toLocaleString(locale)}%`}
              />
              <RechartsTooltip
                formatter={(value: number | string) => `${formatNumber(value)}%`}
                contentStyle={{
                  backgroundColor: "var(--card)",
                  border: "1px solid var(--border)",
                  borderRadius: "10px",
                  color: "var(--card-foreground)",
                }}
              />
              <Bar dataKey="value" radius={[10, 10, 0, 0]} maxBarSize={42}>
                {chartData.map((item) => (
                  <Cell key={item.displayLabel} fill={item.color} />
                ))}
                <LabelList
                  dataKey="value"
                  position="top"
                  formatter={(value: number) => `${value.toLocaleString(locale)}%`}
                  className="fill-foreground text-xs font-semibold"
                />
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}
    </section>
  );
}

function DonutShareChart({
  title,
  items,
  emptyLabel,
  locale,
}: {
  title: string;
  items: DistributionItem[];
  emptyLabel: string;
  locale: string;
}) {
  const valuesTotal = items.reduce((sum, item) => sum + item.value, 0);
  const displayItems = valuesTotal < 100
    ? [
        ...items,
        { label: locale === "ar" ? "أخرى" : "Other", value: 100 - valuesTotal },
      ]
    : items;
  const data = withChartColors(displayItems).map((item, index) => ({
    ...item,
    color: index === items.length && valuesTotal < 100 ? "var(--muted)" : CHART_COLORS[index % CHART_COLORS.length],
  }));

  return (
    <section className="rounded-lg border bg-background p-4 shadow-sm">
      <div className="flex items-center justify-between gap-3">
        <h3 className="text-sm font-medium">{title}</h3>
        {valuesTotal > 0 ? (
          <span className="text-xs font-medium text-muted-foreground">
            {valuesTotal.toLocaleString(locale)}%
          </span>
        ) : null}
      </div>

      {items.length === 0 ? (
        <div className="mt-4">
          <ChartEmptyState label={emptyLabel} />
        </div>
      ) : (
        <div className="mt-4 grid items-center gap-4 lg:grid-cols-[minmax(0,1fr)_190px]">
          <div className="relative order-2 h-[210px] min-w-0 lg:order-1">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={data}
                  dataKey="value"
                  nameKey="label"
                  cx="50%"
                  cy="50%"
                  innerRadius="62%"
                  outerRadius="88%"
                  paddingAngle={2}
                  stroke="var(--card)"
                  strokeWidth={3}
                >
                  {data.map((item) => (
                    <Cell key={item.label} fill={item.color} />
                  ))}
                </Pie>
                <RechartsTooltip
                  formatter={(value: number | string) => `${formatNumber(value)}%`}
                  contentStyle={{
                    backgroundColor: "var(--card)",
                    border: "1px solid var(--border)",
                    borderRadius: "10px",
                    color: "var(--card-foreground)",
                  }}
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
              <span className="text-2xl font-semibold text-foreground">
                {valuesTotal.toLocaleString(locale)}%
              </span>
            </div>
          </div>
          <div className="order-1 flex min-w-0 flex-col justify-center gap-2 lg:order-2">
            {items.map((item, index) => (
              <div key={`${item.label}-${item.meta ?? ""}`} className="flex items-center gap-2 rounded-lg bg-muted/30 px-3 py-2.5">
                <span
                  className="h-2.5 w-5 shrink-0 rounded-full"
                  style={{ backgroundColor: CHART_COLORS[index % CHART_COLORS.length] }}
                />
                <span className="min-w-0 flex-1 truncate text-sm text-foreground">
                  {item.meta ? `${item.label} (${item.meta})` : item.label}
                </span>
                <span className="shrink-0 text-sm font-semibold tabular-nums">
                  {item.value.toLocaleString(locale)}%
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

function PlatformStatsChart({
  items,
  emptyLabel,
}: {
  items: DistributionItem[];
  emptyLabel: string;
}) {
  if (items.length === 0) {
    return (
      <div className="flex w-full">
        <ChartEmptyState label={emptyLabel} />
      </div>
    );
  }

  const colored = withChartColors(items);
  const sorted = [...colored].sort((a, b) => b.value - a.value);
  const maxValue = sorted[0]?.value ?? 0;

  return (
    <div className="grid w-full gap-3 sm:grid-cols-2">
      {sorted.map((item, index) => {
        const ratio = maxValue > 0 ? item.value / maxValue : 0;
        const isLeader = index === 0;
        return (
          <div
            key={item.label}
            className={cn(
              "group relative overflow-hidden rounded-xl border bg-card p-4 transition-shadow hover:shadow-sm",
              isLeader && "ring-1 ring-primary/30",
            )}
          >
            {/* Accent rail */}
            <span
              aria-hidden
              className="absolute inset-y-0 start-0 w-1"
              style={{ backgroundColor: item.color }}
            />

            <div className="flex items-start justify-between gap-2 ps-2">
              <div className="min-w-0">
                <p className="truncate text-xs font-medium text-muted-foreground">
                  {item.label}
                </p>
                <p className="mt-1 text-2xl font-semibold tabular-nums text-foreground">
                  {formatNumber(item.value)}
                </p>
              </div>
              {isLeader ? (
                <span className="shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
                  #1
                </span>
              ) : null}
            </div>

            {/* Relative weight bar */}
            <div
              className="mt-3 h-1.5 w-full overflow-hidden rounded-full bg-muted ps-2"
              role="progressbar"
              aria-valuemin={0}
              aria-valuemax={100}
              aria-valuenow={Math.round(ratio * 100)}
            >
              <div
                className="h-full rounded-full transition-all duration-500"
                style={{
                  width: `${Math.max(ratio * 100, 4)}%`,
                  backgroundColor: item.color,
                }}
              />
            </div>
            <p className="mt-2 ps-2 text-[11px] text-muted-foreground tabular-nums">
              {Math.round(ratio * 100)}%
            </p>
          </div>
        );
      })}
    </div>
  );
}

export function SocialMediaAccountDetailContainer() {
  const t = useTranslations();
  const locale = useLocale();
  const { formatDateTime } = useFormattedDate();
  const params = useParams();
  const id = params.id as string;

  const [addPostOpen, setAddPostOpen] = useState(false);
  const [updateStatsOpen, setUpdateStatsOpen] = useState(false);

  const { data, isLoading, error, refetch } = useSocialMediaAccount(id);
  const { addManualPost, updateManualStatistics, isLoading: isMutating } = useSocialMediaMutations();

  const account = data?.data?.account;
  const statistics = data?.data?.statistics || [];
  const topPosts = data?.data?.top_posts || [];

  const latestStats = statistics[0];
  const getDisplayedViewsValue = (stats?: AccountStatistics | null) =>
    stats ? stats.total_views || stats.total_impressions || 0 : 0;

  const handleAddPost = async (postData: ManualPostInput) => {
    await addManualPost(id, postData);
    refetch();
  };

  const handleUpdateStatistics = async (statsData: UpdateManualStatisticsInput) => {
    await updateManualStatistics(id, statsData);
    refetch();
  };

  const statisticsColumns: DataTableColumn<AccountStatistics>[] = [
    {
      key: "recorded_at",
      header: t("socialMedia.date"),
      render: (item) => formatDateTime(item.recorded_at),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "engagement_rate",
      header: t("socialMedia.engagementRate"),
      render: (item) => formatPercent(item.engagement_rate),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_reach",
      header: t("socialMedia.reach"),
      render: (item) => item.total_reach.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_impressions",
      header: t("socialMedia.impressionsField"),
      render: (item) => item.total_impressions.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "followers_count",
      header: t("socialMedia.followers"),
      render: (item) => item.followers_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "following_count",
      header: t("socialMedia.followingField"),
      render: (item) => item.following_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "posts_count",
      header: t("socialMedia.postsCountField"),
      render: (item) => item.posts_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_views",
      header: t("socialMedia.views"),
      render: (item) => getDisplayedViewsValue(item).toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_engagement",
      header: t("socialMedia.reportsPage.kpis.totalEngagement"),
      render: (item) => item.total_engagement.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_likes",
      header: t("socialMedia.totalLikesField"),
      render: (item) => item.total_likes.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_comments",
      header: t("socialMedia.totalCommentsField"),
      render: (item) => item.total_comments.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "total_shares",
      header: t("socialMedia.totalSharesField"),
      render: (item) => item.total_shares.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "average_engagement_per_post",
      header: t("socialMedia.reportsPage.kpis.avgEngagementPerPost"),
      render: (item) => formatNumber(item.average_engagement_per_post),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "growth_rate",
      header: t("socialMedia.growthRateField"),
      render: (item) => formatPercent(item.growth_rate),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
  ];

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              <Skeleton className="h-16 w-full" />
              <Skeleton className="h-24 w-full" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <Skeleton className="h-64 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error || !account) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="rounded-lg border border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-950 p-4">
            <p className="font-semibold text-red-900 dark:text-red-200">
              {t("common.error")}
            </p>
            <p className="text-sm text-red-700 dark:text-red-300">
              {error?.message || t("common.errorLoadingData")}
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  const accountSummary = {
    followers: latestStats?.followers_count ?? account.followers ?? 0,
    following: latestStats?.following_count ?? account.following_count ?? 0,
    posts: latestStats?.posts_count ?? account.posts_count ?? 0,
    impressions:
      latestStats?.total_impressions ??
      account.total_impressions ??
      account.impressions ??
      0,
    reach: latestStats?.total_reach ?? account.total_reach ?? 0,
    views: latestStats
      ? getDisplayedViewsValue(latestStats)
      : (account.total_views ?? account.views ?? 0),
    engagementTotal: latestStats?.total_engagement ?? account.total_engagement ?? 0,
    engagementRate: latestStats?.engagement_rate ?? account.engagement_rate ?? "0",
    likes: latestStats?.total_likes ?? account.total_likes ?? 0,
    comments: latestStats?.total_comments ?? account.total_comments ?? 0,
    shares: latestStats?.total_shares ?? account.total_shares ?? 0,
    avgEngagementPerPost:
      latestStats?.average_engagement_per_post ??
      account.average_engagement_per_post ??
      "0",
    growthRate: latestStats?.growth_rate ?? account.growth_rate ?? "0",
  };

  const latestDemographics = latestStats?.demographics ?? account.demographics ?? null;
  const platformSpecificStats =
    latestStats?.platform_specific_stats ??
    latestStats?.platform_specific ??
    account.platform_specific_stats ??
    account.platform_specific ??
    null;
  const recordedAt = latestStats?.recorded_at ?? account.stats_recorded_at ?? null;

  const accountMetrics: MetricTile[] = [
    {
      label: t("socialMedia.followers"),
      value: accountSummary.followers,
      icon: Users,
    },
    {
      label: t("socialMedia.followingField"),
      value: accountSummary.following,
      icon: Users,
    },
    {
      label: t("socialMedia.postsCountField"),
      value: accountSummary.posts,
      icon: FileText,
    },
    {
      label: t("socialMedia.impressionsField"),
      value: accountSummary.impressions,
      icon: BarChart3,
    },
    {
      label: t("socialMedia.reach"),
      value: accountSummary.reach,
      icon: Users,
    },
    {
      label: t("socialMedia.views"),
      value: accountSummary.views,
      icon: Eye,
    },
  ];

  const engagementMetrics: MetricTile[] = [
    {
      label: t("socialMedia.reportsPage.kpis.totalEngagement"),
      value: accountSummary.engagementTotal,
      icon: TrendingUp,
      tone: "success",
    },
    {
      label: t("socialMedia.engagementRate"),
      value: formatPercent(accountSummary.engagementRate),
      icon: TrendingUp,
      tone: "success",
    },
    {
      label: t("socialMedia.totalLikesField"),
      value: accountSummary.likes,
      icon: Heart,
    },
    {
      label: t("socialMedia.totalCommentsField"),
      value: accountSummary.comments,
      icon: MessageCircle,
    },
    {
      label: t("socialMedia.totalSharesField"),
      value: accountSummary.shares,
      icon: Repeat2,
    },
    {
      label: t("socialMedia.growthRateField"),
      value: formatPercent(accountSummary.growthRate),
      icon: TrendingUp,
      tone: "warning",
    },
  ];

  const genderDistribution: DistributionItem[] = Object.entries(
    latestDemographics?.gender ?? {},
  )
    .map(([key, value]) => ({
      label:
        key === "male"
          ? t("socialMedia.genderMale")
          : key === "female"
            ? t("socialMedia.genderFemale")
            : t("socialMedia.genderOther"),
      value: toFiniteNumber(value),
    }))
    .filter((item) => item.value > 0);

  const ageDistribution: DistributionItem[] = Object.entries(
    latestDemographics?.age_groups ?? {},
  )
    .map(([key, value]) => ({
      label: key,
      value: toFiniteNumber(value),
    }))
    .filter((item) => item.value > 0);

  const deviceDistribution: DistributionItem[] = Object.entries(
    latestDemographics?.devices ?? {},
  )
    .map(([key, value]) => ({
      label:
        key === "mobile"
          ? t("socialMedia.deviceMobile")
          : key === "desktop"
            ? t("socialMedia.deviceDesktop")
            : t("socialMedia.deviceTablet"),
      value: toFiniteNumber(value),
    }))
    .filter((item) => item.value > 0);

  const countryDistribution: DistributionItem[] = (latestDemographics?.top_countries ?? [])
    .map((country) => ({
      label: country.name,
      meta: country.code,
      value: toFiniteNumber(country.percentage),
    }))
    .filter((item) => item.value > 0);

  const platformSpecificEntries = Object.entries(platformSpecificStats ?? {}).filter(
    ([, value]) => value !== null && value !== undefined && String(value) !== "",
  );
  const platformSpecificDistribution: DistributionItem[] = platformSpecificEntries.map(
    ([key, value]) => ({
      label: formatStatKey(key, locale),
      value: toFiniteNumber(value),
    }),
  );
  const isRtl = locale === "ar";

  return (
    <div className="space-y-6">
      <Card className="overflow-hidden">
        <CardContent className="p-0">
          {/* Identity strip */}
          <div className="flex flex-col gap-4 p-6 sm:flex-row sm:items-center">
            <div className="relative size-16 shrink-0 overflow-hidden rounded-xl bg-muted/40 ring-1 ring-border">
              {account.profile_image_url ? (
                <Image
                  src={account.profile_image_url}
                  alt={account.account_name || account.account_identifier || ""}
                  fill
                  className="object-cover"
                  sizes="64px"
                />
              ) : (
                <div className="flex h-full w-full items-center justify-center">
                  <PlatformIcon platform={account.platform} size="xl" />
                </div>
              )}
            </div>

            <div className="min-w-0 flex-1">
              <div className="flex flex-wrap items-center gap-1.5">
                <Badge variant="secondary" className="capitalize">
                  {account.platform_label || account.platform}
                </Badge>
                <Badge variant={account.is_manual ? "outline" : "secondary"}>
                  {account.is_manual
                    ? t("socialMedia.reportsPage.accountTypes.manual")
                    : t("socialMedia.reportsPage.accountTypes.api")}
                </Badge>
                <Badge variant={account.is_active ? "default" : "outline"}>
                  <span
                    aria-hidden
                    className={cn(
                      "me-1 inline-block size-1.5 rounded-full",
                      account.is_active ? "bg-emerald-400" : "bg-muted-foreground",
                    )}
                  />
                  {account.is_active
                    ? t("settings.dashboard.active")
                    : t("settings.dashboard.inactive")}
                </Badge>
              </div>

              <h2 className="mt-2 truncate text-xl font-semibold text-foreground sm:text-2xl">
                {account.account_display_name ||
                  account.account_name ||
                  account.account_identifier ||
                  "-"}
              </h2>

              {account.account_url ? (
                <a
                  href={account.account_url}
                  target="_blank"
                  rel="noreferrer"
                  className="mt-1 inline-flex max-w-full items-center gap-1.5 text-sm text-primary hover:underline"
                >
                  <span className="truncate">{account.account_url}</span>
                </a>
              ) : null}
            </div>

            <AuthorizedAction
              action={{ actionKey: "social_media.update_manual_statistics" }}
              surface="inline"
            >
              <Button
                variant="outline"
                size="sm"
                className="shrink-0 self-start sm:self-center"
                onClick={() => setUpdateStatsOpen(true)}
              >
                <Edit className="size-4 me-2" />
                {t("socialMedia.updateStatistics")}
              </Button>
            </AuthorizedAction>
          </div>

          {/* Meta strip — dates */}
          {recordedAt || account.created_at ? (
            <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5 border-t bg-muted/30 px-6 py-2.5 text-xs text-muted-foreground">
              {recordedAt ? (
                <div className="flex items-center gap-1.5">
                  <CalendarClock className="size-3.5 shrink-0" />
                  <span className="font-medium text-foreground/80">
                    {t.has("socialMedia.lastUpdated")
                      ? t("socialMedia.lastUpdated")
                      : locale === "ar"
                        ? "آخر تحديث"
                        : "Last updated"}
                  </span>
                  <span className="tabular-nums">{formatDateTime(recordedAt)}</span>
                </div>
              ) : null}
              {account.created_at ? (
                <div className="flex items-center gap-1.5">
                  <CalendarClock className="size-3.5 shrink-0" />
                  <span className="font-medium text-foreground/80">
                    {t("common.createdAt")}
                  </span>
                  <span className="tabular-nums">
                    {formatDateTime(account.created_at)}
                  </span>
                </div>
              ) : null}
            </div>
          ) : null}

          {/* KPI strip */}
          <div className="grid grid-cols-2 divide-x divide-border border-t bg-card sm:grid-cols-4 rtl:divide-x-reverse">
            <HeaderKpi
              label={t("socialMedia.engagementRate")}
              value={formatPercent(accountSummary.engagementRate)}
              icon={TrendingUp}
              tone="success"
            />
            <HeaderKpi
              label={t("socialMedia.reportsPage.kpis.avgEngagementPerPost")}
              value={formatNumber(accountSummary.avgEngagementPerPost)}
              icon={BarChart3}
            />
            <HeaderKpi
              label={t("socialMedia.totalLikesField")}
              value={formatNumber(accountSummary.likes)}
              icon={Heart}
            />
            <HeaderKpi
              label={t("socialMedia.totalCommentsField")}
              value={formatNumber(accountSummary.comments)}
              icon={MessageCircle}
            />
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        {accountMetrics.map((metric) => (
          <MetricTileCard key={metric.label} metric={metric} />
        ))}
      </div>

      <Card>
        <CardHeader className="border-b px-6 py-4">
          <CardTitle className="text-base font-semibold text-foreground text-start">
            {t("socialMedia.interactions")}
          </CardTitle>
          <CardDescription>
            {recordedAt ? formatDateTime(recordedAt) : t("socialMedia.noStatisticsYet")}
          </CardDescription>
        </CardHeader>
        <CardContent className="p-6">
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {engagementMetrics.map((metric) => (
              <MetricTileCard key={metric.label} metric={metric} />
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <Card>
          <CardHeader className="border-b px-6 py-4">
            <CardTitle className="text-base font-semibold text-foreground text-start">
              {t("socialMedia.demographics")}
            </CardTitle>
            <CardDescription>{t("socialMedia.demographicsHint")}</CardDescription>
          </CardHeader>
          <CardContent className="p-6">
            <div className="grid gap-6 md:grid-cols-2">
              <DonutDistributionChart
                title={t("socialMedia.gender")}
                items={genderDistribution}
                emptyLabel={t("socialMedia.noStatisticsYet")}
                locale={locale}
              />
              <ColumnDistributionChart
                title={t("socialMedia.ageGroups")}
                items={ageDistribution}
                emptyLabel={t("socialMedia.noStatisticsYet")}
                locale={locale}
                isRtl={isRtl}
              />
              <DonutDistributionChart
                title={t("socialMedia.devices")}
                items={deviceDistribution}
                emptyLabel={t("socialMedia.noStatisticsYet")}
                locale={locale}
              />
              <DonutShareChart
                title={t("socialMedia.topCountries")}
                items={countryDistribution}
                emptyLabel={t("socialMedia.noCountriesYet")}
                locale={locale}
              />
            </div>
          </CardContent>
        </Card>

        <Card className="gap-0 self-start">
          <CardHeader className="border-b px-6 py-4">
            <div className="flex items-start justify-between gap-3">
              <div>
                <CardTitle className="text-base font-semibold text-foreground text-start">
                  {t("socialMedia.platformSpecificMetrics")}
                </CardTitle>
                <CardDescription className="capitalize">
                  {account.platform_label || account.platform}
                </CardDescription>
              </div>
              {platformSpecificDistribution.length > 0 ? (
                <Badge variant="outline" className="shrink-0 tabular-nums">
                  {platformSpecificDistribution.length}
                </Badge>
              ) : null}
            </div>
          </CardHeader>
          <CardContent className="p-4">
            <PlatformStatsChart
              items={platformSpecificDistribution}
              emptyLabel={t("socialMedia.noStatisticsYet")}
            />
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="border-b px-6 py-4 flex flex-row items-center justify-between">
          <CardTitle className="text-base font-semibold text-foreground text-start">
            {t("socialMedia.topPublications")}
          </CardTitle>
          <AuthorizedAction
            action={{ actionKey: "social_media.add_manual_post" }}
            surface="inline"
          >
            <Button
              variant="outline"
              size="sm"
              onClick={() => setAddPostOpen(true)}
            >
              <Plus className="size-4 me-2" />
              {t("socialMedia.addPost")}
            </Button>
          </AuthorizedAction>
        </CardHeader>
        <CardContent className="p-0">
          {topPosts.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              {t("socialMedia.noPostsYet")}
            </div>
          ) : (
            <div className="flex flex-col">
              {topPosts.map((post: SocialMediaPost, index: number) => (
                <PublicationItem
                  key={post.id}
                  id={post.id.toString()}
                  title={post.title || post.content}
                  publishDate={post.published_at}
                  platformName={post.platform}
                  platformIcon={getPlatformIcon(post.platform)}
                  views={post.views_count || 0}
                  shares={post.shares_count || 0}
                  comments={post.comments_count || 0}
                  likes={post.likes_count || 0}
                  className={cn(
                    "border-b border-border last:border-b-0",
                    index % 2 === 1 && "bg-muted/30 dark:bg-muted/20"
                  )}
                />
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="border-b px-6 py-4">
          <CardTitle className="text-base font-semibold text-foreground text-start">
            {t("socialMedia.statisticsLog")}
          </CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          {statistics.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              {t("socialMedia.noStatisticsYet")}
            </div>
          ) : (
            <DataTable
              data={statistics}
              columns={statisticsColumns}
              keyExtractor={(item) => item.id.toString()}
              className="overflow-x-auto overflow-y-hidden"
            />
          )}
        </CardContent>
      </Card>

      <AddPostDialog
        open={addPostOpen}
        onOpenChange={setAddPostOpen}
        onSubmit={handleAddPost}
        isLoading={isMutating}
        platform={account?.platform}
      />

      <UpdateStatisticsDialog
        open={updateStatsOpen}
        onOpenChange={setUpdateStatsOpen}
        onSubmit={handleUpdateStatistics}
        isLoading={isMutating}
        currentStats={latestStats}
      />
    </div>
  );
}
