'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 Testimonial {
  id: number;
  name: string;
  text: string;
  rating: number;
  photo: string | null;
  position: string | null;
  isActive: boolean;
}

export default function AdminTestimonialsPage() {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState({ name: '', text: '', rating: 5, position: '', isActive: true });
  const [photoFile, setPhotoFile] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [page, setPage] = useState(1);
  const perPage = 10;
  const totalPages = Math.max(1, Math.ceil(testimonials.length / perPage));
  const paginated = testimonials.slice((page - 1) * perPage, page * perPage);

  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';

  useEffect(() => {
    const token = localStorage.getItem('admin_token');
    const loggedIn = localStorage.getItem('admin_logged_in');
    if (!token && !loggedIn) { router.push('/admin/login'); return; }
    setIsLoggedIn(true);
    loadTestimonials();
  }, [router]);

  const loadTestimonials = async () => {
    try {
      const res = await fetch(`${apiUrl}/api/testimonials`);
      if (res.ok) setTestimonials(await res.json());
    } catch (e) {}
    finally { setLoading(false); }
  };

  const openCreate = () => {
    setEditingId(null);
    setForm({ name: '', text: '', rating: 5, position: '', isActive: true });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const openEdit = (t: Testimonial) => {
    setEditingId(t.id);
    setForm({ name: t.name, text: t.text, rating: t.rating, position: t.position || '', isActive: t.isActive });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setSubmitting(true);
    try {
      const fd = new FormData();
      fd.append('name', form.name); fd.append('text', form.text);
      fd.append('rating', form.rating.toString()); fd.append('position', form.position);
      if (photoFile) fd.append('photo', photoFile);
      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${apiUrl}/api/testimonials/${editingId}` : `${apiUrl}/api/testimonials`;
      const res = await fetch(url, { method, body: fd });
      if (res.ok) { setShowForm(false); setPage(1); loadTestimonials(); }
      else { const d = await res.json(); alert(d.message || 'Gagal'); }
    } catch (e) { alert('Gagal menyimpan'); }
    finally { setSubmitting(false); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus testimonial ini?')) return;
    try { await fetch(`${apiUrl}/api/testimonials/${id}`, { method: 'DELETE' }); loadTestimonials(); }
    catch (e) { alert('Gagal menghapus'); }
  };

  if (!isLoggedIn) return null;

  return (
    <AdminLayout title="Testimonial">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{testimonials.length} testimonial</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</button>
        </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'} Testimonial</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div><label className="admin-label">Nama *</label><input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required className="admin-input" /></div>
                <div><label className="admin-label">Rating</label><select value={form.rating} onChange={(e) => setForm({ ...form, rating: +e.target.value })} className="admin-select">{[5,4,3,2,1].map(n => <option key={n} value={n}>{'★'.repeat(n)}{'☆'.repeat(5-n)}</option>)}</select></div>
                <div><label className="admin-label">Foto</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 Foto
                    <input type="file" ref={fileInputRef} onChange={(e) => { const f = e.target.files?.[0]; if (f) { setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); } }} className="hidden" accept="image/*" />
                  </label>
                {(photoPreview || (editingId && testimonials.find(t => t.id === editingId)?.photo)) && <img src={photoPreview || testimonials.find(t => t.id === editingId)?.photo || ''} className="w-14 h-14 rounded-full object-cover mt-2 border" />}</div>
                <div><label className="admin-label">Pekerjaan</label><input type="text" value={form.position} onChange={(e) => setForm({ ...form, position: e.target.value })} className="admin-input" /></div>
              </div>
              <div><label className="admin-label">Testimonial *</label><textarea value={form.text} onChange={(e) => setForm({ ...form, text: e.target.value })} required className="admin-textarea" /></div>
              <div className="flex items-center gap-2"><input type="checkbox" checked={form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} className="accent-gold" id="active" /><label htmlFor="active" className="text-sm text-gray-600">Aktif</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" disabled={submitting} className="admin-btn-primary">{submitting ? '...' : 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 testimonial</p></div>
        ) : (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {paginated.map(t => (
                <div key={t.id} className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <div className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center overflow-hidden flex-shrink-0">
                        {t.photo ? <img src={t.photo} className="w-full h-full object-cover" /> : <span className="text-lg font-semibold text-gray-500">{t.name.charAt(0)}</span>}
                      </div>
                      <div>
                        <p className="font-semibold text-gray-800">{t.name}</p>
                        <div className="flex gap-0.5">{[...Array(5)].map((_, i) => <svg key={i} className={`w-3.5 h-3.5 ${i < t.rating ? 'text-gold' : 'text-gray-200'}`} fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>)}</div>
                        {t.position && <p className="text-xs text-gray-400">{t.position}</p>}
                      </div>
                    </div>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${t.isActive ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-500'}`}>{t.isActive ? 'Aktif' : 'Nonaktif'}</span>
                  </div>
                  <p className="text-sm text-gray-600 italic mb-3 line-clamp-3">&ldquo;{t.text}&rdquo;</p>
                  <div className="flex gap-2 justify-end pt-2 border-t border-gray-100">
                    <button onClick={() => openEdit(t)} className="admin-btn-edit">Edit</button>
                    <button onClick={() => handleDelete(t.id)} className="admin-btn-danger">Hapus</button>
                  </div>
                </div>
              ))}
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
