'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { BookOpen, ChevronLeft, ImagePlus, Loader2, UploadCloud, X, CheckCircle2 } from 'lucide-react';
import { apiFetch, apiFetchJson } from '@/lib/auth';
import { useToast } from '@/components/school/toast-context';

type Classroom = { id: string; name: string; branch?: { id: string; name: string } | null };
type LocalFile = { id: string; file: File; preview: string };

function uid() {
  return Math.random().toString(36).slice(2);
}

export default function TeacherGalleryNewPage() {
  const router = useRouter();
  const { toast } = useToast();
  const inputRef = useRef<HTMLInputElement>(null);

  const [classrooms, setClassrooms] = useState<Classroom[]>([]);
  const [loadingData, setLoadingData] = useState(true);

  const [title, setTitle] = useState('');
  const [desc, setDesc] = useState('');
  const [classroomId, setClassroomId] = useState('');

  const [files, setFiles] = useState<LocalFile[]>([]);
  const [dragging, setDragging] = useState(false);

  const [saving, setSaving] = useState(false);
  const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);

  useEffect(() => {
    (async () => {
      const res = await apiFetchJson<Classroom[]>('/v1/teacher/classrooms');
      const list = Array.isArray(res.data) ? res.data : [];
      setClassrooms(list);
      if (list[0]) setClassroomId(list[0].id);
      setLoadingData(false);
    })();
  }, []);

  const addFiles = useCallback((fileList: FileList | null) => {
    if (!fileList) return;
    const accepted: LocalFile[] = [];
    Array.from(fileList).forEach((file) => {
      if (!file.type.startsWith('image/')) return;
      if (file.size > 10 * 1024 * 1024) return;
      accepted.push({ id: uid(), file, preview: URL.createObjectURL(file) });
    });
    setFiles((prev) => [...prev, ...accepted]);
  }, []);

  const removeFile = (id: string) => {
    setFiles((prev) => {
      const f = prev.find((x) => x.id === id);
      if (f) URL.revokeObjectURL(f.preview);
      return prev.filter((x) => x.id !== id);
    });
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    addFiles(e.dataTransfer.files);
  };

  const handleSave = async () => {
    if (!title.trim()) {
      toast({ title: 'Galeri adı zorunludur', variant: 'destructive' });
      return;
    }
    if (!classroomId) {
      toast({ title: 'Lütfen bir sınıf seçin', variant: 'destructive' });
      return;
    }

    setSaving(true);

    const createRes = await apiFetchJson<{ id: string }>('/v1/teacher/galleries', {
      method: 'POST',
      body: JSON.stringify({
        title: title.trim(),
        description: desc.trim() || undefined,
        classroomId,
      }),
    });

    if (createRes.error || !createRes.data?.id) {
      toast({ title: 'Galeri oluşturulamadı', description: createRes.error ?? undefined, variant: 'destructive' });
      setSaving(false);
      return;
    }

    const galleryId = createRes.data.id;

    if (files.length > 0) {
      setProgress({ done: 0, total: files.length });
      for (let i = 0; i < files.length; i++) {
        const fd = new FormData();
        fd.append('file', files[i].file);
        try {
          await apiFetch(`/v1/teacher/galleries/${galleryId}/images`, { method: 'POST', body: fd });
        } catch {
          // devam et
        }
        setProgress({ done: i + 1, total: files.length });
      }
    }

    setSaving(false);
    toast({ title: 'Galeri oluşturuldu', description: files.length > 0 ? `${files.length} fotoğraf yüklendi` : undefined });
    router.push('/teacher/gallery');
  };

  const selectedClassroom = classrooms.find((c) => c.id === classroomId);

  return (
    <div className="font-urbanist space-y-5 pb-10">

      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p className="text-[11px] font-semibold uppercase tracking-widest text-primary dark:text-teal-400">Galeri</p>
          <h1 className="mt-0.5 text-2xl font-bold tracking-tight text-zinc-900 dark:text-white">Yeni Galeri Oluştur</h1>
        </div>
        <a
          href="/teacher/gallery"
          className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-600 shadow-sm transition hover:bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300"
        >
          <ChevronLeft className="h-3.5 w-3.5" />
          Galeriler
        </a>
      </div>

      <div className="grid gap-5 lg:grid-cols-[1fr_360px]">

        {/* Sol: Form */}
        <div className="space-y-4">

          {/* Galeri Bilgileri */}
          <div className="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="border-b border-zinc-100 px-5 py-3.5 dark:border-zinc-800">
              <p className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">Galeri Bilgileri</p>
            </div>
            <div className="space-y-4 p-5">
              <div className="space-y-1.5">
                <label htmlFor="g-title" className="block text-xs font-semibold text-zinc-500 dark:text-zinc-400">
                  Galeri Adı <span className="text-red-500">*</span>
                </label>
                <input
                  id="g-title"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  maxLength={120}
                  placeholder="Örn: Bahar Etkinlikleri 2026"
                  className="h-9 w-full rounded-lg border border-zinc-200 bg-zinc-50 px-3 text-sm text-zinc-900 focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/20 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                />
                <p className="text-right text-[10px] text-zinc-400">{title.length}/120</p>
              </div>

              <div className="space-y-1.5">
                <label htmlFor="g-desc" className="block text-xs font-semibold text-zinc-500 dark:text-zinc-400">
                  Açıklama
                </label>
                <textarea
                  id="g-desc"
                  value={desc}
                  onChange={(e) => setDesc(e.target.value)}
                  maxLength={500}
                  rows={3}
                  placeholder="Kısa bir açıklama (isteğe bağlı)"
                  className="w-full resize-none rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm text-zinc-900 focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/20 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                />
                <p className="text-right text-[10px] text-zinc-400">{desc.length}/500</p>
              </div>

              {/* Sınıf */}
              <div className="space-y-1.5">
                <label className="block text-xs font-semibold text-zinc-500 dark:text-zinc-400">
                  Sınıf <span className="text-red-500">*</span>
                </label>
                {loadingData ? (
                  <div className="h-9 animate-pulse rounded-lg bg-zinc-100 dark:bg-zinc-800" />
                ) : classrooms.length === 1 ? (
                  <div className="flex items-center gap-2 rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 dark:border-zinc-700 dark:bg-zinc-800">
                    <BookOpen className="h-3.5 w-3.5 text-teal-500" />
                    <span className="text-sm font-medium text-zinc-800 dark:text-zinc-200">
                      {classrooms[0].branch?.name ? `${classrooms[0].branch.name} / ` : ''}{classrooms[0].name}
                    </span>
                  </div>
                ) : (
                  <select
                    value={classroomId}
                    onChange={(e) => setClassroomId(e.target.value)}
                    className="h-9 w-full rounded-lg border border-zinc-200 bg-zinc-50 px-3 text-sm text-zinc-900 focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/20 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100"
                  >
                    <option value="">Sınıf seçin</option>
                    {classrooms.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.branch?.name ? `${c.branch.name} / ` : ''}{c.name}
                      </option>
                    ))}
                  </select>
                )}
              </div>
            </div>
          </div>

          {/* Fotoğraflar */}
          <div className="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="border-b border-zinc-100 px-5 py-3.5 dark:border-zinc-800">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">Fotoğraflar</p>
                  <p className="text-xs text-zinc-400 dark:text-zinc-500">JPEG, PNG, WebP · max 10MB/dosya · max 50</p>
                </div>
                {files.length > 0 && (
                  <span className="rounded-full bg-teal-100 px-2.5 py-0.5 text-[10px] font-semibold text-teal-700 dark:bg-teal-900/40 dark:text-teal-300">
                    {files.length} seçili
                  </span>
                )}
              </div>
            </div>
            <div className="p-5 space-y-4">
              <div
                onDragEnter={(e) => { e.preventDefault(); setDragging(true); }}
                onDragLeave={(e) => { e.preventDefault(); setDragging(false); }}
                onDragOver={(e) => e.preventDefault()}
                onDrop={handleDrop}
                onClick={() => inputRef.current?.click()}
                className={`flex cursor-pointer flex-col items-center justify-center gap-3 rounded-xl border-2 border-dashed py-10 transition-all select-none ${
                  dragging
                    ? 'border-teal-500 bg-teal-50 dark:border-teal-500 dark:bg-teal-950/30'
                    : 'border-zinc-200 bg-zinc-50/50 hover:border-teal-400 hover:bg-teal-50/40 dark:border-zinc-700 dark:bg-zinc-800/20'
                }`}
              >
                <div className={`flex h-12 w-12 items-center justify-center rounded-xl transition-colors ${
                  dragging ? 'bg-teal-100 dark:bg-teal-900/50' : 'bg-white shadow-sm dark:bg-zinc-800'
                }`}>
                  <UploadCloud className={`h-6 w-6 ${dragging ? 'text-teal-600' : 'text-zinc-400'}`} strokeWidth={1.75} />
                </div>
                <div className="text-center">
                  <p className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">
                    {dragging ? 'Bırakın!' : 'Fotoğrafları sürükleyin'}
                  </p>
                  <p className="mt-0.5 text-xs text-zinc-400 dark:text-zinc-500">veya seçmek için tıklayın</p>
                </div>
                <input
                  ref={inputRef}
                  type="file"
                  multiple
                  accept="image/*"
                  className="hidden"
                  onChange={(e) => addFiles(e.target.files)}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>

              {files.length > 0 && (
                <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
                  {files.map((f) => (
                    <div key={f.id} className="group relative aspect-square overflow-hidden rounded-lg bg-zinc-100 dark:bg-zinc-800">
                      <img src={f.preview} alt="" className="h-full w-full object-cover" />
                      <button
                        type="button"
                        onClick={() => removeFile(f.id)}
                        className="absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition group-hover:opacity-100"
                      >
                        <X className="h-3 w-3" strokeWidth={2.5} />
                      </button>
                    </div>
                  ))}
                  <button
                    type="button"
                    onClick={() => inputRef.current?.click()}
                    className="flex aspect-square items-center justify-center rounded-lg border-2 border-dashed border-zinc-200 text-zinc-400 transition hover:border-teal-400 hover:text-teal-500 dark:border-zinc-700"
                  >
                    <ImagePlus className="h-5 w-5" />
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Sağ: Özet + Kaydet */}
        <div className="space-y-4">
          <div className="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="border-b border-zinc-100 px-5 py-3.5 dark:border-zinc-800">
              <p className="text-sm font-semibold text-zinc-700 dark:text-zinc-300">Özet</p>
            </div>
            <div className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
              <div className="flex items-center justify-between px-5 py-3">
                <span className="text-xs text-zinc-500">Ad</span>
                <span className="max-w-[180px] truncate text-right text-xs font-semibold text-zinc-800 dark:text-zinc-200">
                  {title.trim() || <span className="text-zinc-300">—</span>}
                </span>
              </div>
              <div className="flex items-center justify-between px-5 py-3">
                <span className="text-xs text-zinc-500">Sınıf</span>
                <span className="flex items-center gap-1 text-xs font-semibold text-zinc-800 dark:text-zinc-200">
                  {selectedClassroom ? (
                    <>
                      <BookOpen className="h-3 w-3 text-teal-500" />
                      {selectedClassroom.name}
                    </>
                  ) : '—'}
                </span>
              </div>
              <div className="flex items-center justify-between px-5 py-3">
                <span className="text-xs text-zinc-500">Fotoğraf</span>
                <span className="text-xs font-semibold text-zinc-800 dark:text-zinc-200">
                  {files.length > 0 ? `${files.length} dosya seçili` : 'Yok'}
                </span>
              </div>
            </div>

            {progress && (
              <div className="px-5 pb-4">
                <div className="mb-1.5 flex items-center justify-between text-xs">
                  <span className="text-zinc-500">Yükleniyor…</span>
                  <span className="font-semibold text-teal-600">{progress.done}/{progress.total}</span>
                </div>
                <div className="h-1.5 w-full overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800">
                  <div
                    className="h-full rounded-full bg-teal-500 transition-all"
                    style={{ width: `${(progress.done / progress.total) * 100}%` }}
                  />
                </div>
              </div>
            )}

            <div className="px-5 pb-5">
              <button
                type="button"
                disabled={saving || !title.trim() || !classroomId}
                onClick={handleSave}
                className="inline-flex w-full items-center justify-center gap-2 rounded-full bg-primary py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-[#1c5f66] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-teal-600 dark:hover:bg-teal-500"
              >
                {saving ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    {progress ? `Yükleniyor ${progress.done}/${progress.total}…` : 'Oluşturuluyor…'}
                  </>
                ) : (
                  <>
                    <CheckCircle2 className="h-4 w-4" />
                    Galeriyi Kaydet
                  </>
                )}
              </button>
            </div>
          </div>

          <div className="rounded-xl border border-zinc-100 bg-zinc-50 p-4 dark:border-zinc-800 dark:bg-zinc-800/30">
            <p className="text-xs font-semibold text-zinc-500 dark:text-zinc-400">İpucu</p>
            <p className="mt-1 text-xs text-zinc-400 dark:text-zinc-500 leading-relaxed">
              Fotoğraf seçmek isteğe bağlıdır. Galeriyi oluşturduktan sonra detay sayfasından fotoğraf ekleyebilirsiniz.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
