"use client";

import { AdvertisementsSection } from "@/components/dashboard/ads/advertisements-section";
import { DashboardFilters } from "@/components/dashboard/home/dashboard-filters";
import { DashboardStatsCards } from "@/components/dashboard/home/dashboard-stats-cards";
import { RecentActivities } from "@/components/dashboard/home/recent-activities";
import { NewsArticlesSection } from "@/components/dashboard/news/news-articles-section";
import { PhaseProgressOverview } from "@/components/dashboard/projects/phase-progress-overview";
import { ProjectHeaderBanner } from "@/components/dashboard/projects/project-header-banner";
import { SocialMediaStats } from "@/components/dashboard/social-media/social-media-stats";
import { PageHeader } from "@/components/layout";
import {
  SkeletonCard,
  SkeletonChart,
  SkeletonList,
} from "@/components/shared/skeleton";
import { Card, Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui";
import { useProject } from "@/contexts/project-context";
import { usePhases, useProjectStatistics } from "@/hooks";
import { useDashboard } from "@/hooks/use-dashboard";
import { shouldShowStatisticsSections } from "@/lib/utils/statistics-visibility";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import React from "react";

interface DashboardHomeContainerProps {
  showHeader?: boolean;
}

function EmptySectionCard({ title, description }: { title: string; description: string }) {
  return (
    <Card className="p-6">
      <Empty className="border-border/60 md:p-10">
        <EmptyHeader className="max-w-none">
          <EmptyTitle className="text-base sm:text-lg">{title}</EmptyTitle>
          <EmptyDescription>{description}</EmptyDescription>
        </EmptyHeader>
      </Empty>
    </Card>
  );
}

export function DashboardHomeContainer({ showHeader = true }: DashboardHomeContainerProps) {
  const t = useTranslations();
  const searchParams = useSearchParams();
  const urlProjectId = searchParams.get("project_id");
  const startDate = searchParams.get("start_date");
  const endDate = searchParams.get("end_date");

  const {
    projectId: contextProjectId,
    projectName: contextProjectName,
    setProject,
    clearProject,
  } = useProject();

  const { dashboard, isLoading: isDashboardLoading } = useDashboard(
    urlProjectId != null
      ? { project_id: urlProjectId }
      : contextProjectId
        ? { project_id: contextProjectId }
        : undefined,
  );

  const requestedProjectId = urlProjectId || contextProjectId || null;
  const fallbackProjectRecord = dashboard?.projects?.[0] ?? null;
  const selectedProjectRecord =
    requestedProjectId && dashboard?.projects
      ? dashboard.projects.find(
          (project) => String(project.id) === requestedProjectId,
        ) ?? fallbackProjectRecord
      : fallbackProjectRecord;
  const effectiveProjectId = selectedProjectRecord
    ? String(selectedProjectRecord.id)
    : null;

  React.useEffect(() => {
    if (!dashboard?.projects) {
      return;
    }

    if (dashboard.projects.length === 0) {
      if (contextProjectId || contextProjectName) {
        clearProject();
      }
      return;
    }

    if (!selectedProjectRecord) {
      return;
    }

    const nextProjectId = String(selectedProjectRecord.id);
    const nextProjectProgress = selectedProjectRecord.progress_percentage || 0;

    if (
      contextProjectId !== nextProjectId ||
      contextProjectName !== selectedProjectRecord.name
    ) {
      setProject(
        nextProjectId,
        selectedProjectRecord.name,
        nextProjectProgress,
        selectedProjectRecord.name_translations,
      );
    }
  }, [
    clearProject,
    contextProjectId,
    contextProjectName,
    dashboard?.projects,
    selectedProjectRecord,
    setProject,
  ]);

  const { phases } = usePhases({ projectId: effectiveProjectId || undefined });

  const {
    statistics,
    socialMedia,
    news,
    articles,
    ads,
    timeSeries,
    isLoading: isStatisticsLoading,
  } = useProjectStatistics({
    projectId: effectiveProjectId,
    period: "month",
    start_date: startDate || undefined,
    end_date: endDate || undefined,
  });

  const isLoading = isDashboardLoading || isStatisticsLoading;

  const selectedProject =
    effectiveProjectId &&
    dashboard?.selected_project &&
    String(dashboard.selected_project.id) === effectiveProjectId
      ? dashboard.selected_project
      : null;

  const fullProject = selectedProject
    ? dashboard?.projects?.find((p) => p.id === selectedProject.id)
    : null;
  const showSections = React.useMemo(
    () => shouldShowStatisticsSections(statistics),
    [statistics],
  );

  return (
    <div className="">
      {showHeader && (
        <PageHeader
          title={t("dashboard.home")}
          breadcrumbs={[{ label: t("dashboard.home") }]}
        />
      )}

      <div className="px-6 py-6">
        <DashboardFilters projects={dashboard?.projects || []} />
      </div>

      {isLoading ? (
        <div className="space-y-6 px-6">
          <Card className="p-6">
            <div className="h-56 rounded-2xl bg-muted animate-pulse" />
          </Card>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
            <SkeletonCard count={10} />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="p-6">
              <SkeletonChart />
            </Card>
            <Card className="p-6">
              <SkeletonList items={5} />
            </Card>
          </div>

          <Card className="p-6">
            <SkeletonChart />
          </Card>
        </div>
      ) : (
        <div className="space-y-6 ">
          {selectedProject && fullProject && (
            <ProjectHeaderBanner
              projectName={selectedProject.name}
              name_translations={selectedProject.name_translations}
              description={fullProject.description}
              description_translations={fullProject.description_translations}
              progressPercentage={selectedProject.stats?.overall_progress || 0}
              endDate={fullProject.end_date}
              daysRemaining={selectedProject.delay_summary?.project_days_remaining}
            />
          )}

          <DashboardStatsCards stats={selectedProject?.stats} />

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 p-0">
            <PhaseProgressOverview
              stats={selectedProject?.stats}
              phases={phases}
            />

            <RecentActivities
              activities={dashboard?.recent_activities}
              projectId={effectiveProjectId}
            />
          </div>

          {showSections.socialMedia ? (
            <SocialMediaStats
              socialMediaStats={socialMedia}
              timeSeries={timeSeries}
            />
          ) : (
            <EmptySectionCard
              title={t("dashboard.socialStats.title")}
              description={t("dashboard.sectionEmpty", { section: t("dashboard.socialStats.title") })}
            />
          )}

          {showSections.newsArticles ? (
            <NewsArticlesSection
              newsStats={news}
              articlesStats={articles}
              timeSeries={timeSeries}
            />
          ) : (
            <EmptySectionCard
              title={t("dashboard.newsArticlesStats.title")}
              description={t("dashboard.sectionEmpty", {
                section: t("dashboard.newsArticlesStats.title"),
              })}
            />
          )}

          {showSections.advertisements ? (
            <AdvertisementsSection adsStats={ads} timeSeries={timeSeries} />
          ) : (
            <EmptySectionCard
              title={t("dashboard.advertisementsStats.title")}
              description={t("dashboard.sectionEmpty", {
                section: t("dashboard.advertisementsStats.title"),
              })}
            />
          )}
        </div>
      )}
    </div>
  );
}
