"use client";

import { useState, useEffect } from "react";

interface Testimonial {
  id: string;
  clientName: string;
  company: string | null;
  photo: string | null;
  contentId: string;
  contentEn: string;
  rating: number;
  isActive: boolean;
  createdAt: string;
}

export default function TestimonialsPage() {
  const [items, setItems] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingItem, setEditingItem] = useState<Testimonial | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({
    clientName: "",
    company: "",
    photo: "",
    contentId: "",
    contentEn: "",
    rating: 5,
    isActive: true,
  });

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

  async function fetchItems() {
    const res = await fetch("/api/admin/testimonials");
    const data = await res.json();
    setItems(data);
    setLoading(false);
  }

  function resetForm() {
    setFormData({ clientName: "", company: "", photo: "", contentId: "", contentEn: "", rating: 5, isActive: true });
    setEditingItem(null);
  }

  function handleEdit(item: Testimonial) {
    setEditingItem(item);
    setFormData({
      clientName: item.clientName, company: item.company || "", photo: item.photo || "",
      contentId: item.contentId, contentEn: item.contentEn, rating: item.rating, isActive: item.isActive,
    });
    setShowForm(true);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const url = editingItem ? `/api/admin/testimonials/${editingItem.id}` : "/api/admin/testimonials";
    const method = editingItem ? "PUT" : "POST";
    await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData) });
    setShowForm(false); resetForm(); fetchItems();
  }

  async function handleDelete(id: string) {
    if (!confirm("Yakin ingin menghapus?")) return;
    await fetch(`/api/admin/testimonials/${id}`, { method: "DELETE" });
    fetchItems();
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">Testimoni</h1>
          <p className="text-gray-500">Kelola testimoni klien</p>
        </div>
        <button onClick={() => { resetForm(); setShowForm(true); }} className="px-4 py-2 bg-brand-blue text-white rounded-lg hover:bg-brand-blue-dark transition-colors">
          + Tambah Testimoni
        </button>
      </div>

      {showForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-100">
              <h2 className="text-lg font-semibold">{editingItem ? "Edit Testimoni" : "Tambah Testimoni"}</h2>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><label className="block text-sm font-medium text-gray-700 mb-1">Nama Klien</label><input type="text" value={formData.clientName} onChange={(e) => setFormData({ ...formData, clientName: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none" required /></div>
                <div><label className="block text-sm font-medium text-gray-700 mb-1">Perusahaan</label><input type="text" value={formData.company} onChange={(e) => setFormData({ ...formData, company: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none" /></div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div><label className="block text-sm font-medium text-gray-700 mb-1">Konten (ID)</label><textarea value={formData.contentId} onChange={(e) => setFormData({ ...formData, contentId: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none" rows={3} required /></div>
                <div><label className="block text-sm font-medium text-gray-700 mb-1">Konten (EN)</label><textarea value={formData.contentEn} onChange={(e) => setFormData({ ...formData, contentEn: e.target.value })} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none" rows={3} required /></div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div><label className="block text-sm font-medium text-gray-700 mb-1">Rating (1-5)</label><input type="number" min={1} max={5} value={formData.rating} onChange={(e) => setFormData({ ...formData, rating: Number(e.target.value) })} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-transparent outline-none" /></div>
                <div className="flex items-center gap-2 pt-6"><input type="checkbox" id="isActive" checked={formData.isActive} onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })} className="w-4 h-4 text-brand-blue rounded" /><label htmlFor="isActive" className="text-sm text-gray-700">Aktif</label></div>
              </div>
              <div className="flex gap-3 pt-4">
                <button type="submit" className="px-6 py-2 bg-brand-blue text-white rounded-lg hover:bg-brand-blue-dark transition-colors">Simpan</button>
                <button type="button" onClick={() => { setShowForm(false); resetForm(); }} className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">Batal</button>
              </div>
            </form>
          </div>
        </div>
      )}

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Perusahaan</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rating</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aksi</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {items.map((item) => (
              <tr key={item.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 text-sm font-medium text-gray-800">{item.clientName}</td>
                <td className="px-6 py-4 text-sm text-gray-500">{item.company || "-"}</td>
                <td className="px-6 py-4 text-sm text-gray-500">{"★".repeat(item.rating)}</td>
                <td className="px-6 py-4"><span className={`px-2 py-1 text-xs font-medium rounded-full ${item.isActive ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500"}`}>{item.isActive ? "Aktif" : "Nonaktif"}</span></td>
                <td className="px-6 py-4">
                  <div className="flex gap-2">
                    <button onClick={() => handleEdit(item)} className="px-3 py-1 text-sm text-brand-blue hover:bg-brand-blue/10 rounded-lg transition-colors">Edit</button>
                    <button onClick={() => handleDelete(item.id)} className="px-3 py-1 text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors">Hapus</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
