"use client";

import { ArticleDialog } from "@/components/dashboard/articles/article-dialog";
import { PageHeader } from "@/components/layout";
import { ConfirmationDialog, TruncatedText } from "@/components/shared";
import { Card } from "@/components/ui";
import { Skeleton } from "@/components/ui/skeleton";
import { useArticle, useArticleMutations } from "@/hooks/use-articles";
import { useRouter } from "@/i18n/routing";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import type { CreateArticleRequest } from "@/types";
import { Calendar, ExternalLink, Pencil, Trash2 } from "lucide-react";
import Image from "next/image";
import { useLocale, useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";

export function ArticleDetailsPageContainer() {
  const t = useTranslations();
  const locale = useLocale();
  const { formatDate, formatDateTime } = useFormattedDate();
  const isArabic = locale === "ar";
  const router = useRouter();
  const params = useParams();
  const articleId = params.id as string;

  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { article, statistics, isLoading, refetch } = useArticle(articleId);
  const { updateArticle, deleteArticle } = useArticleMutations();

  const articleUrl = article?.article_url || article?.url;
  const articleAuthor = article?.author_name || article?.author;
  const featuredImage = article?.featured_image_url || article?.featured_image;
  const articleTags = article?.tags || [];
  const articleStatusLabel = article?.status_label || article?.status;
  const articleTypeLabel = article?.article_type_label || article?.article_type;
  const articleCategory = article?.category;
  const numberLocale = "en-US";

  type ArticleTrafficSourcesView = {
    organic: number;
    direct: number;
    social: number;
    paid: number;
  };

  type ArticleStatsViewRow = {
    id: string | number;
    recorded_at: string | null;
    views: number;
    unique_views: number;
    comments: number;
    shares: number;
    search_impressions: number;
    search_clicks: number;
    search_ctr: string | number;
    average_read_time: number;
    bounce_rate: string | number;
    engagement_rate: string | number;
    ad_clicks: number;
    ad_revenue: string | number;
    ad_manager_revenue: string | number;
    traffic_sources: ArticleTrafficSourcesView | ArticleTrafficSourcesView[] | null;
  };

  const latestStats: ArticleStatsViewRow | undefined = article?.stats
    ? {
        id: article.id,
        recorded_at: article.stats.recorded_at || article.published_at || null,
        views: article.stats.views ?? 0,
        unique_views: article.stats.unique_views ?? 0,
        comments: article.stats.comments ?? 0,
        shares: article.stats.shares ?? 0,
        search_impressions: article.stats.search_impressions ?? 0,
        search_clicks: article.stats.search_clicks ?? 0,
        search_ctr: article.stats.search_ctr ?? "0",
        average_read_time: article.stats.average_read_time ?? 0,
        bounce_rate: article.stats.bounce_rate ?? "0",
        engagement_rate: article.stats.engagement_rate ?? "0",
        ad_clicks: article.stats.ad_clicks ?? 0,
        ad_revenue: article.stats.ad_revenue ?? "0",
        ad_manager_revenue: article.stats.ad_manager_revenue ?? "0",
        traffic_sources: article.stats.traffic_sources ?? null,
      }
    : statistics?.[0]
      ? {
          id: statistics[0].id,
          recorded_at: statistics[0].recorded_at,
          views: statistics[0].views_count ?? 0,
          unique_views: statistics[0].unique_views_count ?? 0,
          comments: statistics[0].comments_count ?? 0,
          shares: statistics[0].shares_count ?? 0,
          search_impressions: statistics[0].search_impressions ?? 0,
          search_clicks: statistics[0].search_clicks ?? 0,
          search_ctr: statistics[0].search_ctr ?? "0",
          average_read_time: statistics[0].average_read_time ?? 0,
          bounce_rate: statistics[0].bounce_rate ?? "0",
          engagement_rate: statistics[0].engagement_rate ?? "0",
          ad_clicks: statistics[0].ad_clicks ?? 0,
          ad_revenue: statistics[0].ad_revenue ?? "0",
          ad_manager_revenue: statistics[0].ad_manager_revenue ?? "0",
          traffic_sources: statistics[0].traffic_sources ?? null,
        }
      : undefined;

  const statsRows: ArticleStatsViewRow[] = statistics?.length
    ? statistics.map((stat) => ({
        id: stat.id,
        recorded_at: stat.recorded_at,
        views: stat.views_count ?? 0,
        unique_views: stat.unique_views_count ?? 0,
        comments: stat.comments_count ?? 0,
        shares: stat.shares_count ?? 0,
        search_impressions: stat.search_impressions ?? 0,
        search_clicks: stat.search_clicks ?? 0,
        search_ctr: stat.search_ctr ?? "0",
        average_read_time: stat.average_read_time ?? 0,
        bounce_rate: stat.bounce_rate ?? "0",
        engagement_rate: stat.engagement_rate ?? "0",
        ad_clicks: stat.ad_clicks ?? 0,
        ad_revenue: stat.ad_revenue ?? "0",
        ad_manager_revenue: stat.ad_manager_revenue ?? "0",
        traffic_sources: stat.traffic_sources ?? null,
      }))
    : article?.stats
      ? [
          {
            id: `summary-${article.id}`,
            recorded_at: article.stats.recorded_at || article.published_at || null,
            views: article.stats.views ?? 0,
            unique_views: article.stats.unique_views ?? 0,
            comments: article.stats.comments ?? 0,
            shares: article.stats.shares ?? 0,
            search_impressions: article.stats.search_impressions ?? 0,
            search_clicks: article.stats.search_clicks ?? 0,
            search_ctr: article.stats.search_ctr ?? "0",
            average_read_time: article.stats.average_read_time ?? 0,
            bounce_rate: article.stats.bounce_rate ?? "0",
            engagement_rate: article.stats.engagement_rate ?? "0",
            ad_clicks: article.stats.ad_clicks ?? 0,
            ad_revenue: article.stats.ad_revenue ?? "0",
            ad_manager_revenue: article.stats.ad_manager_revenue ?? "0",
            traffic_sources: article.stats.traffic_sources ?? null,
          },
        ]
      : [];

  const formatValue = (value: string | number | null | undefined) => {
    if (value === null || value === undefined || value === "") return "-";
    return String(value);
  };

  const formatMetricValue = (value: number | null | undefined) => {
    if (value === null || value === undefined) {
      return "-";
    }
    return value.toLocaleString(numberLocale);
  };

  const handleEditSubmit = async (data: CreateArticleRequest) => {
    if (!article) return;

    setIsSubmitting(true);
    try {
      await updateArticle(article.id, data);
      refetch();
    } catch (error: unknown) {
      const errorMessage =
        (error as { message?: string })?.message ||
        t("articles.errorUpdatingArticle") ||
        "Failed to update article";
      toast.error(errorMessage);
      throw error;
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!article) return;

    try {
      await deleteArticle(article.id);
      router.push("/articles");
    } catch (error: unknown) {
      const errorMessage =
        (error as { message?: string })?.message ||
        t("articles.errorDeletingArticle") ||
        "Failed to delete article";
      toast.error(errorMessage);
    }
  };

  const headerActions = [
    ...(articleUrl
      ? [{
          label: t("articles.viewArticle"),
          icon: <ExternalLink className="h-4 w-4" />,
          onClick: () => window.open(articleUrl, "_blank", "noopener,noreferrer"),
          variant: "outline" as const,
        }]
      : []),
    {
      label: t("common.edit"),
      icon: <Pencil className="h-4 w-4" />,
      onClick: () => setIsEditDialogOpen(true),
      variant: "outline" as const,
      actionKey: "articles.update",
    },
    {
      label: t("common.delete"),
      icon: <Trash2 className="h-4 w-4" />,
      onClick: () => setIsDeleteDialogOpen(true),
      variant: "destructive" as const,
      actionKey: "articles.delete",
    },
  ];

  if (isLoading) {
    return (
      <div className="space-y-6">
        <PageHeader
          title={t("articles.details.title")}
          breadcrumbs={[
            { label: t("dashboard.home") },
            { label: t("articles.title"), href: "/articles" },
            { label: t("articles.details.title") },
          ]}
        />

        <Card className="p-4 sm:p-6 flex flex-col lg:flex-row gap-4 sm:gap-6">
          <Skeleton className="shrink-0 w-20 h-20 rounded-lg" />
          <div className="min-w-0 flex-1 flex flex-col gap-4">
            <Skeleton className="h-5 w-3/4" />
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-1/2" />
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
              {[1, 2, 3].map((i) => (
                <Skeleton key={i} className="h-20 rounded-lg" />
              ))}
            </div>
          </div>
        </Card>
      </div>
    );
  }

  if (!article) {
    return (
      <div className="space-y-6">
        <PageHeader
          title={t("articles.details.title")}
          breadcrumbs={[
            { label: t("dashboard.home") },
            { label: t("articles.title"), href: "/articles" },
            { label: t("articles.details.title") },
          ]}
        />

        <Card className="p-6">
          <p className="text-muted-foreground text-center">{t("articles.notFound")}</p>
        </Card>
      </div>
    );
  }

  const editInitialData = {
    ...article,
    author_name: articleAuthor,
    article_url: articleUrl,
    featured_image_url: featuredImage,
    stats: article.stats ?? (latestStats
      ? {
          views: latestStats.views,
          unique_views: latestStats.unique_views,
          comments: latestStats.comments,
          shares: latestStats.shares,
          recorded_at: latestStats.recorded_at,
        }
      : null),
  };

  const articleDataRows = [
    { key: "author_name", label: isArabic ? "اسم الكاتب" : "Author Name", value: articleAuthor },
    { key: "category", label: isArabic ? "التصنيف" : "Category", value: articleCategory },
    { key: "tags", label: isArabic ? "الوسوم" : "Tags", value: articleTags.length > 0 ? articleTags.join(", ") : null },
    { key: "article_url", label: isArabic ? "رابط المقال" : "Article URL", value: articleUrl },
    { key: "published_at", label: isArabic ? "تاريخ النشر" : "Published At", value: article.published_at ? formatDate(article.published_at) : null },
    { key: "status", label: isArabic ? "الحالة" : "Status", value: articleStatusLabel },
    { key: "article_type", label: isArabic ? "نوع المقال" : "Article Type", value: articleTypeLabel },
    { key: "stats_views", label: isArabic ? "المشاهدات" : "Views", value: latestStats?.views },
    { key: "stats_unique_views", label: isArabic ? "الزوار الفريدون" : "Unique Views", value: latestStats?.unique_views },
    { key: "stats_comments", label: isArabic ? "التعليقات" : "Comments", value: latestStats?.comments },
    { key: "stats_shares", label: isArabic ? "المشاركات" : "Shares", value: latestStats?.shares },
    { key: "stats_recorded_at", label: isArabic ? "تاريخ تسجيل الإحصائيات" : "Stats Recorded At", value: latestStats?.recorded_at ? formatDate(latestStats.recorded_at) : null },
    { key: "created_at", label: isArabic ? "تاريخ الإنشاء" : "Created At", value: article.created_at ? formatDateTime(article.created_at) : null },
    { key: "updated_at", label: isArabic ? "تاريخ التحديث" : "Updated At", value: article.updated_at ? formatDateTime(article.updated_at) : null },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title={t("articles.details.title")}
        breadcrumbs={[
          { label: t("dashboard.home") },
          { label: t("articles.title"), href: "/articles" },
          { label: t("articles.details.title") },
        ]}
        actions={headerActions}
      />

      <Card className="p-4 sm:p-6 flex flex-col lg:flex-row gap-4 sm:gap-6">
        <div className="shrink-0 w-20 h-20 sm:w-24 sm:h-24 self-start bg-primary/20 rounded-lg flex items-center justify-center overflow-hidden relative">
          {featuredImage ? (
            <Image
              src={featuredImage}
              alt={article.title}
              fill
              unoptimized
              sizes="96px"
              className="object-cover"
            />
          ) : (
            <svg className="size-10 text-primary/60" viewBox="0 0 48 48" fill="currentColor">
              <path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.84 0-16-7.16-16-16S15.16 8 24 8s16 7.16 16 16-7.16 16-16 16z" />
              <circle cx="24" cy="24" r="8" />
            </svg>
          )}
        </div>

        <div className="min-w-0 flex-1 flex flex-col gap-4">
          <div className="flex flex-col gap-3 w-full">
            <h2 className="text-base font-bold text-foreground">{article.title}</h2>

            <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs items-center">
              {article.published_at && (
                <div className="flex gap-1 items-center text-muted-foreground">
                  <span>{formatDate(article.published_at)}</span>
                  <Calendar className="size-3.5" />
                </div>
              )}

              {articleAuthor && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <div className="flex gap-1 items-center text-muted-foreground">
                    <span>{articleAuthor}</span>
                  </div>
                </>
              )}

              {articleCategory && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <span className="px-2 py-0.5 rounded border border-border bg-secondary/20 text-secondary">
                    {articleCategory}
                  </span>
                </>
              )}

              {articleStatusLabel && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <span className="px-2 py-0.5 rounded border border-border bg-muted/20">
                    {articleStatusLabel}
                  </span>
                </>
              )}

              {articleTypeLabel && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <span className="px-2 py-0.5 rounded border border-border bg-primary/10 text-primary">
                    {articleTypeLabel}
                  </span>
                </>
              )}

              {latestStats?.recorded_at && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <div className="flex gap-1 items-center text-muted-foreground">
                    <span>{formatDate(latestStats.recorded_at)}</span>
                    <span>{isArabic ? "(آخر تحديث)" : "(Last update)"}</span>
                  </div>
                </>
              )}

              {articleUrl && (
                <>
                  <span className="text-muted-foreground">|</span>
                  <a
                    href={articleUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-primary hover:underline"
                  >
                    {t("articles.viewArticle")}
                  </a>
                </>
              )}
            </div>

            {articleTags.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {articleTags.map((tag) => (
                  <span
                    key={tag}
                    className="inline-flex items-center rounded-md bg-primary/10 text-primary px-2 py-1 text-xs"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            )}

            {article.content && (
              <TruncatedText text={article.content} className="text-sm text-muted-foreground whitespace-pre-line" maxWords={100} fullContentTitle={t("common.fullContent")} showMoreLabel={t("common.showMore")} />
            )}
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("articles.views")}</p>
              <p className="text-lg font-bold text-foreground">
                {(latestStats?.views ?? 0).toLocaleString(numberLocale)}
              </p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{isArabic ? "الزوار الفريدون" : "Unique Views"}</p>
              <p className="text-lg font-bold text-foreground">
                {(latestStats?.unique_views ?? 0).toLocaleString(numberLocale)}
              </p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{isArabic ? "المشاركات" : "Shares"}</p>
              <p className="text-lg font-bold text-foreground">
                {(latestStats?.shares ?? 0).toLocaleString(numberLocale)}
              </p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("articles.searchAppearances")}</p>
              <p className="text-lg font-bold text-foreground">
                {(latestStats?.search_impressions ?? 0).toLocaleString(numberLocale)}
              </p>
            </div>
          </div>
        </div>
      </Card>

      <Card className="p-4 sm:p-6">
        <h3 className="text-base font-semibold text-foreground mb-4">{isArabic ? "بيانات المقال الكاملة" : "Complete Article Data"}</h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
          {articleDataRows.map((row) => (
            <div key={row.key} className="rounded-lg border border-border p-3 bg-muted/20">
              <p className="text-xs text-muted-foreground">{row.label}</p>
              <p className="text-sm text-foreground break-words mt-1">{formatValue(row.value)}</p>
            </div>
          ))}
        </div>
      </Card>

      {latestStats?.traffic_sources && !Array.isArray(latestStats.traffic_sources) && (
        <Card className="p-4 sm:p-6">
          <h3 className="text-base font-semibold text-foreground mb-4">{t("articles.trafficSources")}</h3>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("articles.organic")}</p>
              <p className="text-lg font-bold text-foreground">{latestStats.traffic_sources.organic}</p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("articles.direct")}</p>
              <p className="text-lg font-bold text-foreground">{latestStats.traffic_sources.direct}</p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("articles.social")}</p>
              <p className="text-lg font-bold text-foreground">{latestStats.traffic_sources.social}</p>
            </div>
            <div className="bg-muted/30 rounded-lg px-3 sm:px-6 py-3 flex flex-col gap-2 items-center min-w-0">
              <p className="text-xs text-muted-foreground">{t("ads.paid")}</p>
              <p className="text-lg font-bold text-foreground">{latestStats.traffic_sources.paid}</p>
            </div>
          </div>
        </Card>
      )}

      <Card className="overflow-hidden">
        <div className="px-4 sm:px-6 py-3 sm:py-4 border-b border-border">
          <h3 className="text-base font-semibold text-foreground">{t("articles.statistics.title")}</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            {isArabic ? "يعرض هذا القسم سجل الإحصائيات الفعلي القادم من API المقال." : "This section shows the actual statistics history returned by the article API."}
          </p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-muted/30">
              <tr>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {t("articles.statistics.date")}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {t("articles.statistics.views")}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {isArabic ? "الزوار الفريدون" : "Unique Views"}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {isArabic ? "التعليقات" : "Comments"}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {isArabic ? "المشاركات" : "Shares"}
                </th>
                {/* <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {t("articles.statistics.searchAppearances")}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {isArabic ? "نقرات البحث" : "Search Clicks"}
                </th>
                <th className="px-6 py-3 text-xs font-semibold text-muted-foreground text-center">
                  {isArabic ? "نسبة النقر" : "CTR"}
                </th> */}
              </tr>
            </thead>
            <tbody>
              {statsRows.length === 0 && (
                <tr>
                  <td colSpan={8} className="px-6 py-6 text-sm text-center text-muted-foreground">
                    {isArabic ? "لا توجد إحصاءات متاحة" : "No statistics available"}
                  </td>
                </tr>
              )}
              {statsRows.map((stat, index) => (
                <tr key={String(stat.id)} className={index !== statsRows.length - 1 ? "border-b border-border" : ""}>
                  <td className="px-6 py-4 text-sm text-foreground text-center">
                    {stat.recorded_at ? formatDate(stat.recorded_at) : "-"}
                  </td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.views)}</td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.unique_views)}</td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.comments)}</td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.shares)}</td>
                  {/* <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.search_impressions)}</td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatMetricValue(stat.search_clicks)}</td>
                  <td className="px-6 py-4 text-sm text-foreground text-center">{formatValue(stat.search_ctr)}</td> */}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <ArticleDialog
        open={isEditDialogOpen}
        onOpenChange={setIsEditDialogOpen}
        onSubmit={handleEditSubmit}
        isLoading={isSubmitting}
        mode="edit"
        initialData={editInitialData}
        submitAction={{ actionKey: "articles.update" }}
      />

      <ConfirmationDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        title={t("articles.deleteArticle") || "Delete Article"}
        description={t("articles.deleteArticleConfirmation") || "Are you sure you want to delete this article? This action cannot be undone."}
        confirmLabel={t("common.delete")}
        cancelLabel={t("common.cancel")}
        onConfirm={handleDelete}
        confirmAction={{ actionKey: "articles.delete" }}
        variant="danger"
      />
    </div>
  );
}
