"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { LinkManualDialog, LinkViaApiDialog, SocialMediaAccountCard } from "@/components/dashboard/social-media";
import { FilterBar, type AppliedFilter, type FilterField } from "@/components/shared/filter-bar";
import { getPlatformIcon } from "@/components/icons";
import { PageHeader } from "@/components/layout";
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 { useSocialMediaOverview } from "@/hooks/use-social-media";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { useRouter } from "@/i18n/routing";
import type { SocialMediaPost as Post } from "@/types";
import {
  ArrowLeft,
  ArrowRight,
  BarChart3,
  Calendar,
  ChevronDown,
  Eye,
  Plus,
  StickyNote,
  User,
} from "lucide-react";
import { useTranslations, useLocale } from "next-intl";
import { useState, useMemo, useCallback } from "react";

type SocialMediaOverviewContainerProps = {
  variant?: "overview" | "reports";
};

type SocialMetricKey =
  | "likes"
  | "comments"
  | "shares"
  | "views"
  | "reach"
  | "impressions"
  | "engagementRate";

type ContentTypeKey = "all" | "text" | "image" | "video" | "media";

const resolvePlatformLabel = (platform: string) => {
  switch (platform) {
    case "facebook":
      return "Facebook";
    case "instagram":
      return "Instagram";
    case "twitter":
      return "Twitter";
    case "linkedin":
      return "LinkedIn";
    default:
      return platform.charAt(0).toUpperCase() + platform.slice(1);
  }
};

const getPostMetricValue = (post: Post, metric: SocialMetricKey): number => {
  switch (metric) {
    case "likes":
      return post.likes_count ?? 0;
    case "comments":
      return post.comments_count ?? 0;
    case "shares":
      return post.shares_count ?? 0;
    case "views":
      return post.views_count ?? 0;
    case "reach":
      return post.reach ?? 0;
    case "impressions":
      return post.impressions ?? 0;
    case "engagementRate": {
      const rate =
        typeof post.engagement_rate === "string"
          ? Number(post.engagement_rate)
          : 0;
      return Number.isFinite(rate) ? rate : 0;
    }
  }
};

const getPostContentType = (post: Post): Exclude<ContentTypeKey, "all"> => {
  if (!post.media_url) return "text";

  const lower = post.media_url.toLowerCase();
  if (/\.(mp4|mov|webm|m4v)(\?|$)/.test(lower)) return "video";
  if (/\.(png|jpg|jpeg|gif|webp|svg)(\?|$)/.test(lower)) return "image";
  return "media";
};

