"use client";

import { AddPostDialog } from "@/components/dashboard/social-media/add-post-dialog";
import { SocialMediaMediaPreview } from "@/components/dashboard/social-media/social-media-media-preview";
import { getPlatformIcon } from "@/components/icons";
import { PageHeader } from "@/components/layout";
import {
  ConfirmationDialog,
  DataTable,
  PostMetaInfo,
  StatMetric,
  type DataTableColumn,
} from "@/components/shared";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useSocialMediaMutations, useSocialMediaPost } from "@/hooks/use-social-media";
import { useRouter } from "@/i18n/routing";
import type { ManualPostInput, PostStatistics } from "@/types";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { ExternalLink, Pencil, Trash2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { useState } from "react";

export function SocialMediaPostDetailContainer() {
  const t = useTranslations();
  const locale = useLocale() as "ar" | "en";
  const { formatDateTime } = useFormattedDate();
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;

  const { data, isLoading, error, refetch } = useSocialMediaPost(id);

  const post = data?.data?.post;
  const statistics = data?.data?.statistics || [];

  const latestStats = statistics[0];

  const { deletePost, updatePost } = useSocialMediaMutations();

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

  const handleEditSubmit = async (data: ManualPostInput) => {
    if (!post) return;

    setIsSubmitting(true);
    try {
      await updatePost(post.id, {
        title: data.title,
        content: data.content,
        post_url: data.post_url,
      });
      refetch();
    } catch {
      // Error toast is handled by the hook
    } finally {
      setIsSubmitting(false);
    }
  };

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

    try {
      const accountId =
        post.account_id ??
        post.account?.id ??
        (post as { social_media_account_id?: number | string }).social_media_account_id ??
        (post as { accountId?: number | string }).accountId;
      await deletePost(post.id, accountId);
      router.push("/social-media/all-posts");
    } catch {
      // Error toast is handled by the hook
    }
  };

  const toNumber = (value: unknown): number => {
    const num = typeof value === "number" ? value : Number(value);
    return Number.isFinite(num) ? num : 0;
  };

  const createdAtLabel = t.has("common.createdAt")
    ? t("common.createdAt")
    : locale === "ar"
      ? "تاريخ الإنشاء"
      : "Created At";

  const updatedAtLabel = t.has("common.updatedAt")
    ? t("common.updatedAt")
    : locale === "ar"
      ? "تاريخ التحديث"
      : "Updated At";

  const statisticsColumns: DataTableColumn<PostStatistics>[] = [
    {
      key: "views_count",
      header: t("socialMedia.views"),
      render: (item) => item.views_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "shares_count",
      header: t("socialMedia.shares"),
      render: (item) => item.shares_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "comments_count",
      header: t("socialMedia.comments"),
      render: (item) => item.comments_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "likes_count",
      header: t("socialMedia.likes"),
      render: (item) => item.likes_count.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "impressions",
      header: t("socialMedia.impressionsField"),
      render: (item) => item.impressions.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "reach",
      header: t("socialMedia.reach"),
      render: (item) => item.reach.toLocaleString(),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "engagement_rate",
      header: t("socialMedia.engagementRate"),
      render: (item) => `${toNumber(item.engagement_rate).toFixed(2)}%`,
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "recorded_at",
      header: t("socialMedia.date"),
      render: (item) => formatDateTime(item.recorded_at),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "created_at",
      header: createdAtLabel,
      render: (item) => formatDateTime(item.created_at),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
    {
      key: "updated_at",
      header: updatedAtLabel,
      render: (item) => formatDateTime(item.updated_at),
      className: "whitespace-nowrap",
      headerClassName: "whitespace-nowrap",
    },
  ];

  if (isLoading) {
    return (
      <div className="space-y-6">
        <PageHeader
          title={t("socialMedia.postDetails")}
          breadcrumbs={[
            { label: t("sidebar.dashboard"), href: "/" },
            { label: t("sidebar.projects"), href: "/projects" },
            { label: t("reports.projectName"), href: "/projects/1" },
            { label: t("sidebar.socialMedia"), href: "/social-media" },
            {
              label: t("socialMedia.publications"),
              href: "/social-media/all-posts",
            },
            { label: t("socialMedia.postDetails") },
          ]}
        />

        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              <Skeleton className="h-16 w-full" />
              <Skeleton className="h-24 w-full" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <Skeleton className="h-64 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error || !post) {
    return (
      <div className="space-y-6">
        <PageHeader
          title={t("socialMedia.postDetails")}
          breadcrumbs={[
            { label: t("sidebar.dashboard"), href: "/" },
            { label: t("sidebar.projects"), href: "/projects" },
            { label: t("reports.projectName"), href: "/projects/1" },
            { label: t("sidebar.socialMedia"), href: "/social-media" },
            {
              label: t("socialMedia.publications"),
              href: "/social-media/all-posts",
            },
            { label: t("socialMedia.postDetails") },
          ]}
        />

        <Card>
          <CardContent className="p-6">
            <div className="rounded-lg border border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-950 p-4">
              <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>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const headerActions = [
    ...(post.post_url
      ? [{
          label: t("socialMedia.viewOnPlatform"),
          icon: <ExternalLink className="h-4 w-4" />,
          onClick: () => window.open(post.post_url, "_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: "social_media.update_post",
    },
    {
      label: t("common.delete"),
      icon: <Trash2 className="h-4 w-4" />,
      onClick: () => setIsDeleteDialogOpen(true),
      variant: "destructive" as const,
      actionKey: "social_media.delete_post",
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title={t("socialMedia.postDetails")}
        breadcrumbs={[
          { label: t("sidebar.dashboard"), href: "/" },
          { label: t("sidebar.projects"), href: "/projects" },
          { label: t("reports.projectName"), href: "/projects/1" },
          { label: t("sidebar.socialMedia"), href: "/social-media" },
          {
            label: t("socialMedia.publications"),
            href: "/social-media/all-posts",
          },
          { label: t("socialMedia.postDetails") },
        ]}
        actions={headerActions}
      />

      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col gap-6">
            <div className="flex flex-col gap-2 items-start w-full">
              <h2 className="text-lg font-bold leading-7 text-foreground text-start w-full">
                {post.title || post.content}
              </h2>

              <PostMetaInfo
                publishDate={post.published_at}
                publishDateLabel={t("socialMedia.publishDate")}
                platformName={post.platform_label || post.platform}
                platformLabel={t("socialMedia.platform")}
                platformIcon={getPlatformIcon(post.platform)}
              />

              {post.created_at ? (
                <p className="text-xs text-muted-foreground text-start whitespace-nowrap">
                  {createdAtLabel}: {formatDateTime(post.created_at)}
                </p>
              ) : null}

              {post.media_url ? (
                <SocialMediaMediaPreview
                  src={post.media_url}
                  alt={post.title || post.content || t("socialMedia.postMedia")}
                  containerClassName="mt-2 w-full overflow-hidden rounded-xl border bg-muted/20 p-2"
                  className="max-h-[420px] w-full rounded-lg object-contain"
                />
              ) : null}
            </div>

            <div>
              <div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-6 gap-3 w-full">
                <StatMetric label={t("socialMedia.views")} value={post.views_count ?? latestStats?.views_count ?? 0} />
                <StatMetric label={t("socialMedia.shares")} value={post.shares_count ?? latestStats?.shares_count ?? 0} />
                <StatMetric label={t("socialMedia.comments")} value={post.comments_count ?? latestStats?.comments_count ?? 0} />
                <StatMetric label={t("socialMedia.likes")} value={post.likes_count ?? latestStats?.likes_count ?? 0} />
                <StatMetric label={t("socialMedia.impressionsField")} value={post.impressions ?? latestStats?.impressions ?? 0} />
                <StatMetric label={t("socialMedia.reach")} value={post.reach ?? latestStats?.reach ?? 0} />
                <StatMetric label={t("socialMedia.engagementRate")} value={`${toNumber(post.engagement_rate ?? latestStats?.engagement_rate ?? "0").toFixed(2)}%`} />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="border-b px-6 py-4">
          <CardTitle className="text-base font-semibold text-foreground text-start">
            {t("socialMedia.statisticsLog")}
          </CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          {statistics.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">{t("socialMedia.noStatisticsYet")}</div>
          ) : (
            <DataTable
              data={statistics}
              columns={statisticsColumns}
              keyExtractor={(item) => item.id.toString()}
              className="overflow-x-auto overflow-y-hidden"
            />
          )}
        </CardContent>
      </Card>

      {post && latestStats && (
        <AddPostDialog
          open={isEditDialogOpen}
          onOpenChange={setIsEditDialogOpen}
          onSubmit={handleEditSubmit}
          isLoading={isSubmitting}
          mode="edit"
          platform={post.platform}
          initialData={{
            title: post.title || post.content || "",
            content: post.content || "",
            post_url: post.post_url || "",
            media_url: post.media_url || "",
            publishDate: post.published_at?.split(" ")[0] || "",
            impressions: latestStats.impressions || 0,
            reach: latestStats.reach || 0,
            likes: latestStats.likes_count || 0,
            views: latestStats.views_count || 0,
            shares: latestStats.shares_count || 0,
            comments: latestStats.comments_count || 0,
          }}
        />
      )}

      <ConfirmationDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        title={t("socialMedia.deletePost") || "Delete Post"}
        description={t("socialMedia.deletePostConfirmation") || "Are you sure you want to delete this post? This action cannot be undone."}
        confirmLabel={t("common.delete")}
        cancelLabel={t("common.cancel")}
        onConfirm={handleDelete}
        confirmAction={{ actionKey: "social_media.delete_post" }}
        variant="danger"
      />
    </div>
  );
}
