"use client";

import Image from "next/image";
import { useState, useEffect, useRef } from "react";
import type { Section } from "@/types/api/section.types";

// ── Story-specific types ──────────────────────────────────────────────────────
interface StoryItem {
  id: number;
  channel_id: number;
  description: string;
  type: "image" | "video";
  story_url: string;
  total_view: number;
  status: number;
  created_at: string;
  updated_at: string;
  is_view: number;
}

interface StoryChannel {
  channel_id: number;
  channel_name: string;
  channel_image: string;
  story: StoryItem[];
}

function isValidImg(url?: string) {
  return !!url && !url.includes("no_img");
}

const STORY_DURATION = 5000; // ms per story

// ── Full-screen Story Modal ───────────────────────────────────────────────────
function StoryModal({
  channels,
  startChannelIdx,
  onClose,
}: {
  channels: StoryChannel[];
  startChannelIdx: number;
  onClose: () => void;
}) {
  const [channelIdx, setChannelIdx] = useState(startChannelIdx);
  const [storyIdx, setStoryIdx] = useState(0);
  const [progress, setProgress] = useState(0);
  const [visible, setVisible] = useState(false);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const progressRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const channel = channels[channelIdx];
  const stories = (channel?.story ?? []).filter((s) => s.status === 1);
  const currentStory = stories[storyIdx];

  useEffect(() => {
    requestAnimationFrame(() => setVisible(true));
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  // Auto-advance
  useEffect(() => {
    setProgress(0);
    if (progressRef.current) clearInterval(progressRef.current);
    if (timerRef.current) clearTimeout(timerRef.current);

    const start = Date.now();
    progressRef.current = setInterval(() => {
      const elapsed = Date.now() - start;
      setProgress(Math.min((elapsed / STORY_DURATION) * 100, 100));
    }, 50);

    timerRef.current = setTimeout(() => goNext(), STORY_DURATION);

    return () => {
      if (progressRef.current) clearInterval(progressRef.current);
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channelIdx, storyIdx]);

  function goNext() {
    if (storyIdx < stories.length - 1) {
      setStoryIdx((i) => i + 1);
    } else if (channelIdx < channels.length - 1) {
      setChannelIdx((i) => i + 1);
      setStoryIdx(0);
    } else {
      handleClose();
    }
  }

  function goPrev() {
    if (storyIdx > 0) {
      setStoryIdx((i) => i - 1);
    } else if (channelIdx > 0) {
      setChannelIdx((i) => i - 1);
      setStoryIdx(0);
    }
  }

  function handleClose() {
    setVisible(false);
    setTimeout(onClose, 220);
  }

  function handleTap(e: React.MouseEvent<HTMLDivElement>) {
    const rect = e.currentTarget.getBoundingClientRect();
    if (e.clientX < rect.width / 2) {
      goPrev();
    } else {
      goNext();
    }
  }

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 2000,
        background: "rgba(0,0,0,0.95)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        opacity: visible ? 1 : 0,
        transition: "opacity 0.22s ease",
      }}
    >
      {/* Story container */}
      <div
        style={{
          position: "relative",
          width: "min(420px, 100vw)",
          height: "min(90vh, 750px)",
          background: "#111",
          borderRadius: 12,
          overflow: "hidden",
          transform: visible ? "scale(1)" : "scale(0.95)",
          transition: "transform 0.28s cubic-bezier(0.22,1,0.36,1)",
        }}
      >
        {/* Progress bars */}
        <div
          style={{
            position: "absolute",
            top: 12,
            left: 12,
            right: 12,
            zIndex: 10,
            display: "flex",
            gap: 4,
          }}
        >
          {stories.map((_, i) => (
            <div
              key={i}
              style={{
                flex: 1,
                height: 3,
                borderRadius: 2,
                background: "rgba(255,255,255,0.3)",
                overflow: "hidden",
              }}
            >
              <div
                style={{
                  height: "100%",
                  width: i < storyIdx ? "100%" : i === storyIdx ? `${progress}%` : "0%",
                  background: "#fff",
                  transition: i === storyIdx ? "none" : "none",
                }}
              />
            </div>
          ))}
        </div>

        {/* Channel header */}
        <div
          style={{
            position: "absolute",
            top: 28,
            left: 12,
            right: 48,
            zIndex: 10,
            display: "flex",
            alignItems: "center",
            gap: "0.625rem",
          }}
        >
          <div
            style={{
              width: 36,
              height: 36,
              borderRadius: "50%",
              overflow: "hidden",
              position: "relative",
              border: "2px solid rgba(255,255,255,0.5)",
              flexShrink: 0,
              background: "rgba(193,39,45,0.2)",
            }}
          >
            {isValidImg(channel?.channel_image) ? (
              <Image
                src={channel.channel_image}
                alt={channel.channel_name}
                fill
                style={{ objectFit: "cover" }}
                unoptimized
              />
            ) : (
              <span
                style={{
                  position: "absolute",
                  inset: 0,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: 13,
                  fontWeight: 800,
                  color: "#fff",
                }}
              >
                {channel?.channel_name?.charAt(0)}
              </span>
            )}
          </div>
          <div>
            <p style={{ margin: 0, color: "#fff", fontWeight: 700, fontSize: "0.875rem", lineHeight: 1.2 }}>
              {channel?.channel_name}
            </p>
            {currentStory?.created_at && (
              <p style={{ margin: 0, color: "rgba(255,255,255,0.6)", fontSize: "0.7rem", fontFamily: "var(--mono, monospace)" }}>
                {new Date(currentStory.created_at).toLocaleDateString("en-IN", { day: "numeric", month: "short" })}
              </p>
            )}
          </div>
        </div>

        {/* Close button */}
        <button
          onClick={(e) => { e.stopPropagation(); handleClose(); }}
          style={{
            position: "absolute",
            top: 28,
            right: 12,
            zIndex: 10,
            background: "rgba(0,0,0,0.3)",
            border: "none",
            width: 32,
            height: 32,
            borderRadius: "50%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            cursor: "pointer",
            color: "#fff",
            fontSize: 18,
          }}
        >
          ✕
        </button>

        {/* Story media */}
        <div
          style={{ position: "absolute", inset: 0, cursor: "pointer" }}
          onClick={handleTap}
        >
          {currentStory ? (
            currentStory.type === "video" ? (
              <video
                key={currentStory.id}
                src={currentStory.story_url}
                autoPlay
                playsInline
                muted={false}
                style={{ width: "100%", height: "100%", objectFit: "cover" }}
                onEnded={goNext}
              />
            ) : (
              <Image
                key={currentStory.id}
                src={currentStory.story_url}
                alt={currentStory.description || "Story"}
                fill
                style={{ objectFit: "cover" }}
                unoptimized
                priority
              />
            )
          ) : (
            <div
              style={{
                width: "100%",
                height: "100%",
                background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <p style={{ color: "rgba(255,255,255,0.4)", fontFamily: "var(--mono, monospace)", fontSize: 13 }}>
                No story available
              </p>
            </div>
          )}
        </div>

        {/* Description overlay */}
        {currentStory?.description && (
          <div
            style={{
              position: "absolute",
              bottom: 0,
              left: 0,
              right: 0,
              padding: "2rem 1rem 1rem",
              background: "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 100%)",
              zIndex: 5,
              pointerEvents: "none",
            }}
          >
            <p style={{ margin: 0, color: "#fff", fontSize: "0.875rem", lineHeight: 1.5 }}>
              {currentStory.description}
            </p>
          </div>
        )}
      </div>

      {/* Backdrop click to close */}
      <div
        style={{ position: "absolute", inset: 0, zIndex: -1 }}
        onClick={handleClose}
      />
    </div>
  );
}

// ── Story ring ────────────────────────────────────────────────────────────────
function StoryRing({
  channel,
  onClick,
}: {
  channel: StoryChannel;
  onClick: () => void;
}) {
  const hasStories = channel.story.some((s) => s.status === 1);
  const hasNewStory = channel.story.some(
    (s) => s.status === 1 && s.is_view === 0,
  );

  return (
    <button
      onClick={onClick}
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        gap: "0.5rem",
        flexShrink: 0,
        width: 84,
        background: "none",
        border: "none",
        cursor: hasStories ? "pointer" : "default",
        padding: 0,
      }}
    >
      {/* Ring */}
      <div
        style={{
          width: 76,
          height: 76,
          borderRadius: "50%",
          padding: 3,
          background: hasNewStory
            ? "conic-gradient(from 0deg, var(--brand, #C1272D) 0%, var(--brand, #C1272D) 70%, rgba(193,39,45,0.3) 100%)"
            : "rgba(200,200,200,0.4)",
          flexShrink: 0,
        }}
      >
        <div
          style={{
            width: "100%",
            height: "100%",
            borderRadius: "50%",
            overflow: "hidden",
            border: "2px solid var(--bg, #f8f9fb)",
            background: "var(--surf-hi, #f1f3f7)",
            position: "relative",
          }}
        >
          {isValidImg(channel.channel_image) ? (
            <Image
              src={channel.channel_image}
              alt={channel.channel_name}
              fill
              style={{ objectFit: "cover" }}
              unoptimized
              sizes="70px"
            />
          ) : (
            <div
              style={{
                width: "100%",
                height: "100%",
                background: "var(--brand-08, rgba(193,39,45,0.08))",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <span
                style={{
                  fontFamily: "var(--mono)",
                  fontSize: 16,
                  fontWeight: 800,
                  color: "var(--brand, #C1272D)",
                }}
              >
                {channel.channel_name?.charAt(0).toUpperCase() ?? "?"}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Label */}
      <span
        style={{
          fontFamily: "var(--sans)",
          fontSize: 11,
          fontWeight: 500,
          color: "var(--text, #0e0e11)",
          textAlign: "center",
          lineHeight: 1.3,
          display: "-webkit-box",
          WebkitLineClamp: 2,
          WebkitBoxOrient: "vertical" as const,
          overflow: "hidden",
          maxWidth: 80,
        }}
      >
        {channel.channel_name}
      </span>

      {hasNewStory && (
        <span
          style={{
            fontFamily: "var(--mono)",
            fontSize: 9,
            fontWeight: 700,
            color: "var(--brand, #C1272D)",
            letterSpacing: "0.08em",
            textTransform: "uppercase" as const,
            marginTop: -4,
          }}
        >
          NEW
        </span>
      )}
    </button>
  );
}

// ── Main section ──────────────────────────────────────────────────────────────
interface StorySectionProps {
  section: Section;
  locale: string;
}

export default function StorySection({ section }: StorySectionProps) {
  const [modalChannelIdx, setModalChannelIdx] = useState<number | null>(null);

  // The story section data is StoryChannel[], not SectionArticle[]
  const channels = (section.data as unknown as StoryChannel[]).filter(
    (ch) => ch.story && ch.story.length > 0,
  );

  if (channels.length === 0) return null;

  return (
    <>
      <section className="sec" style={{ paddingBottom: "2rem" }}>
        <div className="wrap">
          <div className="sec-head" style={{ marginBottom: "1.25rem" }}>
            <div className="sec-title">
              <h2 style={{ fontFamily: "var(--italic)", fontStyle: "italic" }}>
                {section.title}
              </h2>
              {section.sub_title && (
                <span className="count">{section.sub_title}</span>
              )}
            </div>
          </div>

          {/* Horizontal story strip */}
          <div
            style={{
              display: "flex",
              gap: "1.25rem",
              overflowX: "auto",
              paddingBottom: "0.75rem",
              scrollbarWidth: "none",
              msOverflowStyle: "none",
            }}
          >
            {channels.map((channel, idx) => (
              <StoryRing
                key={channel.channel_id}
                channel={channel}
                onClick={() => setModalChannelIdx(idx)}
              />
            ))}
          </div>
        </div>
      </section>

      {/* Full-screen story modal */}
      {modalChannelIdx !== null && (
        <StoryModal
          channels={channels}
          startChannelIdx={modalChannelIdx}
          onClose={() => setModalChannelIdx(null)}
        />
      )}
    </>
  );
}