export function SocialMediaOverviewContainer({
  variant = "overview",
}: SocialMediaOverviewContainerProps) {
  const t = useTranslations();
  const router = useRouter();
  const { formatDate } = useFormattedDate();
  const locale = useLocale();
  const isArabic = locale === "ar";

  const [linkViaApiOpen, setLinkViaApiOpen] = useState(false);
  const [linkManualOpen, setLinkManualOpen] = useState(false);

  // Filter state
  const [searchInput, setSearchInput] = useState("");
  const [pendingStartDate, setPendingStartDate] = useState<Date | null>(null);
  const [pendingEndDate, setPendingEndDate] = useState<Date | null>(null);
  const [pendingPlatform, setPendingPlatform] = useState<string>("all");
  const [pendingMetric, setPendingMetric] = useState<SocialMetricKey | "all">(
    "all",
  );
  const [pendingMetricMin, setPendingMetricMin] = useState<string>("");
  const [pendingCampaign, setPendingCampaign] = useState<string>("");
  const [pendingContentType, setPendingContentType] =
    useState<ContentTypeKey>("all");

  const [appliedStartDate, setAppliedStartDate] = useState<Date | null>(null);
  const [appliedEndDate, setAppliedEndDate] = useState<Date | null>(null);
  const [appliedPlatform, setAppliedPlatform] = useState<string>("all");
  const [appliedMetric, setAppliedMetric] = useState<SocialMetricKey | "all">(
    "all",
  );
  const [appliedMetricMin, setAppliedMetricMin] = useState<string>("");
  const [appliedCampaign, setAppliedCampaign] = useState<string>("");
  const [appliedContentType, setAppliedContentType] =
    useState<ContentTypeKey>("all");

  const overviewParams = useMemo(() => {
    if (!appliedPlatform || appliedPlatform === "all") return {};
    return { platform: appliedPlatform };
  }, [appliedPlatform]);

  const { data, isLoading, error, refetch } = useSocialMediaOverview(
    overviewParams,
  );

  const accounts = data?.data?.accounts || [];
  const posts = data?.data?.posts?.data || [];

  const filterFields: FilterField[] = useMemo(
    () => [
      {
        type: "select",
        id: "platform",
        label: isArabic ? "المنصة" : "Platform",
        placeholder: isArabic ? "اختر" : "Select",
        options: [
          { value: "all", label: isArabic ? "الكل" : "All" },
          { value: "facebook", label: "Facebook" },
          { value: "instagram", label: "Instagram" },
          { value: "twitter", label: "Twitter" },
          { value: "linkedin", label: "LinkedIn" },
        ],
      },
      {
        type: "select",
        id: "metric",
        label: isArabic ? "المؤشر" : "Metric",
        placeholder: isArabic ? "اختر" : "Select",
        options: [
          { value: "all", label: isArabic ? "الكل" : "All" },
          { value: "likes", label: isArabic ? "الإعجابات" : "Likes" },
          { value: "comments", label: isArabic ? "التعليقات" : "Comments" },
          { value: "shares", label: isArabic ? "المشاركات" : "Shares" },
          { value: "reach", label: isArabic ? "الوصول" : "Reach" },
          {
            value: "impressions",
            label: isArabic ? "مرات الظهور" : "Impressions",
          },
          { value: "views", label: isArabic ? "المشاهدات" : "Views" },
          {
            value: "engagementRate",
            label: isArabic ? "معدل التفاعل" : "Engagement rate",
          },
        ],
      },
      {
        type: "text",
        id: "metricMin",
        label: isArabic ? "الحد الأدنى" : "Min value",
        placeholder: isArabic ? "مثال: 100" : "e.g. 100",
      },
      {
        type: "select",
        id: "contentType",
        label: isArabic ? "نوع المحتوى" : "Content type",
        placeholder: isArabic ? "اختر" : "Select",
        options: [
          { value: "all", label: isArabic ? "الكل" : "All" },
          { value: "text", label: isArabic ? "نص" : "Text" },
          { value: "image", label: isArabic ? "صورة" : "Image" },
          { value: "video", label: isArabic ? "فيديو" : "Video" },
          { value: "media", label: isArabic ? "وسائط" : "Media" },
        ],
      },
      {
        type: "text",
        id: "campaign",
        label: isArabic ? "الحملة" : "Campaign",
        placeholder: isArabic ? "اسم الحملة / هاشتاق" : "Campaign name / hashtag",
      },
      {
        type: "date",
        id: "startDate",
        label: t("common.dateFrom"),
        placeholder: t("common.selectDate"),
      },
      {
        type: "date",
        id: "endDate",
        label: t("common.dateTo"),
        placeholder: t("common.selectDate"),
      },
    ],
    [isArabic, t]
  );

  const appliedFilters: AppliedFilter[] = useMemo(() => {
    const filters: AppliedFilter[] = [];
    if (appliedPlatform && appliedPlatform !== "all") {
      filters.push({
        id: "platform",
        label: `${isArabic ? "المنصة" : "Platform"}: ${resolvePlatformLabel(appliedPlatform)}`,
        value: appliedPlatform,
      });
    }
    if (appliedMetric && appliedMetric !== "all") {
      const minText = appliedMetricMin.trim();
      const metricLabel =
        appliedMetric === "likes"
          ? isArabic
            ? "الإعجابات"
            : "Likes"
          : appliedMetric === "comments"
            ? isArabic
              ? "التعليقات"
              : "Comments"
            : appliedMetric === "shares"
              ? isArabic
                ? "المشاركات"
                : "Shares"
              : appliedMetric === "reach"
                ? isArabic
                  ? "الوصول"
                  : "Reach"
                : appliedMetric === "impressions"
                  ? isArabic
                    ? "مرات الظهور"
                    : "Impressions"
                  : appliedMetric === "views"
                    ? isArabic
                      ? "المشاهدات"
                      : "Views"
                    : isArabic
                      ? "معدل التفاعل"
                      : "Engagement rate";
      filters.push({
        id: "metric",
        label: `${isArabic ? "المؤشر" : "Metric"}: ${metricLabel}${minText ? ` ≥ ${minText}` : ""}`,
        value: appliedMetric,
      });
    } else if (appliedMetricMin.trim()) {
      filters.push({
        id: "metricMin",
        label: `${isArabic ? "الحد الأدنى" : "Min value"}: ${appliedMetricMin.trim()}`,
        value: appliedMetricMin.trim(),
      });
    }
    if (appliedContentType !== "all") {
      const contentLabel =
        appliedContentType === "text"
          ? isArabic
            ? "نص"
            : "Text"
          : appliedContentType === "image"
            ? isArabic
              ? "صورة"
              : "Image"
            : appliedContentType === "video"
              ? isArabic
                ? "فيديو"
                : "Video"
              : isArabic
                ? "وسائط"
                : "Media";
      filters.push({
        id: "contentType",
        label: `${isArabic ? "نوع المحتوى" : "Content type"}: ${contentLabel}`,
        value: appliedContentType,
      });
    }
    if (appliedCampaign.trim()) {
      filters.push({
        id: "campaign",
        label: `${isArabic ? "الحملة" : "Campaign"}: ${appliedCampaign.trim()}`,
        value: appliedCampaign.trim(),
      });
    }
    if (appliedStartDate) {
      filters.push({
        id: "startDate",
        label: `${t("common.dateFrom")}: ${formatDate(appliedStartDate)}`,
        value: appliedStartDate.toISOString(),
      });
    }
    if (appliedEndDate) {
      filters.push({
        id: "endDate",
        label: `${t("common.dateTo")}: ${formatDate(appliedEndDate)}`,
        value: appliedEndDate.toISOString(),
      });
    }
    return filters;
  }, [
    appliedCampaign,
    appliedContentType,
    appliedEndDate,
    appliedMetric,
    appliedMetricMin,
    appliedPlatform,
    appliedStartDate,
    isArabic,
    t,
    formatDate,
  ]);

  const handlePendingFilterChange = useCallback(
    (id: string, value: string | Date | null) => {
      if (id === "startDate") {
        setPendingStartDate(value instanceof Date ? value : null);
        return;
      }
      if (id === "endDate") {
        setPendingEndDate(value instanceof Date ? value : null);
        return;
      }

      if (typeof value !== "string") return;

      if (id === "platform") {
        setPendingPlatform(value || "all");
        return;
      }

      if (id === "metric") {
        const next =
          value === "likes" ||
          value === "comments" ||
          value === "shares" ||
          value === "views" ||
          value === "reach" ||
          value === "impressions" ||
          value === "engagementRate"
            ? value
            : "all";
        setPendingMetric(next);
        return;
      }

      if (id === "metricMin") {
        setPendingMetricMin(value);
        return;
      }

      if (id === "campaign") {
        setPendingCampaign(value);
        return;
      }

      if (id === "contentType") {
        const next =
          value === "text" ||
          value === "image" ||
          value === "video" ||
          value === "media"
            ? value
            : "all";
        setPendingContentType(next);
        return;
      }
    },
    []
  );

  const handleApplyFilters = useCallback(() => {
    setAppliedStartDate(pendingStartDate);
    setAppliedEndDate(pendingEndDate);
    setAppliedPlatform(pendingPlatform || "all");
    setAppliedMetric(pendingMetric);
    setAppliedMetricMin(pendingMetricMin);
    setAppliedCampaign(pendingCampaign);
    setAppliedContentType(pendingContentType);
  }, [
    pendingCampaign,
    pendingContentType,
    pendingEndDate,
    pendingMetric,
    pendingMetricMin,
    pendingPlatform,
    pendingStartDate,
  ]);

  const handleClearFilters = useCallback(() => {
    setPendingStartDate(null);
    setPendingEndDate(null);
    setPendingPlatform("all");
    setPendingMetric("all");
    setPendingMetricMin("");
    setPendingCampaign("");
    setPendingContentType("all");
  }, []);

  const handleRemoveAppliedFilter = useCallback((id: string) => {
    if (id === "startDate") {
      setAppliedStartDate(null);
      setPendingStartDate(null);
    }
    if (id === "endDate") {
      setAppliedEndDate(null);
      setPendingEndDate(null);
    }
    if (id === "platform") {
      setAppliedPlatform("all");
      setPendingPlatform("all");
    }
    if (id === "metric") {
      setAppliedMetric("all");
      setPendingMetric("all");
    }
    if (id === "metricMin") {
      setAppliedMetricMin("");
      setPendingMetricMin("");
    }
    if (id === "campaign") {
      setAppliedCampaign("");
      setPendingCampaign("");
    }
    if (id === "contentType") {
      setAppliedContentType("all");
      setPendingContentType("all");
    }
  }, []);

  const handleDialogSuccess = () => {
    refetch();
  };

  const filteredAccounts = useMemo(() => {
    const query = searchInput.trim().toLowerCase();
    return accounts.filter((account) => {
      if (appliedPlatform !== "all" && account.platform !== appliedPlatform) {
        return false;
      }

      if (!query) return true;

      const haystack = `${account.account_name || ""} ${account.account_identifier || ""} ${account.platform || ""}`.toLowerCase();
      return haystack.includes(query);
    });
  }, [accounts, appliedPlatform, searchInput]);

  const filteredPosts = useMemo(() => {
    const query = searchInput.trim().toLowerCase();
    const campaignQuery = appliedCampaign.trim().toLowerCase();
    const minRaw = appliedMetricMin.trim();
    const min = minRaw ? Number(minRaw) : null;
    const metric = appliedMetric !== "all" ? appliedMetric : null;

    return posts.filter((post) => {
      if (appliedPlatform !== "all" && post.platform !== appliedPlatform) {
        return false;
      }

      if (appliedStartDate) {
        const published = new Date(post.published_at);
        if (Number.isFinite(published.getTime()) && published < appliedStartDate) {
          return false;
        }
      }

      if (appliedEndDate) {
        const published = new Date(post.published_at);
        if (Number.isFinite(published.getTime()) && published > appliedEndDate) {
          return false;
        }
      }

      if (appliedContentType !== "all") {
        const contentType = getPostContentType(post);
        if (appliedContentType !== contentType) return false;
      }

      if (campaignQuery) {
        const haystack = `${post.title || ""} ${post.content || ""}`.toLowerCase();
        if (!haystack.includes(campaignQuery)) return false;
      }

      if (query) {
        const haystack = `${post.title || ""} ${post.content || ""} ${post.platform || ""}`.toLowerCase();
        if (!haystack.includes(query)) return false;
      }

      if (metric && min !== null && Number.isFinite(min)) {
        const value = getPostMetricValue(post, metric);
        if (value < min) return false;
      }

      return true;
    });
  }, [
    posts,
    appliedPlatform,
    appliedStartDate,
    appliedEndDate,
    appliedContentType,
    appliedCampaign,
    searchInput,
    appliedMetric,
    appliedMetricMin,
  ]);

  return (
    <div className="space-y-6">
      <PageHeader
        title={
          variant === "reports"
            ? t("socialMedia.reports") || "Reports"
            : t("socialMedia.title")
        }
        breadcrumbs={[
          { label: t("dashboard.home") },
          { label: t("projects.title"), href: "/projects" },
          { label: t("projects.details.title") },
          {
            label:
              variant === "reports"
                ? t("socialMedia.reports") || "Reports"
                : t("socialMedia.title"),
          },
        ]}
        actions={
          <div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-start w-full sm:w-auto">
            <AuthorizedAction
              action={{
                permissions: [
                  "social_media.create",
                  "social_media.manage",
                ],
                require: "any",
              }}
              surface="page"
            >
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="default"
                    className="h-10 gap-2 w-full sm:w-auto"
                  >
                    <ChevronDown className="size-4" />
                    <span>{t("socialMedia.linkNewAccount")}</span>
                    <Plus className="size-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-48">
                  <AuthorizedAction
                    action={{ actionKey: "social_media.connect_account" }}
                    surface="dropdown"
                  >
                    <DropdownMenuItem
                      className="cursor-pointer"
                      onClick={() => setLinkViaApiOpen(true)}
                    >
                      {t("socialMedia.linkViaAPI")}
                    </DropdownMenuItem>
                  </AuthorizedAction>
                  <AuthorizedAction
                    action={{ actionKey: "social_media.create_manual_account" }}
                    surface="dropdown"
                  >
                    <DropdownMenuItem
                      className="cursor-pointer"
                      onClick={() => setLinkManualOpen(true)}
                    >
                      {t("socialMedia.linkManual")}
                    </DropdownMenuItem>
                  </AuthorizedAction>
                </DropdownMenuContent>
              </DropdownMenu>
            </AuthorizedAction>

            <AuthorizedAction
              action={{ actionKey: "social_media.view" }}
              surface="page"
            >
              <Button
                onClick={() => router.push("/social-media/accounts")}
                variant="outline"
                className="h-10 gap-2 w-full sm:w-auto"
              >
                <User className="size-4" />
                <span>{t("socialMedia.accounts")}</span>
              </Button>
            </AuthorizedAction>

            <AuthorizedAction
              action={{ actionKey: "social_media.view" }}
              surface="page"
            >
              <Button
                onClick={() => router.push("/social-media/all-posts")}
                variant="outline"
                className="h-10 gap-2 w-full sm:w-auto"
              >
                <StickyNote className="size-4" />
                <span>{t("socialMedia.publications")}</span>
              </Button>
            </AuthorizedAction>
            {variant !== "reports" && (
              <AuthorizedAction
                action={{ actionKey: "social_media.view" }}
                surface="page"
              >
                <Button
                  onClick={() => router.push("/social-media/reports")}
                  variant="default"
                  className="h-10 gap-2 w-full sm:w-auto bg-amber-500 hover:bg-amber-600 text-white"
                >
                  {isArabic ? (
                    <>
                      <span>{t("socialMedia.reportsButton")}</span>
                      <BarChart3 className="size-4" />
                    </>
                  ) : (
                    <>
                      <BarChart3 className="size-4" />
                      <span>{t("socialMedia.reportsButton")}</span>
                    </>
                  )}
                </Button>
              </AuthorizedAction>
            )}
          </div>
        }
      />

      {error && (
        <Card className="p-4 border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-950">
          <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>
        </Card>
      )}

   

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, i) => (
            <Card key={i} className="p-6">
              <Skeleton className="h-12 w-12 rounded-full mb-4" />
              <Skeleton className="h-4 w-32 mb-2" />
              <Skeleton className="h-3 w-24 mb-4" />
              <div className="flex gap-4">
                <Skeleton className="h-10 w-20" />
                <Skeleton className="h-10 w-20" />
              </div>
            </Card>
          ))
        ) : filteredAccounts.length === 0 ? (
          <div className="col-span-full text-center py-12 text-muted-foreground">
            {appliedFilters.length > 0 || searchInput.trim()
              ? isArabic
                ? "لا توجد نتائج مطابقة"
                : "No matching results"
              : t("socialMedia.noAccountsYet")}
          </div>
        ) : (
          filteredAccounts.map((account) => (
            <SocialMediaAccountCard
              key={account.id}
              account={account}
              variant="default"
            />
          ))
        )}
      </div>

      <Card className=" mt-7">
        <div className="px-6 py-4 border-b border-border flex items-center justify-between">
          <h2 className="text-lg font-semibold">
            {t("socialMedia.latestPublications")}
          </h2>
          <AuthorizedAction
            action={{ actionKey: "social_media.view" }}
            surface="inline"
          >
            <Button
              onClick={() => router.push("/social-media/all-posts")}
              variant="outline"
              className="h-10 gap-2"
            >
            
              {t("socialMedia.allPublications")}
              {locale === "ar" ? <ArrowLeft className="size-4" /> : <ArrowRight className="size-4" />}
            </Button>
          </AuthorizedAction>
        </div>

        <div className="p-6">
          {isLoading ? (
            <div className="flex flex-col gap-4">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="flex items-center justify-between py-4">
                  <div className="flex-1">
                    <Skeleton className="h-4 w-3/4 mb-2" />
                    <Skeleton className="h-3 w-1/2" />
                  </div>
                  <Skeleton className="h-6 w-20" />
                </div>
              ))}
            </div>
          ) : filteredPosts.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              {appliedFilters.length > 0 || searchInput.trim()
                ? isArabic
                  ? "لا توجد نتائج مطابقة"
                  : "No matching results"
                : t("socialMedia.noPostsYet")}
            </div>
          ) : (
            <div className="flex flex-col ">
              {filteredPosts.map((post, index) => (
                <PostListItem
                  key={post.id}
                  post={post}
                  isLast={index === filteredPosts.length - 1}
                  formatDate={formatDate}
                  onViewDetails={() =>
                    router.push(`/social-media/post/${post.id}`)
                  }
                  translations={{
                    views: t("socialMedia.views"),
                    viewDetails: t("socialMedia.viewDetails"),
                  }}
                />
              ))}
            </div>
          )}
        </div>
      </Card>

      <LinkViaApiDialog
        open={linkViaApiOpen}
        onOpenChange={setLinkViaApiOpen}
        onSuccess={handleDialogSuccess}
      />
      <LinkManualDialog
        open={linkManualOpen}
        onOpenChange={setLinkManualOpen}
        onSuccess={handleDialogSuccess}
      />
    </div>
  );
}

