"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/auth";
import { Plus, Trash2, Edit2, Loader2, Save, X } from "lucide-react";

const API = process.env.NEXT_PUBLIC_API_URL ;

export default function AdminAnnouncementsPage() {
  const { token } = useAuth();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ title: "", content: "", type: "info", active: true });

  const fetchData = async () => {
    if (!token) return;
    setLoading(true);
    try {
      const res = await fetch(`${API}/api/admin/announcements`, { headers: { Authorization: `Bearer ${token}` } });
      const json = await res.json();
      if (json.success) setItems(json.data);
    } catch (err) { console.error(err); }
    finally { setLoading(false); }
  };

  const handleSave = async () => {
    const method = editing?.id ? "PUT" : "POST";
    const url = editing?.id ? `${API}/api/admin/announcements/${editing.id}` : `${API}/api/admin/announcements`;
    try {
      const res = await fetch(url, {
        method, headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify(form),
      });
      const json = await res.json();
      if (json.success) { setEditing(null); setForm({ title: "", content: "", type: "info", active: true }); fetchData(); }
    } catch { alert("Gagal menyimpan"); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Hapus pengumuman ini?")) return;
    try {
      await fetch(`${API}/api/admin/announcements/${id}`, { method: "DELETE", headers: { Authorization: `Bearer ${token}` } });
      fetchData();
    } catch { alert("Gagal menghapus"); }
  };

  useEffect(() => { fetchData(); }, [token]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold text-white">Pengumuman</h1>
        <button
          onClick={() => { setEditing({}); setForm({ title: "", content: "", type: "info", active: true }); }}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-bold hover:bg-red-500/20 transition-all"
        >
          <Plus size={14} /> Tambah
        </button>
      </div>

      {/* Edit Form */}
      {editing && (
        <div className="bg-dark-surface rounded-xl border border-dark-border p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-bold text-white">{editing.id ? "Edit" : "Buat"} Pengumuman</h3>
            <button onClick={() => setEditing(null)} className="text-muted hover:text-white"><X size={16} /></button>
          </div>
          <input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="Judul..."
            className="w-full bg-dark border border-dark-border rounded-lg px-4 py-2 text-sm text-white placeholder:text-muted focus:outline-none focus:border-red-500/50" />
          <textarea value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} placeholder="Isi pengumuman..." rows={3}
            className="w-full bg-dark border border-dark-border rounded-lg px-4 py-2 text-sm text-white placeholder:text-muted focus:outline-none focus:border-red-500/50 resize-none" />
          <div className="flex gap-3">
            <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="bg-dark border border-dark-border rounded-lg px-3 py-2 text-sm text-white">
              <option value="info">Info</option>
              <option value="warning">Warning</option>
              <option value="promo">Promo</option>
              <option value="maintenance">Maintenance</option>
            </select>
            <label className="flex items-center gap-2 text-sm text-muted">
              <input type="checkbox" checked={form.active} onChange={(e) => setForm({ ...form, active: e.target.checked })} className="accent-red-500" />
              Aktif
            </label>
          </div>
          <button onClick={handleSave} className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500 text-white text-xs font-bold hover:bg-red-600 transition-all">
            <Save size={14} /> Simpan
          </button>
        </div>
      )}

      {/* List */}
      <div className="space-y-3">
        {loading ? (
          <div className="text-center py-12 text-muted"><Loader2 className="inline animate-spin mr-2" size={16} />Memuat...</div>
        ) : items.length === 0 ? (
          <div className="text-center py-12 text-muted">Belum ada pengumuman</div>
        ) : items.map((item) => (
          <div key={item.id} className={`bg-dark-surface rounded-xl border p-4 flex items-start justify-between gap-4 ${item.active ? "border-dark-border" : "border-dark-border opacity-50"}`}>
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span className={`text-[10px] font-bold px-2 py-0.5 rounded ${
                  item.type === "warning" ? "bg-yellow-500/10 text-yellow-400" :
                  item.type === "promo" ? "bg-green-500/10 text-green-400" :
                  item.type === "maintenance" ? "bg-red-500/10 text-red-400" :
                  "bg-blue-500/10 text-blue-400"
                }`}>{item.type?.toUpperCase()}</span>
                {!item.active && <span className="text-[10px] text-muted">(Nonaktif)</span>}
              </div>
              <h4 className="text-sm font-bold text-white">{item.title}</h4>
              <p className="text-xs text-muted mt-1">{item.content}</p>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <button onClick={() => { setEditing(item); setForm({ title: item.title, content: item.content, type: item.type || "info", active: item.active }); }}
                className="p-2 rounded bg-white/5 text-muted hover:text-white"><Edit2 size={12} /></button>
              <button onClick={() => handleDelete(item.id)} className="p-2 rounded bg-red-500/10 text-red-400 hover:bg-red-500/20"><Trash2 size={12} /></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
