'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { Images, Plus, BookOpen, CalendarDays, Trash2, ImageOff } from 'lucide-react';
import { apiFetchJson } from '@/lib/auth';
import { useToast } from '@/components/school/toast-context';
import { ConfirmDialog } from '@/components/school/confirm-dialog';

type Classroom = { id: string; name: string; branch?: { id: string; name: string } | null };
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;
  imageCount: number; createdAt: string;
};

export default function TeacherGalleryPage() {
  const { toast } = useToast();
  const [galleries, setGalleries] = useState<Gallery[]>([]);
  const [classrooms, setClassrooms] = useState<Classroom[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const [galRes, clsRes] = await Promise.all([
      apiFetchJson<Gallery[]>('/v1/teacher/galleries'),
      apiFetchJson<Classroom[]>('/v1/teacher/classrooms'),
    ]);
    if (!galRes.error) setGalleries(galRes.data ?? []);
    if (!clsRes.error) setClassrooms(clsRes.data ?? []);
    setLoading(false);
  }, []);

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

  const confirmDelete = async () => {
    if (!deleteId) return;
    const res = await apiFetchJson(`/v1/teacher/galleries/${deleteId}`, { method: 'DELETE' });
    if (res.error) { toast({ title: 'Hata', description: res.error, variant: 'destructive' }); return; }
    setGalleries((prev) => prev.filter((g) => g.id !== deleteId));
    setDeleteId(null);
    toast({ title: 'Galeri silindi' });
  };

  const newGalleryHref = `/teacher/gallery/new${classrooms.length === 1 ? `?classroomId=${classrooms[0].id}` : ''}`;

  if (loading) return (
    <div className="space-y-6 pb-8">
      <div className="flex items-center justify-between">
        <div className="space-y-1.5">
          <div className="h-3 w-16 animate-pulse rounded-full bg-zinc-200 dark:bg-zinc-700" />
          <div className="h-6 w-40 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-700" />
        </div>
        <div className="h-9 w-32 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-700" />
      </div>
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {[1, 2, 3].map((i) => (
          <div key={i} className="animate-pulse overflow-hidden rounded-xl border border-zinc-200/90 bg-white shadow-theme-sm dark:border-zinc-800/90 dark:bg-zinc-900/40">
            <div className="aspect-[4/3] bg-zinc-100 dark:bg-zinc-800" />
            <div className="space-y-2 p-4">
              <div className="h-4 rounded-md bg-zinc-100 dark:bg-zinc-800" />
              <div className="h-3 w-2/3 rounded-md bg-zinc-100 dark:bg-zinc-800" />
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="font-urbanist space-y-6 pb-8">
      {/* Başlık */}
      <div className="flex items-center justify-between">
        <div>
          <p className="text-[11px] font-semibold uppercase tracking-widest text-zinc-400 dark:text-zinc-500">Galeri</p>
          <h1 className="mt-0.5 text-xl font-bold text-zinc-900 dark:text-white">Galerilerim</h1>
          <p className="mt-0.5 text-sm text-zinc-500 dark:text-zinc-400">Sınıfınıza ait fotoğraf galerilerini yönetin</p>
        </div>
        <Link
          href={newGalleryHref}
          className="inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white shadow-sm transition-opacity hover:opacity-90 dark:bg-teal-600"
        >
          <Plus size={14} strokeWidth={2.5} />
          Yeni Galeri
        </Link>
      </div>

      {/* İçerik */}
      {galleries.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-zinc-200 py-20 text-center dark:border-zinc-700/60">
          <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-zinc-100 dark:bg-zinc-800">
            <ImageOff size={22} className="text-zinc-400 dark:text-zinc-500" />
          </div>
          <p className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">Henüz galeri oluşturmadınız</p>
          <p className="mt-1 text-xs text-zinc-400 dark:text-zinc-500">Sınıfınız için fotoğraf galerisi oluşturun</p>
          <Link
            href={newGalleryHref}
            className="mt-5 inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white shadow-sm transition-opacity hover:opacity-90 dark:bg-teal-600"
          >
            <Plus size={13} strokeWidth={2.5} />
            Yeni Galeri Oluştur
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {galleries.map((gallery) => (
            <div
              key={gallery.id}
              className="group overflow-hidden rounded-xl border border-zinc-200/90 bg-white shadow-theme-sm transition-shadow hover:shadow-theme-md dark:border-zinc-800/90 dark:bg-zinc-900/40"
            >
              {/* Kapak */}
              <Link href={`/teacher/gallery/${gallery.id}`} className="block">
                <div className="relative aspect-[4/3] overflow-hidden bg-gradient-to-br from-teal-50 to-teal-100 dark:from-teal-950/30 dark:to-teal-900/20">
                  {gallery.coverUrl ? (
                    <img
                      src={gallery.coverUrl}
                      alt={gallery.title}
                      className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                  ) : (
                    <div className="flex h-full w-full items-center justify-center">
                      <Images size={32} className="text-teal-300 dark:text-teal-700" />
                    </div>
                  )}
                  {/* Resim sayısı badge */}
                  <div className="absolute right-2 top-2 flex items-center gap-1 rounded-full bg-black/50 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
                    <Images size={10} strokeWidth={2} />
                    {gallery.imageCount}
                  </div>
                  {/* Hover overlay */}
                  <div className="absolute inset-0 bg-black/0 transition-all duration-200 group-hover:bg-black/8" />
                </div>
              </Link>

              {/* Bilgi */}
              <div className="p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0 flex-1">
                    <Link href={`/teacher/gallery/${gallery.id}`}>
                      <h3 className="truncate text-[15px] font-semibold text-zinc-900 transition-colors hover:text-primary dark:text-white dark:hover:text-teal-400">
                        {gallery.title}
                      </h3>
                    </Link>
                    {gallery.description && (
                      <p className="mt-0.5 line-clamp-1 text-xs text-zinc-400 dark:text-zinc-500">
                        {gallery.description}
                      </p>
                    )}
                    {gallery.classroom && (
                      <p className="mt-1.5 flex items-center gap-1 text-xs font-medium text-zinc-500 dark:text-zinc-400">
                        <BookOpen size={11} strokeWidth={2} className="text-teal-500 dark:text-teal-400" />
                        {gallery.classroom.branch?.name && (
                          <span className="text-zinc-400 dark:text-zinc-500">{gallery.classroom.branch.name} /&nbsp;</span>
                        )}
                        {gallery.classroom.name}
                      </p>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => setDeleteId(gallery.id)}
                    className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-zinc-400 opacity-0 transition-all hover:bg-red-50 hover:text-red-500 group-hover:opacity-100 dark:hover:bg-red-950/30 dark:hover:text-red-400"
                    aria-label="Sil"
                  >
                    <Trash2 size={13} strokeWidth={2} />
                  </button>
                </div>
                <p className="mt-2.5 flex items-center gap-1 text-[11px] text-zinc-400 dark:text-zinc-500">
                  <CalendarDays size={11} strokeWidth={2} />
                  {new Date(gallery.createdAt).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', year: 'numeric' })}
                </p>
              </div>
            </div>
          ))}
        </div>
      )}

      <ConfirmDialog
        open={!!deleteId}
        onOpenChange={(o) => !o && setDeleteId(null)}
        title="Galeriyi sil"
        description="Bu galeri ve içindeki tüm fotoğraflar kalıcı olarak silinecektir."
        confirmLabel="Sil"
        variant="destructive"
        onConfirm={confirmDelete}
      />
    </div>
  );
}
