'use client';

import { use, useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { BookOpen, Images, ChevronLeft, CalendarDays } from 'lucide-react';
import { apiFetchJson } from '@/lib/auth';
import { PageHeader } from '@/components/school/page-header';
import { GalleryImageGrid } from '@/components/gallery/gallery-image-grid';

type GalleryImage = { id: string; url: string; caption?: string | null; order: number };
type Gallery = {
  id: string; title: string; description?: string | null; coverUrl?: string | null;
  classroomId?: string | null;
  classroom?: { id: string; name: string; branch?: { id: string; name: string } | null } | null;
  images: GalleryImage[];
  imageCount: number; createdAt: string; updatedAt: string;
};

export default function ParentGalleryDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [gallery, setGallery] = useState<Gallery | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const res = await apiFetchJson<Gallery>(`/v1/parent/galleries/${id}`);
    if (res.error) { setError(res.error); setLoading(false); return; }
    setGallery(res.data);
    setLoading(false);
  }, [id]);

  useEffect(() => { load(); }, [load]);

  if (loading) return (
    <div className="space-y-6 pb-8">
      <PageHeader eyebrow="Galeri" title="Yükleniyor…" description="" />
      <div className="space-y-3">
        <div className="h-48 animate-pulse rounded-2xl bg-zinc-100 dark:bg-zinc-800" />
        <div className="grid grid-cols-4 gap-2">
          {[1, 2, 3, 4, 5, 6, 7, 8].map((i) => (
            <div key={i} className="aspect-square animate-pulse rounded-xl bg-zinc-100 dark:bg-zinc-800" />
          ))}
        </div>
      </div>
    </div>
  );

  if (error || !gallery) return (
    <div className="space-y-4 pb-8">
      <PageHeader eyebrow="Galeri" title="Hata" description="" />
      <p className="admin-callout-error">{error || 'Galeri bulunamadı'}</p>
      <Link href="/parent/gallery" className="inline-flex items-center gap-1 text-sm text-zinc-500 hover:text-zinc-700">
        <ChevronLeft size={14} /> Geri dön
      </Link>
    </div>
  );

  const createdDate = new Date(gallery.createdAt).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', year: 'numeric' });

  return (
    <div className="space-y-6 pb-8">
      <PageHeader
        eyebrow="Galeri"
        title={gallery.title}
        description={gallery.description ?? `${gallery.imageCount} fotoğraf`}
        backHref="/parent/gallery"
      />

      <div className="flex flex-col gap-5 lg:flex-row">
        {/* Ana içerik — tam genişlikte fotoğraf ızgarası */}
        <div className="min-w-0 flex-1">
          <div className="admin-panel p-5">
            <div className="mb-4 flex items-center justify-between">
              <p className="text-[13px] font-semibold text-zinc-700 dark:text-zinc-300">
                Fotoğraflar
                <span className="ml-2 rounded-full bg-zinc-100 px-2 py-0.5 text-[11px] font-medium text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400">
                  {gallery.imageCount}
                </span>
              </p>
            </div>
            <GalleryImageGrid
              images={gallery.images}
              editable={false}
              columns={4}
            />
          </div>
        </div>

        {/* Sağ sidebar */}
        <aside className="w-full lg:w-56 lg:shrink-0">
          <div className="admin-panel divide-y divide-zinc-100 dark:divide-zinc-800">
            {gallery.classroom && (
              <div className="px-4 py-4">
                <p className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">Sınıf</p>
                {gallery.classroom.branch?.name && (
                  <p className="mb-0.5 text-xs text-zinc-400 dark:text-zinc-500">{gallery.classroom.branch.name}</p>
                )}
                <p className="flex items-center gap-1.5 text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                  <BookOpen size={14} strokeWidth={2} className="text-brand-500" />
                  {gallery.classroom.name}
                </p>
              </div>
            )}
            <div className="px-4 py-4">
              <p className="mb-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">Fotoğraf Sayısı</p>
              <p className="flex items-center gap-1.5 text-2xl font-bold text-zinc-900 dark:text-white">
                <Images size={18} strokeWidth={2} className="text-brand-500" />
                {gallery.imageCount}
              </p>
            </div>
            <div className="px-4 py-4">
              <p className="mb-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">Oluşturulma</p>
              <p className="flex items-center gap-1.5 text-sm text-zinc-600 dark:text-zinc-400">
                <CalendarDays size={13} strokeWidth={2} className="text-zinc-400" />
                {createdDate}
              </p>
            </div>
            {gallery.description && (
              <div className="px-4 py-4">
                <p className="mb-1 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 dark:text-zinc-500">Açıklama</p>
                <p className="text-sm text-zinc-600 dark:text-zinc-400">{gallery.description}</p>
              </div>
            )}
          </div>
        </aside>
      </div>
    </div>
  );
}