interface PostListItemProps {
  post: Post;
  isLast: boolean;
  formatDate: (date: string) => string;
  onViewDetails: () => void;
  translations: {
    views: string;
    viewDetails: string;
  };
}

function PostListItem({
  post,
  isLast,
  formatDate,
  onViewDetails,
  translations,
}: PostListItemProps) {
  return (
    <div
      className={`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 py-4 px-4 ${!isLast ? "border-b border-border" : ""}`}
    >
      <div className="flex flex-col gap-2 items-start flex-1 w-full sm:w-auto">
        <h3 className="text-sm font-bold text-foreground text-start line-clamp-2">
          {post.title || post.content || "-"}
        </h3>
        {post.content && post.content !== post.title && (
          <p className="text-sm text-muted-foreground text-start line-clamp-2">
            {post.content}
          </p>
        )}

        <div className="flex items-center gap-1 text-xs flex-wrap">
          <div className="flex items-center gap-1">
            {getPlatformIcon(post.platform)}
            <span className="text-muted-foreground capitalize">
              {post.platform}
            </span>
          </div>

          <div className="h-1 w-1 rounded-full bg-border mx-1" />

          <div className="flex items-center gap-1">
            <span className="text-muted-foreground">
              {formatDate(post.published_at)}
            </span>
            <Calendar className="size-3.5 text-muted-foreground" />
          </div>
        </div>
      </div>

      <AuthorizedAction
        action={{ actionKey: "social_media.view_details" }}
        surface="inline"
      >
        <Button
          variant="outline"
          size="sm"
          className="h-8 sm:h-6 gap-1.5 px-3 sm:px-2 text-xs w-full sm:w-auto shrink-0"
          onClick={onViewDetails}
        >
          <Eye className="size-3.5" />
          <span>{translations.viewDetails}</span>
        </Button>
      </AuthorizedAction>
    </div>
  );
}
