"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft, Download, Film } from "lucide-react";
import { api } from "@/lib/api";
import { Navbar } from "@/components/public/Navbar";
import { Footer } from "@/components/public/Footer";

interface MediaItem {
  id: string;
  slug: string;
  type: "image" | "video";
  mimeType: string;
  size: number;
  originalFilename: string;
  createdAt: string;
  url: string;
  title?: string;
  description?: string;
  altText?: string;
}

function extractUlid(slugParam: string): string {
  const parts = slugParam.split("-");
  return parts[parts.length - 1];
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export default function GalleryDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const [media, setMedia] = useState<MediaItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!slug) return;
    const id = extractUlid(slug);
    api
      .getMedia(id)
      .then((data) => setMedia(data))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [slug]);

  return (
    <>
      <Navbar />

      <div className="min-h-screen">
        <div className="max-w-4xl mx-auto px-8 pt-12 pb-24">
          <Link
            href="/"
            className="inline-flex items-center gap-2 text-on-surface-variant hover:text-primary transition-colors mb-12 text-sm font-medium"
          >
            <ArrowLeft size={16} />
            Back
          </Link>

          {loading && (
            <div className="flex items-center justify-center py-24">
              <div className="text-on-surface/50">Loading...</div>
            </div>
          )}

          {error && (
            <div className="bg-error-container/20 text-error rounded-xl p-6">
              Media not found or failed to load.
            </div>
          )}

          {!loading && !error && media && (
            <div>
              <div className="rounded-2xl overflow-hidden bg-surface-container-lowest mb-8">
                {media.type === "image" ? (
                  <img
                    src={`/media/${media.id}`}
                    alt={media.altText || media.title || media.originalFilename}
                    className="w-full h-auto max-h-[80vh] object-contain mx-auto"
                  />
                ) : (
                  <video
                    controls
                    src={`/media/${media.id}`}
                    className="w-full max-h-[80vh]"
                  >
                    Your browser does not support the video tag.
                  </video>
                )}
              </div>

              <div className="flex items-start justify-between">
                <div>
                  <h1 className="text-xl font-bold text-on-surface mb-2">
                    {media.title || media.originalFilename}
                  </h1>
                  {media.description && (
                    <p className="text-on-surface-variant/70 text-sm mb-3 max-w-2xl">
                      {media.description}
                    </p>
                  )}
                  <div className="flex items-center gap-3 text-sm text-on-surface-variant/60">
                    <span className="flex items-center gap-1.5">
                      {media.type === "video" ? <Film size={14} /> : null}
                      {media.type.charAt(0).toUpperCase() + media.type.slice(1)}
                    </span>
                    <span>{formatFileSize(media.size)}</span>
                    <span>{media.mimeType}</span>
                  </div>
                </div>
                <a
                  href={`/media/${media.id}`}
                  download={media.originalFilename}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg bg-surface-container-high text-on-surface hover:bg-surface-container-highest transition-colors text-sm font-medium"
                >
                  <Download size={16} />
                  Download
                </a>
              </div>
            </div>
          )}
        </div>
      </div>

      <Footer />
    </>
  );
}
