"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import Modal from "@/components/elements/Modal";
import { Post } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { getVideoPoster } from "@/lib/explore/postMedia";
import { resolvePostMediaType } from "@/lib/reelsMediaType";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";
import { useAppLanguage } from "@/contexts/LanguageProvider";

type AnalyticsStats = {
  likesCount: number;
  commentsCount: number;
  sendsCount: number;
  sharesCount: number;
  savesCount: number;
  followsFromPost: number;
  offersCount: number;
  viewsCount: number;
  totalWatchMs: number;
  followerViews: number;
  nonFollowerViews: number;
  followerPct: number;
  nonFollowerPct: number;
};

type Props = {
  postData: Post;
  isOpen: boolean;
  onClose: () => void;
};

function formatDuration(ms: number) {
  const totalSec = Math.floor(ms / 1000);
  const h = Math.floor(totalSec / 3600);
  const m = Math.floor((totalSec % 3600) / 60);
  const s = totalSec % 60;
  if (h > 0) {
    return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
  }
  return `${m}:${s.toString().padStart(2, "0")}`;
}

function StatRow({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string | number;
}) {
  const { language } = useAppLanguage();
  const numberLocale = language === "en" ? "en-US" : "fa-IR";

  return (
    <div className="flex items-center justify-between border-b border-neutral-100 py-3 last:border-b-0 dark:border-neutral-800">
      <div className="flex items-center gap-2 text-sm text-neutral-600 dark:text-neutral-300">
        {icon}
        <span>{label}</span>
      </div>
      <span className="text-sm font-bold tabular-nums">
        {typeof value === "number" ? value.toLocaleString(numberLocale) : value}
      </span>
    </div>
  );
}

export default function ReelsPostAnalyticsModal({
  postData,
  isOpen,
  onClose,
}: Props) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<AnalyticsStats | null>(null);

  useEffect(() => {
    if (!isOpen) return;
    let cancelled = false;
    setLoading(true);
    void request<{ stats: AnalyticsStats }>(
      "GET",
      `/posts/${postData._id}/analytics`,
      undefined,
      { noToast: true }
    )
      .then((res) => {
        if (!cancelled) setStats(res.stats);
      })
      .catch(() => {
        if (!cancelled) setStats(null);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [isOpen, postData._id, request]);

  const mediaType = resolvePostMediaType(postData) ?? postData.type;
  const previewSrc =
    mediaType === "video"
      ? getVideoPoster(postData)
      : postData.files?.[0]?.path
        ? buildStorageUrl(postData.files[0].path)
        : undefined;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      height="fit"
      panelClassName="!p-0 max-h-[85dvh] overflow-hidden"
    >
      <div className="flex max-h-[85dvh] flex-col overflow-y-auto">
        <div className="border-b border-neutral-100 px-4 py-3 dark:border-neutral-800">
          <h2 className="text-center text-base font-bold">{t("posts.analyticsTitle")}</h2>
        </div>

        {previewSrc ? (
          <div className="relative mx-auto mt-4 aspect-[9/16] w-28 overflow-hidden rounded-2xl bg-black">
            <Image
              src={previewSrc}
              alt=""
              fill
              className="object-cover"
              unoptimized
            />
          </div>
        ) : null}

        {loading ? (
          <div className="flex flex-col gap-3 p-5">
            {Array.from({ length: 6 }).map((_, i) => (
              <div
                key={i}
                className="h-10 animate-pulse rounded-xl bg-neutral-100 dark:bg-neutral-800"
              />
            ))}
          </div>
        ) : stats ? (
          <div className="px-5 pb-5 pt-2">
            <div className="mb-4 rounded-2xl bg-neutral-50 p-3 dark:bg-neutral-900">
              <StatRow
                icon={<BoldIcon name="heart" size={18} tinted />}
                label={t("posts.like")}
                value={stats.likesCount}
              />
              <StatRow
                icon={<BoldIcon name="message" size={18} tinted />}
                label={t("posts.comment")}
                value={stats.commentsCount}
              />
              <StatRow
                icon={<BoldIcon name="send-2" size={18} tinted />}
                label={t("posts.send")}
                value={stats.sendsCount}
              />
              <StatRow
                icon={<BoldIcon name="share" size={18} tinted />}
                label={t("posts.share")}
                value={stats.sharesCount}
              />
              <StatRow
                icon={<BoldIcon name="archive-book" size={18} tinted />}
                label={t("posts.saveStat")}
                value={stats.savesCount}
              />
              <StatRow
                icon={<BoldIcon name="people" size={18} tinted />}
                label={t("posts.followFromPost")}
                value={stats.followsFromPost}
              />
              <StatRow
                icon={<BoldIcon name="briefcase" size={18} tinted />}
                label={t("posts.collaborationRequest")}
                value={stats.offersCount}
              />
            </div>

            <h3 className="mb-2 text-sm font-bold">{t("posts.viewsAndWatch")}</h3>
            <div className="mb-4 rounded-2xl bg-neutral-50 p-3 dark:bg-neutral-900">
              <StatRow
                icon={<BoldIcon name="eye" size={18} tinted />}
                label={t("posts.views")}
                value={stats.viewsCount}
              />
              <StatRow
                icon={<BoldIcon name="timer-1" size={18} tinted />}
                label={t("posts.watchTime")}
                value={formatDuration(stats.totalWatchMs)}
              />
            </div>

            <h3 className="mb-2 text-sm font-bold">{t("posts.audience")}</h3>
            <div className="rounded-2xl bg-neutral-50 p-3 dark:bg-neutral-900">
              <div className="mb-3 flex h-3 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-700">
                <div
                  className="bg-blue-500"
                  style={{ width: `${stats.followerPct}%` }}
                />
                <div
                  className="bg-violet-500"
                  style={{ width: `${stats.nonFollowerPct}%` }}
                />
              </div>
              <StatRow
                icon={
                  <span className="inline-block h-2 w-2 rounded-full bg-blue-500" />
                }
                label={t("posts.followersPct", { pct: stats.followerPct })}
                value={stats.followerViews}
              />
              <StatRow
                icon={
                  <span className="inline-block h-2 w-2 rounded-full bg-violet-500" />
                }
                label={t("posts.nonFollowersPct", { pct: stats.nonFollowerPct })}
                value={stats.nonFollowerViews}
              />
            </div>
          </div>
        ) : (
          <p className="p-6 text-center text-sm text-neutral-500">
            {t("posts.analyticsLoadFailed")}
          </p>
        )}
      </div>
    </Modal>
  );
}
