"use client";

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

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

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

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

export default function VideoGuideView({
  name,
  description,
  videoLink,
  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]);

  // Extract video ID from various YouTube URL formats
  const getYouTubeVideoId = (url: string): string | null => {
    const patterns = [
      /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\n?#]+)/,
      /^([a-zA-Z0-9_-]{11})$/, // Direct video ID
    ];

    for (const pattern of patterns) {
      const match = url.match(pattern);
      if (match) return match[1];
    }
    return null;
  };

  const videoId = getYouTubeVideoId(videoLink);
  const embedUrl = videoId
    ? `https://www.youtube.com/embed/${videoId}?rel=0&modestbranding=1`
    : videoLink;

  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}>
          <div className={styles.videoInner}>
            <iframe
              src={embedUrl}
              title={name}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              className={styles.video}
            />
          </div>
        </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>
  );
}
