'use client';
import { useRef, useState } from 'react';
import { PHOTO_EDGE, PHOTO_MAX } from '@/lib/photos';

export type Photo = { id: string; url: string; key?: string; err?: string };

/** Uzun kenarı PHOTO_EDGE'e indirip JPEG yapar; createImageBitmap telefon fotoğrafının EXIF yönünü uygular. */
async function shrink(file: File): Promise<Blob> {
  const bmp = await createImageBitmap(file, { imageOrientation: 'from-image' });
  const k = Math.min(1, PHOTO_EDGE / Math.max(bmp.width, bmp.height));
  const c = document.createElement('canvas'); c.width = Math.round(bmp.width * k); c.height = Math.round(bmp.height * k);
  c.getContext('2d')!.drawImage(bmp, 0, 0, c.width, c.height); bmp.close();
  return new Promise((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error('Fotoğraf işlenemedi'))), 'image/jpeg', 0.86));
}

export function PhotoUpload({ photos, onChange }: { photos: Photo[]; onChange: (fn: (p: Photo[]) => Photo[]) => void }) {
  const input = useRef<HTMLInputElement>(null);
  const [drag, setDrag] = useState(false);
  const room = PHOTO_MAX - photos.length;

  async function add(files: FileList | File[]) {
    const list = [...files].filter((f) => f.type.startsWith('image/') || /\.(heic|heif)$/i.test(f.name)).slice(0, room);
    for (const f of list) {
      const id = Math.random().toString(36).slice(2);
      const url = URL.createObjectURL(f);
      onChange((p) => [...p, { id, url }]);
      (async () => {
        try {
          const fd = new FormData(); fd.append('photo', await shrink(f), 'photo.jpg');
          const r = await fetch('/api/orders/photos', { method: 'POST', body: fd });
          const j = await r.json().catch(() => ({}));
          if (!r.ok || !j.key) throw new Error(j.error || 'Yüklenemedi');
          onChange((p) => p.map((x) => (x.id === id ? { ...x, key: j.key } : x)));
        } catch (e) {
          onChange((p) => p.map((x) => (x.id === id ? { ...x, err: (e as Error).message || 'Yüklenemedi' } : x)));
        }
      })();
    }
  }
  const move = (i: number, d: number) => onChange((p) => { const q = [...p]; const j = i + d; if (j < 0 || j >= q.length) return p; [q[i], q[j]] = [q[j], q[i]]; return q; });
  const remove = (id: string) => onChange((p) => { const x = p.find((y) => y.id === id); if (x) URL.revokeObjectURL(x.url); return p.filter((y) => y.id !== id); });

  return (
    <div>
      <div className="grid grid-cols-3 gap-2">
        {photos.map((p, i) => (
          <figure key={p.id} className="relative aspect-[3/4] overflow-hidden bg-paper-2">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={p.url} alt={`Fotoğraf ${i + 1}`} className={`h-full w-full object-cover ${p.key ? '' : 'opacity-50'}`} />
            <span className="num absolute left-0 top-0 bg-ink px-1.5 text-[11.5px] font-bold text-white">{i + 1}</span>
            {!p.key && !p.err && <span className="absolute inset-x-0 bottom-7 text-center text-[11.5px] font-semibold">Yükleniyor…</span>}
            {p.err && <span className="absolute inset-x-1 bottom-7 bg-white/90 px-1 text-center text-[11px] font-semibold text-survey-dark">{p.err}</span>}
            <div className="absolute inset-x-0 bottom-0 flex bg-ink/80 text-white">
              <button type="button" aria-label="Öne al" disabled={i === 0} onClick={() => move(i, -1)} className="h-6 flex-1 text-[13px] disabled:opacity-30">‹</button>
              <button type="button" aria-label="Fotoğrafı kaldır" onClick={() => remove(p.id)} className="h-6 flex-1 text-[12px] font-semibold">Sil</button>
              <button type="button" aria-label="Arkaya al" disabled={i === photos.length - 1} onClick={() => move(i, 1)} className="h-6 flex-1 text-[13px] disabled:opacity-30">›</button>
            </div>
          </figure>
        ))}
        {room > 0 && (
          <button type="button" onClick={() => input.current?.click()}
            onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)}
            onDrop={(e) => { e.preventDefault(); setDrag(false); add(e.dataTransfer.files); }}
            className={`flex aspect-[3/4] flex-col items-center justify-center gap-1 border-2 border-dashed text-center text-[12.5px] font-semibold ${drag ? 'border-signal bg-signal-soft' : 'border-ink/25 text-ink-soft hover:border-ink/50'}`}>
            <span className="text-[22px] leading-none">+</span>
            <span>Fotoğraf ekle</span>
            <span className="text-[11px] font-normal">{photos.length ? `${room} yer kaldı` : `En çok ${PHOTO_MAX}`}</span>
          </button>
        )}
      </div>
      <input ref={input} type="file" accept="image/*" multiple hidden onChange={(e) => { if (e.target.files) add(e.target.files); e.target.value = ''; }} />
    </div>
  );
}
