import { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "../components/ui/dialog";
import { api } from "../utils/api";
import { useAuthStore } from "../stores/authStore";

interface LessonModalProps {
  lessonId: string | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export const LessonModal = ({
  lessonId,
  open,
  onOpenChange,
}: LessonModalProps) => {
  const user = useAuthStore((state) => state.user);
  const [loading, setLoading] = useState(false);
  const [lesson, setLesson] = useState<any>(null);

  useEffect(() => {
    if (!open || !lessonId || !user) return;

    const fetchLesson = async () => {
      try {
        setLoading(true);

        const authStorage = localStorage.getItem("auth-storage");
        if (!authStorage) return;

        const parsed = JSON.parse(authStorage) as {
          state?: { token?: string };
        };

        const token = parsed.state?.token;
        if (!token) return;

        const response = await api.fetchLessonById(token, lessonId);
        setLesson(response);
      } catch (err) {
        console.error("Failed to fetch lesson", err);
      } finally {
        setLoading(false);
      }
    };

    fetchLesson();
  }, [open, lessonId, user]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        {loading && (
          <div className="py-12 text-center text-muted-foreground">
            Loading lesson...
          </div>
        )}
        <DialogHeader>
          <DialogTitle>{lesson ? lesson.title : "Lesson details"}</DialogTitle>
        </DialogHeader>

        {!loading && lesson && (
          <div className="space-y-4">
            {lesson.video_url && (
              <video
                src={lesson.video_url}
                controls
                className="w-full rounded-lg"
              />
            )}
            <h2 className="font-satoshi-bold text-xl">
              {lesson ? lesson.title : "Lesson details"}
            </h2>

            <p className="text-sm text-muted-foreground">
              {lesson.description}
            </p>
            <p className="text-sm text-muted-foreground">{lesson.content}</p>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};
