import { useState, useEffect, useCallback } from 'react';
import { supabase } from '../../lib/supabase';

const BUCKET = 'order-photos';

export function useOrderPhotos(orderId) {
  const [photos, setPhotos] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState(null);

  const fetchPhotos = useCallback(async () => {
    if (!orderId) return;
    const { data, error: err } = await supabase.storage.from(BUCKET).list(`${orderId}/`);
    if (err) { setError(err.message); return; }
    const urls = (data || [])
      .filter((f) => f.name !== '.emptyFolderPlaceholder')
      .map((f) => ({
        name: f.name,
        url: supabase.storage.from(BUCKET).getPublicUrl(`${orderId}/${f.name}`).data.publicUrl,
      }));
    setPhotos(urls);
  }, [orderId]);

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

  const uploadPhotos = async (files) => {
    if (!orderId || !files.length) return;
    setUploading(true);
    setError(null);
    for (const file of Array.from(files)) {
      const ext = file.name.split('.').pop();
      const path = `${orderId}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
      const { error: upErr } = await supabase.storage.from(BUCKET).upload(path, file, { upsert: false });
      if (upErr) { setError(upErr.message); }
    }
    setUploading(false);
    await fetchPhotos();
  };

  const deletePhoto = async (name) => {
    const { error: delErr } = await supabase.storage.from(BUCKET).remove([`${orderId}/${name}`]);
    if (delErr) { setError(delErr.message); return; }
    setPhotos((prev) => prev.filter((p) => p.name !== name));
  };

  return { photos, uploading, error, uploadPhotos, deletePhoto };
}
