"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { PageHeader } from "@/components/layout";
import { ArticleDialog } from "@/components/dashboard/articles/article-dialog";
import { ConfirmationDialog } from "@/components/shared";
import { EmptyState } from "@/components/shared/empty-state";
import {
  FilterBar,
  type AppliedFilter,
} from "@/components/shared/filter-bar";
import type { DateRange } from "@/components/datepicker/preset-shortcuts";
import { Pagination } from "@/components/shared/pagination";
import { Card } from "@/components/ui";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";
import { useArticles, useArticleMutations, useArticleActions } from "@/hooks/use-articles";
import { useRouter } from "@/i18n/routing";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { formatDateToYMD } from "@/lib/date-utils";
import type { Article, CreateArticleRequest } from "@/types";
import {
  Calendar,
  Eye,
  FileText,
  Link2,
  MoreVertical,
  Pencil,
  Plus,
  RefreshCw,
  Trash2,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import Image from "next/image";
import { useMemo, useState } from "react";
import { toast } from "sonner";

interface ArticlesListContainerProps {
  showHeader?: boolean;
}

export function ArticlesListContainer({ showHeader = true }: ArticlesListContainerProps) {
  const t = useTranslations();
  const locale = useLocale();
  const isArabic = locale === "ar";
  const { formatDate } = useFormattedDate();
  const router = useRouter();
  const numberLocale = "en-US";
  const [searchInput, setSearchInput] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  const [pendingStartDate, setPendingStartDate] = useState<Date | null>(null);
  const [pendingEndDate, setPendingEndDate] = useState<Date | null>(null);
  const [appliedStartDate, setAppliedStartDate] = useState<Date | null>(null);
  const [appliedEndDate, setAppliedEndDate] = useState<Date | null>(null);

  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const params = useMemo(
    () => ({
      search: searchTerm || undefined,
      ...(appliedStartDate && appliedEndDate
        ? formatDateToYMD(appliedStartDate) === formatDateToYMD(appliedEndDate)
          ? { date: formatDateToYMD(appliedStartDate) }
          : {
              start_date: formatDateToYMD(appliedStartDate),
              end_date: formatDateToYMD(appliedEndDate),
            }
        : {
            ...(appliedStartDate ? { start_date: formatDateToYMD(appliedStartDate) } : {}),
            ...(appliedEndDate ? { end_date: formatDateToYMD(appliedEndDate) } : {}),
          }),
    }),
    [searchTerm, appliedStartDate, appliedEndDate]
  );

  const { articles, isLoading, pagination, refetch } = useArticles(params);
  const { createArticle, updateArticle, deleteArticle } = useArticleMutations();
  const { syncArticles, refreshArticles, isSyncing, isRefreshing } = useArticleActions();

  const handleSearch = () => {
    setSearchTerm(searchInput);
  };

  const handlePendingFilterChange = (id: string, value: string | Date | DateRange | null) => {
    if (id === "startDate") {
      setPendingStartDate(value as Date | null);
    } else if (id === "endDate") {
      setPendingEndDate(value as Date | null);
    }
  };

  const handleApplyFilters = () => {
    setAppliedStartDate(pendingStartDate);
    setAppliedEndDate(pendingEndDate);
  };

  const handleClearFilters = () => {
    setPendingStartDate(null);
    setPendingEndDate(null);
    setAppliedStartDate(null);
    setAppliedEndDate(null);
  };

  const handleRemoveAppliedFilter = (id: string) => {
    if (id === "startDate") {
      setPendingStartDate(null);
      setAppliedStartDate(null);
    } else if (id === "endDate") {
      setPendingEndDate(null);
      setAppliedEndDate(null);
    }
  };

  const appliedFilters = useMemo<AppliedFilter[]>(() => {
    const filters: AppliedFilter[] = [];

    if (appliedStartDate) {
      filters.push({
        id: "startDate",
        label: `${isArabic ? "تاريخ البداية" : "Start Date"}: ${formatDate(appliedStartDate)}`,
        value: formatDateToYMD(appliedStartDate),
      });
    }

    if (appliedEndDate) {
      filters.push({
        id: "endDate",
        label: `${isArabic ? "تاريخ النهاية" : "End Date"}: ${formatDate(appliedEndDate)}`,
        value: formatDateToYMD(appliedEndDate),
      });
    }

    return filters;
  }, [appliedStartDate, appliedEndDate, formatDate, isArabic]);

  const handleSync = async () => {
    try {
      await syncArticles();
      refetch();
    } catch {
      // Error already handled in hook
    }
  };

  const handleRefresh = async () => {
    try {
      await refreshArticles();
      refetch();
    } catch {
      // Error already handled in hook
    }
  };

  const handleCreateSubmit = async (data: CreateArticleRequest) => {
    setIsSubmitting(true);
    try {
      await createArticle(data);
      refetch();
    } catch (error: unknown) {
      const errorMessage =
        (error as { message?: string })?.message ||
        t("articles.errorCreatingArticle") ||
        "Failed to create article";
      toast.error(errorMessage);
      throw error;
    } finally {
      setIsSubmitting(false);
    }
  };

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

    setIsSubmitting(true);
    try {
      await updateArticle(selectedArticle.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 (!selectedArticle) return;

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

  const openEditDialog = (article: Article) => {
    setSelectedArticle(article);
    setIsEditDialogOpen(true);
  };

  const openDeleteDialog = (article: Article) => {
    setSelectedArticle(article);
    setIsDeleteDialogOpen(true);
  };

  const navigateToDetail = (id: number) => {
    router.push(`/articles/${id}`);
  };

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

  return (
    <div className="">
      {showHeader && (
        <PageHeader
          title={t("articles.title")}
          breadcrumbs={[
            { label: t("dashboard.home") },
            { label: t("projects.title"), href: "/projects" },
            { label: t("projects.details.title") },
            { label: t("articles.title") },
          ]}
          actions={[
            {
              label: t("articles.sync"),
              icon: <Link2 className="size-4" />,
              onClick: handleSync,
              variant: "outline" as const,
              disabled: isSyncing,
              actionKey: "projects.sync_content",
            },
            {
              label: t("articles.refresh"),
              icon: <RefreshCw className={`size-4 ${isRefreshing ? "animate-spin" : ""}`} />,
              onClick: handleRefresh,
              variant: "outline" as const,
              disabled: isRefreshing,
              actionKey: "projects.sync_content",
            },
            {
              label: t("articles.addArticle"),
              icon: <Plus className="size-4" />,
              onClick: () => setIsAddDialogOpen(true),
              actionKey: "articles.create",
            },
          ]}
        />
      )}

      <div className="rounded-2xl flex flex-col overflow-hidden">
        <FilterBar
          searchPlaceholder={t("articles.searchPlaceholder")}
          searchValue={searchInput}
          onSearchChange={setSearchInput}
          onSearch={handleSearch}
          searchButtonLabel={t("articles.search")}
          filterFields={[
            {
              type: "date",
              id: "startDate",
              label: isArabic ? "تاريخ البداية" : "Start Date",
              placeholder: isArabic ? "تاريخ البداية" : "Start Date",
            },
            {
              type: "date",
              id: "endDate",
              label: isArabic ? "تاريخ النهاية" : "End Date",
              placeholder: isArabic ? "تاريخ النهاية" : "End Date",
            },
          ]}
          pendingFilters={{ startDate: pendingStartDate, endDate: pendingEndDate }}
          appliedFilters={appliedFilters}
          onPendingFilterChange={handlePendingFilterChange}
          onApplyFilters={handleApplyFilters}
          onClearFilters={handleClearFilters}
          onRemoveAppliedFilter={handleRemoveAppliedFilter}
          filterButtonLabel={t("common.filter")}
          applyButtonLabel={t("common.apply")}
          cancelButtonLabel={t("common.clear")}
          className="px-2 py-2"
        />

        <Card className="">
          {isLoading ? (
            <div className="flex flex-col">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className={`flex gap-4 px-6 py-6 ${i !== 4 ? "border-b border-border" : ""}`}>
                  <Skeleton className="shrink-0 w-24 h-24 rounded-lg" />
                  <div className="flex-1 flex flex-col gap-3">
                    <Skeleton className="h-5 w-3/4" />
                    <Skeleton className="h-4 w-full" />
                    <Skeleton className="h-4 w-1/2" />
                    <Skeleton className="h-4 w-2/3" />
                  </div>
                  <Skeleton className="h-6 w-20" />
                </div>
              ))}
            </div>
          ) : articles.length === 0 ? (
            <EmptyState
              icon={FileText}
              title={t("articles.noArticlesYet")}
              description={t("articles.noArticlesDescription")}
              action={{
                label: t("articles.addArticle"),
                onClick: () => setIsAddDialogOpen(true),
                actionKey: "articles.create",
              }}
            />
          ) : (
            <div className="flex flex-col">
              {articles.map((article, index) => {
                const articleAuthor = article.author_name || article.author;
                const articleImage = article.featured_image_url || article.featured_image;
                const articleUrl = article.article_url;
                const articleTypeLabel = article.article_type_label || article.article_type;
                const articleStatusLabel = article.status_label || article.status;
                const articleViews = article.stats?.views ?? article.statistics?.views_count ?? 0;
                const articleUniqueViews = article.stats?.unique_views ?? article.statistics?.unique_views_count ?? 0;
                const articleShares = article.stats?.shares ?? article.statistics?.shares_count ?? 0;
                const articleComments = article.stats?.comments ?? article.statistics?.comments_count ?? 0;
                const articleRecordedAt =
                  article.stats?.recorded_at ||
                  article.statistics?.recorded_at ||
                  article.published_at ||
                  null;

                return (
                  <div key={article.id} className={`flex gap-4 px-6 py-6 ${index !== articles.length - 1 ? "border-b border-border" : ""}`}>
                    <div className="shrink-0 w-24 h-24 bg-primary/20 rounded-lg flex items-center justify-center overflow-hidden relative">
                      {articleImage ? (
                        <Image
                          src={articleImage}
                          alt={article.title}
                          fill
                          sizes="96px"
                          className="object-cover"
                        />
                      ) : (
                        <svg
                          className="size-12 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="flex-1 flex flex-col gap-3">
                      <div className="flex flex-col gap-1">
                        <div className="flex items-center gap-2 flex-wrap">
                          <h3 className="text-base font-bold text-foreground">
                            {article.title}
                          </h3>
                          {articleStatusLabel && (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-muted text-muted-foreground">
                              {articleStatusLabel}
                            </span>
                          )}
                          {articleTypeLabel && (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-primary/10 text-primary">
                              {articleTypeLabel}
                            </span>
                          )}
                          {article.category && (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-secondary text-secondary-foreground">
                              {article.category}
                            </span>
                          )}
                        </div>

                        {articleAuthor && (
                          <p className="text-sm text-muted-foreground">{articleAuthor}</p>
                        )}
                      </div>

                      <div className="flex gap-3 text-xs items-center flex-wrap">
                        {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>
                        )}

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

                      <div className="flex gap-4 text-xs flex-wrap">
                        <div className="flex gap-1">
                          <span className="text-muted-foreground">{t("articles.views")}</span>
                          <span className="font-semibold text-foreground">
                            {formatMetricValue(articleViews)}
                          </span>
                        </div>

                        <span className="text-muted-foreground">|</span>

                        <div className="flex gap-1">
                          <span className="text-muted-foreground">{t("articles.uniqueVisitors")}</span>
                          <span className="font-semibold text-foreground">
                            {formatMetricValue(articleUniqueViews)}
                          </span>
                        </div>

                        <span className="text-muted-foreground">|</span>

                        <div className="flex gap-1">
                          <span className="text-muted-foreground">{t("articles.shares")}</span>
                          <span className="font-semibold text-foreground">
                            {formatMetricValue(articleShares)}
                          </span>
                        </div>

                        <span className="text-muted-foreground">|</span>

                        <div className="flex gap-1">
                          <span className="text-muted-foreground">{isArabic ? "التعليقات" : "Comments"}</span>
                          <span className="font-semibold text-foreground">
                            {formatMetricValue(articleComments)}
                          </span>
                        </div>

                        <span className="text-muted-foreground">|</span>

                        <div className="flex gap-1">
                          <span className="text-muted-foreground">{t("articles.form.recordedAt")}</span>
                          <span className="font-semibold text-foreground">
                            {articleRecordedAt ? formatDate(articleRecordedAt) : "-"}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="shrink-0">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreVertical className="size-4" />
                            <span className="sr-only">{t("common.actions")}</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start">
                          <AuthorizedAction action={{ actionKey: "articles.view" }} surface="dropdown">
                            <DropdownMenuItem onClick={() => navigateToDetail(article.id)}>
                              <Eye className="size-4 me-2" />
                              {t("articles.viewDetails")}
                            </DropdownMenuItem>
                          </AuthorizedAction>
                          <AuthorizedAction action={{ actionKey: "articles.update" }} surface="dropdown">
                            <DropdownMenuItem onClick={() => openEditDialog(article)}>
                              <Pencil className="size-4 me-2" />
                              {t("common.edit")}
                            </DropdownMenuItem>
                          </AuthorizedAction>
                          <AuthorizedAction action={{ actionKey: "articles.delete" }} surface="dropdown">
                            <DropdownMenuItem onClick={() => openDeleteDialog(article)} className="text-destructive focus:text-destructive">
                              <Trash2 className="size-4 me-2" />
                              {t("common.delete")}
                            </DropdownMenuItem>
                          </AuthorizedAction>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {!isLoading && articles.length > 0 && pagination && <Pagination {...pagination} />}
        </Card>
      </div>

      <ArticleDialog
        open={isAddDialogOpen}
        onOpenChange={setIsAddDialogOpen}
        onSubmit={handleCreateSubmit}
        isLoading={isSubmitting}
        mode="add"
        submitAction={{ actionKey: "articles.create" }}
      />

      <ArticleDialog
        open={isEditDialogOpen}
        onOpenChange={setIsEditDialogOpen}
        onSubmit={handleEditSubmit}
        isLoading={isSubmitting}
        mode="edit"
        initialData={selectedArticle}
        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>
  );
}
