"use client";

import {
  EyeNewsIcon,
  FileTextNewsIcon,
  SmileIcon,
} from "@/components/icons/dashboard";
import { Card, CardContent, CardTitle } from "@/components/ui/card";
import { StatCard } from "@/components/ui/stat-card";
import { Badge } from "@/components/ui/badge";
import { useThemeColors } from "@/hooks/use-theme-colors";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import type {
  ArticlesStatistics,
  NewsStatisticsSummary,
  TimeSeries,
} from "@/types/statistics";
import { useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { useMemo } from "react";
import { Newspaper } from "lucide-react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

// Series colors — purple for news, sky-blue for articles
const NEWS_COLOR = "#8b5cf6";
const ARTICLES_COLOR = "#93c5fd";

interface NewsArticlesProps {
  newsStats?: NewsStatisticsSummary;
  articlesStats?: ArticlesStatistics;
  timeSeries?: TimeSeries;
}

export function NewsArticlesSection({
  newsStats,
  articlesStats,
  timeSeries,
}: NewsArticlesProps) {
  const t = useTranslations();
  const { formatDate: formatAppDate } = useFormattedDate();
  const colors = useThemeColors();
  const params = useParams();
  const locale = params?.locale as string;
  const isRTL = locale === "ar";

  const newsCount = newsStats?.total_news ?? newsStats?.total_count ?? 0;
  const articlesCount =
    articlesStats?.total_articles ?? articlesStats?.total_count ?? 0;
  // Combined views and shares
  const totalViews = (newsStats?.total_views ?? 0) + (articlesStats?.total_views ?? 0);
  const totalShares = (newsStats?.total_shares ?? 0) + (articlesStats?.total_shares ?? 0);

  // Platform breakdown from news (and merge articles if present)
  const platformBreakdown = useMemo<Record<string, number>>(() => {
    const result: Record<string, number> = {};
    if (newsStats?.platform_breakdown && typeof newsStats.platform_breakdown === "object") {
      Object.entries(newsStats.platform_breakdown as Record<string, number>).forEach(
        ([platform, count]) => {
          result[platform] = (result[platform] ?? 0) + count;
        }
      );
    }
    if (
      articlesStats?.platform_breakdown &&
      !Array.isArray(articlesStats.platform_breakdown) &&
      typeof articlesStats.platform_breakdown === "object"
    ) {
      Object.entries(articlesStats.platform_breakdown as Record<string, number>).forEach(
        ([platform, count]) => {
          result[platform] = (result[platform] ?? 0) + count;
        }
      );
    }
    return result;
  }, [newsStats?.platform_breakdown, articlesStats?.platform_breakdown]);

  const hasPlatforms = Object.keys(platformBreakdown).length > 0;

  // Build bar chart data — both news and articles views per date
  const chartData = useMemo(() => {
    if (!timeSeries?.labels?.length) return [];
    return timeSeries.labels.map((label, index) => ({
      date: formatAppDate(label),
      news: timeSeries.news?.[index] ?? 0,
      articles: timeSeries.articles?.[index] ?? 0,
    }));
  }, [timeSeries, formatAppDate]);

  const displayData = isRTL ? [...chartData].reverse() : chartData;

  return (
    <div>
      <div className="flex items-center justify-between gap-3 p-4">
        <CardTitle className="text-start text-base sm:text-lg">
          {t("dashboard.newsArticlesStats.title")}
        </CardTitle>
      </div>

      <CardContent className="p-3 sm:p-6 space-y-4 sm:space-y-6">
        {/* 4 Stat Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
          <StatCard
            variant="status"
            icon={Newspaper}
            iconBgColor="bg-tag-background-secondary-light text-tag-text-secondary"
            title={t("dashboard.newsArticlesStats.totalNews")}
            value={newsCount.toLocaleString()}
            statuses={{
              primary: {
                label: t("dashboard.newsArticlesStats.thisMonth"),
                value: newsCount,
              },
              secondary: {
                label: t("dashboard.newsArticlesStats.lastMonth"),
                value: 0,
              },
            }}
          />

          <StatCard
            variant="status"
            icon={FileTextNewsIcon}
            iconBgColor="bg-tag-background-info-light text-tag-text-info"
            title={t("dashboard.newsArticlesStats.totalArticles")}
            value={articlesCount.toLocaleString()}
            statuses={{
              primary: {
                label: t("dashboard.newsArticlesStats.thisMonth"),
                value: articlesCount,
              },
              secondary: {
                label: t("dashboard.newsArticlesStats.lastMonth"),
                value: 0,
              },
            }}
          />

          <StatCard
            variant="status"
            icon={EyeNewsIcon}
            iconBgColor="bg-tag-background-warning-light text-tag-text-warning"
            title={t("dashboard.newsArticlesStats.totalViews")}
            value={totalViews.toLocaleString()}
            statuses={{
              primary: {
                label: t("dashboard.newsArticlesStats.thisMonth"),
                value: totalViews,
              },
              secondary: {
                label: t("dashboard.newsArticlesStats.lastMonth"),
                value: 0,
              },
            }}
          />

          <StatCard
            variant="status"
            icon={SmileIcon}
            iconBgColor="bg-tag-background-success-light text-tag-text-success"
            title={t("dashboard.newsArticlesStats.totalShares")}
            value={totalShares.toLocaleString()}
            statuses={{
              primary: {
                label: t("dashboard.newsArticlesStats.thisMonth"),
                value: totalShares,
              },
              secondary: {
                label: t("dashboard.newsArticlesStats.lastMonth"),
                value: 0,
              },
            }}
          />
        </div>

        {/* Platform distribution */}
        {hasPlatforms && (
          <div className="flex flex-wrap items-center gap-3 px-1">
            <span className="text-sm text-muted-foreground shrink-0">
              {t("dashboard.newsArticlesStats.platformDistribution")}
            </span>
            <div className="flex flex-wrap gap-2">
              {Object.entries(platformBreakdown).map(([platform, count]) => (
                <Badge
                  key={platform}
                  variant="outline"
                  className="text-xs gap-1 px-2 py-0.5"
                >
                  <span className="inline-block h-1.5 w-1.5 rounded-full bg-primary shrink-0" />
                  {platform} ({count})
                </Badge>
              ))}
            </div>
          </div>
        )}

        {/* Label row above chart */}
        <div className="flex items-center justify-end px-1">
          <span className="text-sm font-medium text-foreground">
            {t("dashboard.newsArticlesStats.viewsChartSectionLabel")}
          </span>
        </div>

        {/* Bar Chart */}
        <Card className="relative p-3 sm:p-6 gap-3 sm:gap-6">
          <div className="rounded-lg bg-primary/5 px-3 sm:px-6 py-3 sm:py-4">
            <h3 className="font-semibold text-base sm:text-lg text-foreground">
              {t("dashboard.newsArticlesStats.viewsChartTitle")}
            </h3>
          </div>

          <div className="px-0 min-w-0">
            <div className="overflow-x-auto min-w-0">
              <div className="min-w-[360px] sm:min-w-[520px] lg:min-w-[720px]">
                <div className="h-[220px] sm:h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart
                      data={displayData}
                      margin={{ top: 8, right: 8, left: 0, bottom: 0 }}
                      barCategoryGap="30%"
                      barGap={2}
                    >
                      <CartesianGrid
                        strokeDasharray="0"
                        stroke={colors.border}
                        vertical={true}
                        horizontal={true}
                      />

                      <XAxis
                        dataKey="date"
                        tick={{ fill: colors.mutedForeground, fontSize: 10 }}
                        axisLine={false}
                        tickLine={false}
                        reversed={isRTL}
                        interval="preserveStartEnd"
                        minTickGap={24}
                      />

                      <YAxis
                        tick={{ fill: colors.mutedForeground, fontSize: 11 }}
                        axisLine={false}
                        tickLine={false}
                        domain={[0, "auto"]}
                        orientation={isRTL ? "right" : "left"}
                        tickFormatter={(v) => v.toLocaleString()}
                        width={36}
                        allowDecimals={false}
                      />

                      <Tooltip
                        contentStyle={{
                          backgroundColor: "var(--card)",
                          border: `1px solid var(--border)`,
                          borderRadius: "8px",
                          boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                          color: "var(--card-foreground)",
                        }}
                        labelStyle={{
                          color: "var(--card-foreground)",
                          fontWeight: 600,
                        }}
                        cursor={{ fill: "var(--muted)", opacity: 0.4 }}
                      />

                      <Legend
                        verticalAlign="top"
                        align={isRTL ? "left" : "right"}
                        iconType="rect"
                        iconSize={12}
                        wrapperStyle={{
                          fontSize: "12px",
                          color: "var(--muted-foreground)",
                          paddingBottom: "8px",
                        }}
                      />

                      <Bar
                        dataKey="articles"
                        name={t("dashboard.newsArticlesStats.articlesTab")}
                        fill={ARTICLES_COLOR}
                        radius={[3, 3, 0, 0]}
                        maxBarSize={24}
                        isAnimationActive={true}
                        animationDuration={800}
                        animationEasing="ease-out"
                      />

                      <Bar
                        dataKey="news"
                        name={t("dashboard.newsArticlesStats.newsTab")}
                        fill={NEWS_COLOR}
                        radius={[3, 3, 0, 0]}
                        maxBarSize={24}
                        isAnimationActive={true}
                        animationDuration={800}
                        animationEasing="ease-out"
                      />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </CardContent>
    </div>
  );
}
