"use client";

import { useState, useEffect } from "react";
import Image from "next/image";

interface Story {
  title: string;
  photo_url: string;
  description: string;
}

interface StoryViewerProps {
  userId: number;
  username: string;
}

export default function StoryViewer({ userId, username }: StoryViewerProps) {
  const [stories, setStories] = useState<Story[]>([]);
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/stories?user_id=${userId}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.stories && data.stories.length > 0) {
          setStories(data.stories);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [userId]);

  if (loading || stories.length === 0) return null;

  const isOpen = activeIndex !== null;
  const current = isOpen ? stories[activeIndex] : null;

  function goNext() {
    if (activeIndex === null) return;
    if (activeIndex < stories.length - 1) {
      setActiveIndex(activeIndex + 1);
    } else {
      setActiveIndex(null);
    }
  }

  function goPrev() {
    if (activeIndex === null) return;
    if (activeIndex > 0) {
      setActiveIndex(activeIndex - 1);
    }
  }

  return (
    <>
      {/* Story Thumbnails */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
          <svg className="w-5 h-5 text-pink-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 4V2m0 2a2 2 0 00-2 2v1a2 2 0 002 2h0a2 2 0 002-2V6a2 2 0 00-2-2zm0 0V2m10 2V2m0 2a2 2 0 00-2 2v1a2 2 0 002 2h0a2 2 0 002-2V6a2 2 0 00-2-2zm0 0V2M5 11h14M5 15h14M5 19h14" />
          </svg>
          A Day in My Life
        </h2>
        <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-thin scrollbar-thumb-surface-light">
          {stories.map((story, idx) => (
            <button
              key={idx}
              onClick={() => setActiveIndex(idx)}
              className="flex-shrink-0 group"
            >
              <div className="w-20 h-20 rounded-full overflow-hidden ring-2 ring-primary/50 ring-offset-2 ring-offset-surface group-hover:ring-primary transition-all relative">
                <Image
                  src={story.photo_url}
                  alt={story.title}
                  fill
                  sizes="80px"
                  className="object-cover"
                />
              </div>
              <p className="text-xs text-text-muted mt-1.5 text-center truncate w-20">
                {story.title}
              </p>
            </button>
          ))}
        </div>
      </div>

      {/* Fullscreen Story Viewer */}
      {isOpen && current && (
        <div className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center">
          {/* Progress bar */}
          <div className="absolute top-4 left-4 right-4 flex gap-1">
            {stories.map((_, idx) => (
              <div
                key={idx}
                className="h-0.5 flex-1 rounded-full overflow-hidden bg-white/20"
              >
                <div
                  className={`h-full rounded-full transition-all duration-300 ${
                    idx < activeIndex! ? "bg-white w-full" : idx === activeIndex ? "bg-primary w-full" : "w-0"
                  }`}
                />
              </div>
            ))}
          </div>

          {/* Header */}
          <div className="absolute top-8 left-4 right-4 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-white font-semibold text-sm">{username}</span>
              <span className="text-white/50 text-xs">{current.title}</span>
            </div>
            <button
              onClick={() => setActiveIndex(null)}
              className="text-white/70 hover:text-white transition-colors p-1"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Story Image */}
          <div className="max-w-lg w-full mx-4">
            <Image
              src={current.photo_url}
              alt={current.title}
              width={800}
              height={900}
              className="w-full max-h-[70vh] object-contain rounded-lg"
            />
            {current.description && (
              <div className="mt-4 bg-black/50 backdrop-blur-sm rounded-lg p-4">
                <p className="text-white text-sm leading-relaxed">{current.description}</p>
              </div>
            )}
          </div>

          {/* Navigation */}
          <button
            onClick={goPrev}
            className={`absolute left-4 top-1/2 -translate-y-1/2 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors ${
              activeIndex === 0 ? "opacity-30 pointer-events-none" : ""
            }`}
          >
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <button
            onClick={goNext}
            className="absolute right-4 top-1/2 -translate-y-1/2 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
          >
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      )}
    </>
  );
}
