'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import AdminLayout from '@/components/admin/AdminLayout';
import Pagination from '@/components/admin/Pagination';

interface Banner {
  id: number;
  title: string;
  subtitle: string | null;
  image: string;
  link: string | null;
  buttonText: string | null;
  sortOrder: number;
  isActive: boolean;
}

export default function AdminBannerPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [banners, setBanners] = useState<Banner[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [photoFile, setPhotoFile] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const perPage = 10;
  const [form, setForm] = useState({ title: '', subtitle: '', link: '', buttonText: '', sortOrder: 1, isActive: true });

  useEffect(() => {
    const token = localStorage.getItem('admin_token') || localStorage.getItem('admin_logged_in');
    if (!token) { router.push('/admin/login'); return; }
    loadBanners();
  }, [router]);

  const loadBanners = async () => {
    try {
      const res = await fetch(`${apiUrl}/api/banners`);
      if (res.ok) setBanners(await res.json());
    } catch (e) { console.log('Gagal load banners'); }
    finally { setLoading(false); }
  };

  const sorted = [...banners].sort((a, b) => a.sortOrder - b.sortOrder);
  const totalPages = Math.max(1, Math.ceil(sorted.length / perPage));
  const paginated = sorted.slice((page - 1) * perPage, page * perPage);

  const openCreate = () => {
    setEditingId(null);
    setForm({ title: '', subtitle: '', link: '', buttonText: '', sortOrder: 1, isActive: true });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const openEdit = (b: Banner) => {
    setEditingId(b.id);
    setForm({ title: b.title, subtitle: b.subtitle || '', link: b.link || '', buttonText: b.buttonText || '', sortOrder: b.sortOrder, isActive: b.isActive });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const fd = new FormData();
      fd.append('title', form.title);
      fd.append('subtitle', form.subtitle);
      fd.append('link', form.link);
      fd.append('buttonText', form.buttonText);
      fd.append('sortOrder', form.sortOrder.toString());
      fd.append('isActive', form.isActive.toString());
      if (photoFile) fd.append('image', photoFile);

      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${apiUrl}/api/banners/${editingId}` : `${apiUrl}/api/banners`;
      const res = await fetch(url, { method, headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` }, body: fd });
      if (res.ok) { setShowForm(false); loadBanners(); }
      else alert('Gagal menyimpan');
    } catch (e) { alert('Gagal'); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus banner ini?')) return;
    const res = await fetch(`${apiUrl}/api/banners/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` } });
    if (res.ok) loadBanners();
  };

  return (
    <AdminLayout title="Banner Slider">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{banners.length} banner · urutan berdasarkan sort order</p>
          <div className="flex gap-2">
            <button onClick={openCreate} className="admin-btn-primary"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4"/></svg>Tambah Banner</button>
          </div>
        </div>

        {showForm && (
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-800 mb-4">{editingId ? 'Edit' : 'Tambah'} Banner</h3>
            <form onSubmit={handleSubmit} className="space-y-4 max-w-lg">
              <div><label className="admin-label">Judul *</label><input type="text" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} required className="admin-input" /></div>
              <div><label className="admin-label">Subtitle</label><textarea value={form.subtitle} onChange={e => setForm({ ...form, subtitle: e.target.value })} className="admin-textarea" rows={2} /></div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div><label className="admin-label">Link CTA</label><input type="text" value={form.link} onChange={e => setForm({ ...form, link: e.target.value })} className="admin-input" placeholder="/online-booking" /></div>
                <div><label className="admin-label">Tombol CTA</label><input type="text" value={form.buttonText} onChange={e => setForm({ ...form, buttonText: e.target.value })} className="admin-input" placeholder="Booking Sekarang" /></div>
                <div><label className="admin-label">Urutan (sort order)</label><input type="number" value={form.sortOrder} onChange={e => setForm({ ...form, sortOrder: parseInt(e.target.value) || 1 })} className="admin-input" min={1} /></div>
                <div className="flex items-end pb-2"><label className="flex items-center gap-2"><input type="checkbox" checked={form.isActive} onChange={e => setForm({ ...form, isActive: e.target.checked })} className="accent-gold" /><span className="text-sm text-gray-600">Aktif</span></label></div>
              </div>
              <div><label className="admin-label">Gambar Banner</label>
                <label className="inline-flex items-center gap-2 px-4 py-2 bg-gold text-white text-xs font-semibold rounded-lg cursor-pointer hover:bg-gold-dark transition">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                  Pilih Gambar
                  <input type="file" accept="image/*" onChange={e => { const f = e.target.files?.[0]; if (f) { setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); } }} className="hidden" />
                </label>
                {(photoPreview || (editingId && banners.find(b => b.id === editingId)?.image)) && (
                  <img src={photoPreview || banners.find(b => b.id === editingId)?.image || ''} className="w-full h-32 object-cover mt-2 rounded-lg border" />
                )}
              </div>
              <div className="flex gap-3 justify-end pt-2 border-t border-gray-100">
                <button type="button" onClick={() => setShowForm(false)} className="admin-btn-secondary">Batal</button>
                <button type="submit" className="admin-btn-primary">{editingId ? 'Simpan' : 'Tambah'}</button>
              </div>
            </form>
          </div>
        )}

        {loading ? (
          <p className="text-gray-400">Memuat...</p>
        ) : paginated.length === 0 ? (
          <div className="bg-white rounded-xl border border-gray-200 p-12 text-center"><p className="text-4xl mb-3">🖼️</p><p className="text-gray-500">Belum ada banner</p></div>
        ) : (
          <>
            <div className="space-y-4">
              {paginated.map((b, idx) => (
                <div key={b.id} className="bg-white rounded-xl border border-gray-200 overflow-hidden flex flex-col md:flex-row hover:shadow-md transition">
                  <div className="md:w-48 h-32 bg-gray-100 flex-shrink-0 overflow-hidden">
                    {b.image ? <img src={b.image} className="w-full h-full object-cover" /> : <div className="w-full h-full flex items-center justify-center text-gray-300 text-sm">No Image</div>}
                  </div>
                  <div className="p-4 flex-1 flex flex-col justify-between">
                    <div>
                      <div className="flex items-start justify-between gap-3">
                        <h3 className="font-semibold text-gray-800">{b.title}</h3>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          <span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">#{b.sortOrder}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${b.isActive ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-500'}`}>{b.isActive ? 'Aktif' : 'Nonaktif'}</span>
                        </div>
                      </div>
                      {b.subtitle && <p className="text-sm text-gray-500 mt-1">{b.subtitle}</p>}
                      <div className="flex gap-3 mt-2 text-xs text-gray-400">
                        {b.buttonText && <span>🔗 {b.buttonText}</span>}
                        {b.link && <span>→ {b.link}</span>}
                      </div>
                    </div>
                    <div className="flex gap-2 justify-end mt-3 pt-3 border-t border-gray-100">
                      <button onClick={() => openEdit(b)} className="admin-btn-edit">Edit</button>
                      <button onClick={() => handleDelete(b.id)} className="admin-btn-danger">Hapus</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
