'use client';

import { useState, useEffect } from 'react';
import type { Artwork } from '@/lib/types';

function ImageUpload({ currentImage, onUpload }: { currentImage: string; onUpload: (url: string) => void }) {
  const [uploading, setUploading] = useState(false);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    const form = new FormData();
    form.append('file', file);
    try {
      const res = await fetch('/api/admin/upload', { method: 'POST', body: form });
      const data = await res.json();
      if (data.url) onUpload(data.url);
    } catch { /* ignore */ }
    setUploading(false);
  };

  return (
    <div>
      {currentImage && (
        <div className="w-20 h-20 bg-gray-100 rounded overflow-hidden mb-2">
          <img src={currentImage} alt="" className="w-full h-full object-cover" />
        </div>
      )}
      <label className="text-xs text-blue-600 hover:text-blue-800 cursor-pointer">
        {uploading ? 'Uploading...' : currentImage ? 'Change image' : 'Upload image'}
        <input type="file" accept="image/*" onChange={handleUpload} className="hidden" disabled={uploading} />
      </label>
    </div>
  );
}

export default function AdminArtworks() {
  const [artworks, setArtworks] = useState<Artwork[]>([]);
  const [editing, setEditing] = useState<Artwork | null>(null);
  const [isNew, setIsNew] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchArtworks = async () => {
    const res = await fetch('/api/admin/artworks');
    setArtworks(await res.json());
    setLoading(false);
  };

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

  const handleSave = async () => {
    if (!editing) return;
    const method = isNew ? 'POST' : 'PUT';
    const url = isNew ? '/api/admin/artworks' : `/api/admin/artworks/${editing.id}`;
    await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(editing),
    });
    setEditing(null);
    setIsNew(false);
    fetchArtworks();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this artwork?')) return;
    await fetch(`/api/admin/artworks/${id}`, { method: 'DELETE' });
    fetchArtworks();
  };

  const newArtwork = (): Artwork => ({
    id: `art-${Date.now()}`,
    title: '',
    medium: '',
    dimensions: '',
    year: '',
    price: '',
    image: '',
    category: 'available',
    featured: false,
    sortOrder: artworks.length + 1,
  });

  if (loading) return <div className="p-8 text-gray-400">Loading...</div>;

  return (
    <div className="p-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-light">Artworks</h1>
        <button
          onClick={() => { setEditing(newArtwork()); setIsNew(true); }}
          className="px-4 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors"
        >
          + Add Artwork
        </button>
      </div>

      {/* Edit Modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-lg w-full max-h-[90vh] overflow-y-auto p-6">
            <h2 className="text-xl font-light mb-4">{isNew ? 'New Artwork' : 'Edit Artwork'}</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs tracking-widest mb-1">TITLE</label>
                <input value={editing.title} onChange={(e) => setEditing({...editing, title: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">MEDIUM</label>
                  <input value={editing.medium} onChange={(e) => setEditing({...editing, medium: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">DIMENSIONS</label>
                  <input value={editing.dimensions} onChange={(e) => setEditing({...editing, dimensions: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">YEAR</label>
                  <input value={editing.year} onChange={(e) => setEditing({...editing, year: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">PRICE</label>
                  <input value={editing.price} onChange={(e) => setEditing({...editing, price: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
              <div>
                <label className="block text-xs tracking-widest mb-1">IMAGE</label>
                <ImageUpload currentImage={editing.image} onUpload={(url) => setEditing({...editing, image: url})} />
                <input value={editing.image} onChange={(e) => setEditing({...editing, image: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm mt-2 focus:outline-none focus:border-[#c9a962]"
                  placeholder="Or paste image path" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">CATEGORY</label>
                  <select value={editing.category} onChange={(e) => setEditing({...editing, category: e.target.value as Artwork['category']})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]">
                    <option value="available">Available</option>
                    <option value="sold">Sold</option>
                    <option value="private">Private Collection</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">SORT ORDER</label>
                  <input type="number" value={editing.sortOrder} onChange={(e) => setEditing({...editing, sortOrder: parseInt(e.target.value) || 0})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={editing.featured} onChange={(e) => setEditing({...editing, featured: e.target.checked})} />
                Featured artwork
              </label>
            </div>
            <div className="flex gap-3 mt-6">
              <button onClick={handleSave} className="px-6 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors">
                Save
              </button>
              <button onClick={() => { setEditing(null); setIsNew(false); }} className="px-6 py-2 border rounded-lg text-sm hover:bg-gray-50">
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Artwork List */}
      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left">
            <tr>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">IMAGE</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">TITLE</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">CATEGORY</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">FEATURED</th>
              <th className="px-4 py-3 text-xs tracking-widest text-gray-500">ACTIONS</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {artworks.sort((a, b) => a.sortOrder - b.sortOrder).map((artwork) => (
              <tr key={artwork.id} className="hover:bg-gray-50">
                <td className="px-4 py-3">
                  {artwork.image && (
                    <div className="w-12 h-12 rounded overflow-hidden bg-gray-100">
                      <img src={artwork.image} alt="" className="w-full h-full object-cover" />
                    </div>
                  )}
                </td>
                <td className="px-4 py-3 font-medium">{artwork.title}</td>
                <td className="px-4 py-3">
                  <span className={`text-xs px-2 py-1 rounded-full ${
                    artwork.category === 'available' ? 'bg-green-100 text-green-700' :
                    artwork.category === 'sold' ? 'bg-red-100 text-red-700' :
                    'bg-purple-100 text-purple-700'
                  }`}>
                    {artwork.category}
                  </span>
                </td>
                <td className="px-4 py-3">{artwork.featured ? 'Yes' : ''}</td>
                <td className="px-4 py-3">
                  <button onClick={() => { setEditing(artwork); setIsNew(false); }} className="text-blue-600 hover:text-blue-800 mr-3 text-xs">
                    Edit
                  </button>
                  <button onClick={() => handleDelete(artwork.id)} className="text-red-600 hover:text-red-800 text-xs">
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
