"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { useRouter } from "next/navigation";

import { Icon, IconName, MarkdownText, Typography } from "@/components/ui";

import styles from "./VideoGuideView.module.scss";

const VideoPlayer = dynamic(() => import("../VideoPlayer"), { ssr: false });

interface VideoGuideViewProps {
  id: string;
  name: string;
  description: string;
  videoLinkHLS: string;
  videoLinkDASH: string;
  contentUrl?: string;
}

export default function VideoGuideView({
  name,
  description,
  videoLinkHLS,
  videoLinkDASH,
  contentUrl,
}: VideoGuideViewProps) {
  const router = useRouter();
  const [markdownContent, setMarkdownContent] = useState<string | null>(null);
  const [isLoadingMarkdown, setIsLoadingMarkdown] = useState(false);

  // Load markdown content if contentUrl is provided
  useEffect(() => {
    if (!contentUrl) return;

    const loadMarkdown = async () => {
      setIsLoadingMarkdown(true);
      try {
        const response = await fetch(contentUrl);
        if (response.ok) {
          const text = await response.text();
          setMarkdownContent(text);
        }
        // Silently fail and show description as fallback
      } catch {
        // Silently fail and show description as fallback
      } finally {
        setIsLoadingMarkdown(false);
      }
    };

    loadMarkdown();
  }, [contentUrl]);

  return (
    <div className={styles.container}>
      {/* Header with back button and title */}
      <div className={styles.header}>
        <button className={styles.backButton} onClick={() => router.back()}>
          <Icon name={IconName.ChevronLeft} size={{ width: 24, height: 24 }} />
        </button>
        <Typography
          as="h1"
          size="xl"
          weight="semiBold"
          className={styles.title}
        >
          {name}
        </Typography>
      </div>

      {/* Video and Description */}
      <div className={styles.contentWrapper}>
        {/* Video Player */}
        <div className={styles.videoContainer}>
          <VideoPlayer mpd={videoLinkDASH} m3u8={videoLinkHLS} />
        </div>

        {/* Description or Markdown Content */}
        {(isLoadingMarkdown || markdownContent || description) && (
          <div className={styles.descriptionWrapper}>
            {isLoadingMarkdown ? (
              <Typography as="p" size="md" className={styles.description}>
                Loading content...
              </Typography>
            ) : markdownContent ? (
              <MarkdownText content={markdownContent} />
            ) : description ? (
              <Typography as="p" size="md" className={styles.description}>
                {description}
              </Typography>
            ) : null}
          </div>
        )}
      </div>
    </div>
  );
}
