'use client';

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

interface Treatment {
  id: number; name: string; slug: string; category: string;
  description: string; benefits: string | null; isActive: boolean;
}

interface Category {
  id: number; name: string; slug: string; description: string | null;
}

export default function AdminTreatmentsPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [treatments, setTreatments] = useState<Treatment[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [filterCat, setFilterCat] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const perPage = 10;
  const [form, setForm] = useState({ name: '', slug: '', category: 'facial', description: '', benefits: '', isActive: true });
  const [showCatModal, setShowCatModal] = useState(false);
  const [editingCatId, setEditingCatId] = useState<number | null>(null);
  const [catForm, setCatForm] = useState({ name: '', slug: '', description: '' });
  const [msg, setMsg] = useState('');

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

  const loadData = async () => {
    try {
      const [tRes, cRes] = await Promise.all([
        fetch(`${apiUrl}/api/treatments`),
        fetch(`${apiUrl}/api/treatment-categories`),
      ]);
      if (tRes.ok) setTreatments(await tRes.json());
      if (cRes.ok) setCategories(await cRes.json());
    } catch (e) {}
    finally { setLoading(false); }
  };

  const headers = () => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` });

  const filtered = treatments.filter(t => {
    const matchCat = !filterCat || t.category === filterCat;
    const matchSearch = t.name.toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSearch;
  });
  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const paginated = filtered.slice((page - 1) * perPage, page * perPage);

  const openCreate = () => {
    setEditingId(null); setForm({ name: '', slug: '', category: 'facial', description: '', benefits: '', isActive: true }); setShowForm(true);
  };
  const openEdit = (t: Treatment) => {
    setEditingId(t.id); setForm({ name: t.name, slug: t.slug, category: t.category, description: t.description, benefits: t.benefits || '', isActive: t.isActive }); setShowForm(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const body = { ...form, slug: form.slug || form.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') };
    try {
      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${apiUrl}/api/treatments/${editingId}` : `${apiUrl}/api/treatments`;
      const res = await fetch(url, { method, headers: headers(), body: JSON.stringify(body) });
      if (res.ok) { setShowForm(false); setPage(1); loadData(); }
      else { const d = await res.json(); alert(d.message || 'Gagal'); }
    } catch (e) { alert('Gagal'); }
  };

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

  // Category CRUD
  const openCatEdit = (c: Category) => { setEditingCatId(c.id); setCatForm({ name: c.name, slug: c.slug, description: c.description || '' }); setShowCatModal(true); };
  const handleCatDelete = async (id: number) => {
    if (!confirm('Hapus kategori?')) return;
    const res = await fetch(`${apiUrl}/api/treatment-categories/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` } });
    if (res.ok) loadData();
  };

  return (
    <AdminLayout title="Treatments">
      <div className="space-y-6">
        <div className="flex flex-wrap gap-2 items-center">
          <span className="text-xs font-semibold text-gray-400 uppercase mr-1">Kategori:</span>
          {categories.map(c => (
            <div key={c.id} className="group flex items-center gap-1 px-3 py-1 bg-gold/10 text-gold rounded-full text-xs font-medium">
              <span>{c.name}</span>
              <button onClick={() => openCatEdit(c)} className="opacity-0 group-hover:opacity-100 hover:text-gold-dark transition ml-0.5 text-[10px]">✏️</button>
              <button onClick={() => handleCatDelete(c.id)} className="opacity-0 group-hover:opacity-100 hover:text-red-500 transition text-[10px]">✕</button>
            </div>
          ))}
          <button onClick={() => { setEditingCatId(null); setCatForm({ name: '', slug: '', description: '' }); setShowCatModal(true); }}
            className="px-3 py-1 text-xs border border-dashed border-gray-300 text-gray-400 rounded-full hover:border-gold hover:text-gold transition">+ Kategori</button>
        </div>

        {showCatModal && (
          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <h3 className="font-semibold text-gray-800 mb-3">{editingCatId ? 'Edit' : 'Tambah'} Kategori</h3>
            {msg && <p className="text-sm text-red-500 mb-2">{msg}</p>}
            <form onSubmit={async (e) => { e.preventDefault(); setMsg('');
              try {
                const method = editingCatId ? 'PUT' : 'POST';
                const url = editingCatId ? `${apiUrl}/api/treatment-categories/${editingCatId}` : `${apiUrl}/api/treatment-categories`;
                const res = await fetch(url, { method, headers: headers(), body: JSON.stringify(catForm) });
                if (res.ok) { setShowCatModal(false); loadData(); } else { const d = await res.json(); setMsg(d.message); }
              } catch (e) { setMsg('Gagal'); }
            }} className="flex flex-wrap gap-3 items-end">
              <div><label className="admin-label">Nama</label><input type="text" value={catForm.name} onChange={e => setCatForm({ ...catForm, name: e.target.value, slug: editingCatId ? catForm.slug : e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') })} required className="admin-input w-52" /></div>
              <div><label className="admin-label">Slug</label><input type="text" value={catForm.slug} onChange={e => setCatForm({ ...catForm, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })} className="admin-input w-40" placeholder="Otomatis dari nama" /></div>
                <div><label className="admin-label">Deskripsi</label><textarea value={catForm.description} onChange={e => setCatForm({ ...catForm, description: e.target.value })} className="admin-textarea w-80" rows={3} /></div>
              <div className="flex gap-2 items-end"><button type="submit" className="admin-btn-primary">{editingCatId ? 'Simpan' : 'Tambah'}</button><button type="button" onClick={() => setShowCatModal(false)} className="admin-btn-secondary">Batal</button></div>
            </form>
          </div>
        )}

        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{treatments.length} treatment · {categories.length} kategori</p>
          <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 Treatment</button>
        </div>

        <div className="flex flex-col sm:flex-row gap-3">
          <input type="text" value={search} onChange={e => setSearch(e.target.value)} className="admin-input flex-[3]" placeholder="Cari treatment..." />
          <select value={filterCat} onChange={e => { setFilterCat(e.target.value); setPage(1); }} className="admin-select flex-1 sm:max-w-[220px]">
            <option value="">Semua Kategori</option>
            {categories.map(c => <option key={c.slug} value={c.slug}>{c.name}</option>)}
          </select>
        </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'} Treatment</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-lg">
                <div><label className="admin-label">Nama *</label><input type="text" value={form.name} onChange={e => setForm({ ...form, name: e.target.value, slug: editingId ? form.slug : e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') })} required className="admin-input" /></div>
                <div><label className="admin-label">Slug</label><input type="text" value={form.slug} onChange={e => setForm({ ...form, slug: e.target.value })} className="admin-input" placeholder="Otomatis dari nama" /></div>
                <div><label className="admin-label">Kategori *</label><select value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} required className="admin-select">{categories.map(c => <option key={c.slug} value={c.slug}>{c.name}</option>)}</select></div>
              </div>
              <div>
                <label className="admin-label">Gambar Treatment</label>
                <div className="flex items-center gap-4 p-3 bg-ivory rounded-lg border border-blush mb-3 max-w-md">
                  <Image src="/images/Logo-Carla.png" alt="Carla" width={80} height={28} className="h-7 w-auto" />
                  <span className="text-xs text-grey">Logo Carla Skin Clinic (tetap)</span>
                </div>
              </div>
              <div>
                <label className="admin-label">Deskripsi *</label>
                <RichTextEditor value={form.description} onChange={html => setForm({ ...form, description: html })} placeholder="Tulis deskripsi treatment..." />
              </div>
              <div><label className="admin-label">Benefits (pisahkan dengan ||)</label><textarea value={form.benefits} onChange={e => setForm({ ...form, benefits: e.target.value })} className="admin-textarea" rows={2} /></div>
              <div className="flex items-center gap-3"><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 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">Tidak ada treatment</p></div>
        ) : (
          <>
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="admin-table">
                <thead><tr><th>Treatment</th><th>Kategori</th><th className="text-right">Aksi</th></tr></thead>
                <tbody>{paginated.map(t => (
                  <tr key={t.id}>
                    <td><p className="font-medium text-gray-800">{t.name}</p><p className="text-xs text-gray-400 truncate max-w-md">{t.description}</p></td>
                    <td><span className="bg-gold/10 text-gold px-2 py-0.5 rounded-full text-xs font-medium">{categories.find(c => c.slug === t.category)?.name || t.category}</span></td>
                    <td className="text-right"><button onClick={() => openEdit(t)} className="admin-btn-edit mr-1">Edit</button><button onClick={() => handleDelete(t.id)} className="admin-btn-danger">Hapus</button></td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
