"use client";

import { useEffect, useState } from "react";
import ApplicationLibrary from "@/components/user-profile/ApplicationList";
import { MediaDto } from "@/interface/media"; // Assuming this file will be created
import { apiGetCurrentUserApplications, apiGetCurrentUserMedia } from "@/service/userService";
import MediaLibrary from "@/components/user-profile/Media";
import { Application } from "@/interface/historian";
import Loading from "@/app/loading";
import StickyHeader from "@/components/ui/StickyHeader";

export default function LibraryPage() {
  const [mediaData, setMediaData] = useState<MediaDto | null>(null);
  const [applications, setApplications] = useState<Application[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchLibraryContent = async () => {
      try {
        const [mediaResponse, userApplications] = await Promise.all([
          apiGetCurrentUserMedia(),
          apiGetCurrentUserApplications()
        ]);

        if (userApplications?.data) setApplications(userApplications.data);
        setMediaData(mediaResponse);
      } catch (err) {
        console.error("Lỗi khi tải thư viện:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchLibraryContent();
  }, []);

  if (loading) return <Loading />;

  const hasNoData = (!mediaData?.data || mediaData.data.length === 0) && applications.length === 0;

  return (
    <div className="min-h-screen bg-gray-50/50 dark:bg-zinc-950">
      
     <StickyHeader header="Thư viện của tôi" />

      <div className="px-4 pb-4 lg:px-8 lg:pb-8">
        {hasNoData ? (
          <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-gray-200 py-24 text-center">
            <p className="text-lg font-medium text-gray-500">
              Chưa có nội dung nào trong thư viện
            </p>
          </div>
        ) : (
          <div className="space-y-12">
            {(mediaData?.data?.length ?? 0) > 0 && (
              <section>
                <MediaLibrary data={mediaData!} />
              </section>
            )}

            {applications.length > 0 && (
              <section>
                <ApplicationLibrary applications={applications} />
              </section>
            )}
          </div>
        )}
      </div>
    </div>
  );
}