"use client";

import { useEffect, useState, use } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ArrowLeft, ExternalLink, User, Calendar, FileText } from "lucide-react";
import Link from "next/link";

interface MateriDetail {
  id: string;
  judul: string;
  content: string;
  mapel: { namaMapel: string };
  guru: { nama: string };
  createdAt: string;
  linkDrive?: string;
  youtubeId?: string;
  fileUrl?: string;
}

export default function SiswaMateriDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [data, setData] = useState<MateriDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchData();
  }, [id]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/siswa/materi/${id}`);
      const json = await res.json();
      if (json.success) setData(json.data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <div className="p-8 text-center">Loading...</div>;
  if (!data) return <div className="text-muted-foreground p-8 text-center">Materi tidak ditemukan</div>;

  return (
    <div className="max-w-4xl space-y-6 p-6 text-center">
      <Button variant="ghost" onClick={() => router.back()} className="mb-2">
        <ArrowLeft className="mr-2 h-4 w-4" /> Kembali
      </Button>

      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <Badge>{data.mapel.namaMapel}</Badge>
          <span className="text-muted-foreground flex items-center text-sm">
            <Calendar className="mr-1 h-3 w-3" />
            {new Date(data.createdAt).toLocaleDateString("id-ID", { dateStyle: "long" })}
          </span>
        </div>
        <h1 className="text-3xl font-bold">{data.judul}</h1>
        <div className="text-muted-foreground flex items-center gap-2">
          <User className="h-4 w-4" />
          <span>{data.guru.nama}</span>
        </div>
      </div>

      {/* Hero Video Section */}
      {data.youtubeId && (
        <div className="aspect-video w-full overflow-hidden rounded-lg bg-black shadow-lg">
          <iframe
            width="100%"
            height="100%"
            src={`https://www.youtube.com/embed/${data.youtubeId}`}
            title="YouTube video player"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          ></iframe>
        </div>
      )}

      <Card className="min-h-[200px]">
        <CardContent className="pt-6">
          <div className="prose max-w-none whitespace-pre-wrap">{data.content}</div>
        </CardContent>
      </Card>

      {(data.linkDrive || data.fileUrl) && (
        <div className="grid gap-4 md:grid-cols-2">
          {data.linkDrive && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Materi Tambahan</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Button variant="outline" className="h-auto w-full justify-start py-4" asChild>
                  <a href={data.linkDrive} target="_blank" rel="noopener noreferrer">
                    <div className="mr-3 rounded-full bg-blue-100 p-2">
                      <ExternalLink className="h-5 w-5 text-blue-600" />
                    </div>
                    <div className="text-left">
                      <div className="font-semibold">Buka Google Drive</div>
                      <div className="text-muted-foreground max-w-[200px] truncate text-xs">{data.linkDrive}</div>
                    </div>
                  </a>
                </Button>
              </CardContent>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}
