"use client";

import { useState, useEffect } from "react";
import { Plus, Pencil, Trash2, Loader2, Save, X } from "lucide-react";

interface UsesItem {
  id: string; title: string; description: string;
  category: string; url: string; sortOrder: number;
}

const CATEGORIES = [
  { value: "development", label: "توسعه" },
  { value: "design", label: "طراحی" },
  { value: "marketing", label: "بازاریابی" },
  { value: "productivity", label: "بهره‌وری" },
  { value: "hardware", label: "سخت‌افزار" },
];

const empty: Omit<UsesItem, "id"> = { title: "", description: "", category: "development", url: "", sortOrder: 0 };

export default function AdminUsesPage() {
  const [items, setItems] = useState<UsesItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [showNew, setShowNew] = useState(false);
  const [form, setForm] = useState<Omit<UsesItem, "id">>(empty);
  const [saving, setSaving] = useState(false);

  async function load() {
    const res = await fetch("/api/admin/uses");
    setItems(await res.json());
    setLoading(false);
  }
  useEffect(() => { load(); }, []);

  async function handleSave() {
    setSaving(true);
    if (editingId) {
      await fetch(`/api/admin/uses/${editingId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
    } else {
      await fetch("/api/admin/uses", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
    }
    setSaving(false);
    setEditingId(null);
    setShowNew(false);
    setForm(empty);
    await load();
  }

  const grouped = CATEGORIES.reduce<Record<string, UsesItem[]>>((acc, cat) => {
    const catItems = items.filter((i) => i.category === cat.value);
    if (catItems.length > 0) acc[cat.value] = catItems;
    return acc;
  }, {});

  const showForm = showNew || editingId !== null;

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold text-text-primary">ابزارها و Uses</h1>
        <button onClick={() => { setShowNew(true); setEditingId(null); setForm(empty); }} className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover transition-colors">
          <Plus size={16} /> ابزار جدید
        </button>
      </div>

      {showForm && (
        <div className="mb-6 rounded-xl border border-accent/20 bg-surface p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="font-semibold text-text-primary">{editingId ? "ویرایش ابزار" : "ابزار جدید"}</h2>
            <button onClick={() => { setShowNew(false); setEditingId(null); }}><X size={16} className="text-text-secondary hover:text-text-primary" /></button>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">نام ابزار</label>
              <input type="text" value={form.title} onChange={(e) => setForm((p) => ({ ...p, title: e.target.value }))} className="admin-input w-full" />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">دسته‌بندی</label>
              <select value={form.category} onChange={(e) => setForm((p) => ({ ...p, category: e.target.value }))} className="admin-input w-full">
                {CATEGORIES.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
              </select>
            </div>
            <div className="sm:col-span-2">
              <label className="block text-sm font-medium text-text-primary mb-1.5">توضیحات</label>
              <input type="text" value={form.description} onChange={(e) => setForm((p) => ({ ...p, description: e.target.value }))} className="admin-input w-full" />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">لینک (اختیاری)</label>
              <input type="url" value={form.url} onChange={(e) => setForm((p) => ({ ...p, url: e.target.value }))} dir="ltr" className="admin-input w-full" placeholder="https://..." />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">ترتیب</label>
              <input type="number" value={form.sortOrder} onChange={(e) => setForm((p) => ({ ...p, sortOrder: parseInt(e.target.value) || 0 }))} className="admin-input w-full" />
            </div>
          </div>
          <button onClick={handleSave} disabled={saving || !form.title} className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover disabled:opacity-60 transition-colors">
            {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} ذخیره
          </button>
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-20"><Loader2 className="animate-spin text-text-secondary" /></div>
      ) : (
        <div className="space-y-8">
          {CATEGORIES.map((cat) => {
            const catItems = grouped[cat.value];
            if (!catItems) return null;
            return (
              <div key={cat.value}>
                <h2 className="mb-3 flex items-center gap-3">
                  <span className="font-mono text-xs text-accent">// {cat.label}</span>
                  <span className="h-px flex-1 bg-border" />
                </h2>
                <div className="grid gap-3 sm:grid-cols-2">
                  {catItems.map((item) => (
                    <div key={item.id} className="flex items-start justify-between gap-3 rounded-lg border border-border bg-surface p-4">
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-text-primary">{item.title}</div>
                        {item.description && <p className="mt-0.5 text-sm text-text-secondary">{item.description}</p>}
                        {item.url && <a href={item.url} target="_blank" rel="noopener noreferrer" className="mt-1 block font-mono text-xs text-accent truncate hover:underline">{item.url}</a>}
                      </div>
                      <div className="flex items-center gap-1 shrink-0">
                        <button onClick={() => { setForm({ title: item.title, description: item.description ?? "", category: item.category, url: item.url ?? "", sortOrder: item.sortOrder }); setEditingId(item.id); setShowNew(false); }} className="flex h-7 w-7 items-center justify-center rounded border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors"><Pencil size={12} /></button>
                        <button onClick={async () => { if (!confirm("حذف؟")) return; await fetch(`/api/admin/uses/${item.id}`, { method: "DELETE" }); load(); }} className="flex h-7 w-7 items-center justify-center rounded border border-border text-text-secondary hover:border-danger/40 hover:text-danger transition-colors"><Trash2 size={12} /></button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
          {Object.keys(grouped).length === 0 && (
            <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
              <p className="text-text-secondary">هنوز ابزاری ندارید</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
