"use client";

import { useEffect, useRef, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchVideoDetail,
  clearVideoDetail,
} from "@/store/slices/videoDetailSlice";
import { playMedia } from "@/store/slices/playerSlice";
import { useAddView } from "@/hooks/useAddView";
import { useAddToHistory } from "@/hooks/useAddToHistory";
import { useAdInterstitial } from "@/hooks/useAdInterstitial";
import { VideoPlayer, VideoPlayerSkeleton } from "./VideoPlayer";
import { VideoInfo, VideoInfoSkeleton } from "./VideoInfo";
import { RelatedVideos, RelatedVideosSkeleton } from "./RelatedVideos";
import { CommentSection } from "@/components/shared/CommentSection";
import { GoogleAd } from "@/components/ads/GoogleAd";
import { AdInterstitial } from "@/components/ads/AdInterstitial";
import { AdReward } from "@/components/ads/AdReward";
import { useGoogleAds } from "@/context/GoogleAdsContext";
import { useTranslation } from "@/i18n";

export default function VideoPage() {
  const { t } = useTranslation();
  const params = useParams<{ id: string }>();
  // Some URLs carry extra text after the numeric ID (e.g. "412 Song Title").
  // Strip everything after the first non-digit character so the API always
  // receives a clean numeric content_id.
  const rawId = params?.id ?? "";
  const id = rawId.match(/^(\d+)/)?.[1] ?? rawId;

  const router = useRouter();
  const dispatch = useAppDispatch();
  const {
    video,
    relatedVideos,
    isLoading,
    isRelatedLoading,
    relatedError,
    error,
  } = useAppSelector((s) => s.videoDetail);
  const activeId = useAppSelector((s) => s.player.currentMediaId);
  const currentTime = useAppSelector((s) => s.player.currentTime);
  const currentTimeRef = useRef(0);
  useEffect(() => {
    currentTimeRef.current = currentTime;
  }, [currentTime]);

  const { getPlacement } = useGoogleAds();
  // "others" placement drives both interstitial and reward modals
  const othersAd = getPlacement("others");

  const {
    showAd: showInterstitial,
    recordClick,
    dismissAd,
  } = useAdInterstitial(3, !!othersAd);
  const [showReward, setShowReward] = useState(false);

  useAddView(video?.contentType, video?.id);
  useAddToHistory(
    video?.contentType,
    video?.id,
    undefined,
    5000,
    () => currentTimeRef.current,
  );

  /* fetch on route change */
  useEffect(() => {
    if (!id) return;
    dispatch(fetchVideoDetail(id));
    return () => {
      dispatch(clearVideoDetail());
    };
  }, [id, dispatch]);

  /* register video info with global player.
     Skip entirely when the same video is already registered — this handles the
     mini-player → full expand path where we must not reset currentTime to 0.
     A new video ID (or no prior video) always proceeds. */
  useEffect(() => {
    if (!video) return;
    if (activeId === video.id) return;
    dispatch(
      playMedia({
        id: video.id,
        type: "video",
        title: video.title,
        thumbnail: video.thumbnail,
        channelName: video.channelName,
        videoUrl: video.videoUrl,
        videoContentUploadType: video.contentUploadType,
      }),
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [video, dispatch]);

  /* ── Error ──────────────────────────────────────────────────────────────── */
  if (!isLoading && error) {
    return (
      <div className="flex flex-col items-center justify-center py-24 gap-4">
        <svg
          width="48"
          height="48"
          viewBox="0 0 24 24"
          fill="none"
          stroke="var(--text-muted)"
          strokeWidth="1.2"
        >
          <circle cx="12" cy="12" r="10" />
          <line x1="12" y1="8" x2="12" y2="12" />
          <line x1="12" y1="16" x2="12.01" y2="16" />
        </svg>
        <p
          className="text-sm font-medium"
          style={{ color: "var(--text-muted)" }}
        >
          {error}
        </p>
        <button
          className="px-4 py-2 rounded-full text-xs font-bold text-[#ffffff] transition-all active:scale-95"
          style={{ background: "var(--accent)" }}
          onClick={() => dispatch(fetchVideoDetail(id))}
        >
          {t("common_retry")}
        </button>
      </div>
    );
  }

  return (
    <>
      {/* ── Interstitial Ad Modal ──────────────────────────────────────────── */}
      {showInterstitial && (
        <AdInterstitial onClose={dismissAd} countdownSeconds={5} />
      )}

      {/* ── Reward Ad Modal ────────────────────────────────────────────────── */}
      {showReward && (
        <AdReward
          onRewardEarned={() => {}}
          onClose={() => setShowReward(false)}
          watchSeconds={15}
        />
      )}

      <div className="w-full px-4 py-4 pb-24 md:pb-8">
        <div className="flex flex-col lg:flex-row gap-6 mx-auto">
          {/* ── Left: Player + Info ─────────────────────────────────────── */}
          <div className="flex-1 min-w-0 flex flex-col">
            {/* Back button — navigates without stopping the video.
                Player state stays in Redux; MiniVideoPlayer appears automatically. */}
            <button
              onClick={() => router.back()}
              className="flex items-center gap-1.5 mb-3 w-fit transition-all duration-150 active:scale-95 rounded-lg px-2 py-1 -ml-1 group"
              style={{ color: "var(--text-muted)" }}
              aria-label="Go back"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="transition-transform duration-150 group-hover:-translate-x-0.5"
              >
                <polyline points="15 18 9 12 15 6" />
              </svg>
              <span className="text-xs font-medium transition-colors">
                {t("video_back")}
              </span>
            </button>

            {isLoading || !video ? (
              <VideoPlayerSkeleton />
            ) : (
              <VideoPlayer
                url={video.videoUrl}
                contentUploadType={video.contentUploadType}
              />
            )}

            {/* ── Banner Ad — below video player ────────────────────────── */}
            <div className="mt-3">
              <GoogleAd placement="content" />
            </div>

            {isLoading || !video ? (
              <VideoInfoSkeleton />
            ) : (
              <VideoInfo video={video} />
            )}

            {/* ── Reward Ad CTA ─────────────────────────────────────────── */}
            <button
              onClick={() => setShowReward(true)}
              className="mt-3 flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold w-full transition-all active:scale-95"
              style={{
                background: "var(--btn-ghost)",
                border: "1px solid var(--border)",
                color: "var(--text-primary)",
              }}
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="var(--accent)"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
              </svg>
              <span>Watch an ad to earn reward coins</span>
            </button>

            {/* ── Comments ──────────────────────────────────────────────── */}
            {!isLoading && video && video.isComment === 1 && (
              <div className="mt-4">
                <CommentSection
                  mode="inline"
                  contentType={video.contentType}
                  contentId={video.id}
                  totalComments={video.totalComment}
                  canComment={video.isComment === 1}
                />
              </div>
            )}
          </div>

          {/* ── Right: Related ──────────────────────────────────────────── */}
          <div
            className="w-full lg:w-[340px] xl:w-[380px] shrink-0"
            style={{ minWidth: 0 }}
          >
            {isRelatedLoading ? (
              <RelatedVideosSkeleton />
            ) : relatedVideos.length > 0 ? (
              <RelatedVideos
                videos={relatedVideos}
                onVideoClick={recordClick}
              />
            ) : (
              <div
                className="flex flex-col items-center justify-center gap-2 rounded-xl py-10 px-4 text-center"
                style={{
                  background: "var(--btn-ghost)",
                  border: "1px solid var(--border)",
                }}
              >
                <svg
                  width="32"
                  height="32"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="var(--text-muted)"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect x="2" y="7" width="20" height="14" rx="2" />
                  <path d="M16 2H8" />
                  <path
                    d="M10 11l5 3-5 3V11z"
                    fill="var(--text-muted)"
                    stroke="none"
                  />
                </svg>
                <p
                  className="text-xs font-semibold"
                  style={{ color: "var(--text-muted)" }}
                >
                  {relatedError ?? t("video_noRelated")}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
