"use client";

import { useEffect, useState, FormEvent } from "react";
import styles from "../admin.module.css";

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

function slugify(str: string) {
  return str.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
}

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ name: "", slug: "", icon: "", order: 0 });
  const [newForm, setNewForm] = useState({ name: "", slug: "", icon: "", order: 0 });
  const [success, setSuccess] = useState("");
  const [error, setError] = useState("");

  const fetchCategories = async () => {
    setLoading(true);
    const res = await fetch("/api/admin/categories");
    setCategories(await res.json());
    setLoading(false);
  };

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

  const handleCreate = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/admin/categories", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...newForm, order: Number(newForm.order) }),
      });
      if (!res.ok) throw new Error();
      setNewForm({ name: "", slug: "", icon: "", order: 0 });
      setSuccess("Category created!");
      await fetchCategories();
    } catch { setError("Failed to create category."); }
    setSaving(false);
    setTimeout(() => setSuccess(""), 3000);
  };

  const handleUpdate = async (id: string) => {
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/admin/categories/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...editForm, order: Number(editForm.order) }),
      });
      if (!res.ok) throw new Error();
      setEditingId(null);
      setSuccess("Category updated!");
      await fetchCategories();
    } catch { setError("Failed to update category."); }
    setSaving(false);
    setTimeout(() => setSuccess(""), 3000);
  };

  const handleDelete = async (id: string, name: string) => {
    if (!window.confirm(`Delete category "${name}"? Apps in this category will be uncategorized.`)) return;
    setDeleting(id);
    try {
      await fetch(`/api/admin/categories/${id}`, { method: "DELETE" });
      await fetchCategories();
    } catch { setError("Failed to delete category."); }
    setDeleting(null);
  };

  const startEdit = (cat: Category) => {
    setEditingId(cat.id);
    setEditForm({ name: cat.name, slug: cat.slug, icon: cat.icon ?? "", order: cat.order });
  };

  return (
    <>
      <div className={styles.topBar}>
        <div className={styles.topBarLeft}>
          <span className={styles.pageTitle}>Categories</span>
          <span className={styles.pageBreadcrumb}> · Organize apps into groups</span>
        </div>
      </div>

      <div className={styles.pageBody}>
        {success && <div className={styles.alertSuccess}>✅ {success}</div>}
        {error && <div className={styles.alertError}>❌ {error}</div>}

        {/* Existing Categories */}
        <div className={styles.sectionHeader}>
          <h2 className={styles.sectionTitle}>Existing Categories</h2>
        </div>

        <div className={styles.tableCard} style={{ marginBottom: 24 }}>
          {loading ? (
            <div style={{ padding: "36px", textAlign: "center", color: "#475569" }}>Loading...</div>
          ) : categories.length === 0 ? (
            <div className={styles.emptyState}><h3>No categories yet</h3><p>Create one below.</p></div>
          ) : (
            <table className={styles.table}>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Slug</th>
                  <th>Icon Key</th>
                  <th>Order</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {categories.map((cat) => (
                  editingId === cat.id ? (
                    <tr key={cat.id}>
                      <td><input className={styles.filterInput} style={{ width: "100%" }} value={editForm.name} onChange={(e) => setEditForm(f => ({ ...f, name: e.target.value, slug: slugify(e.target.value) }))} /></td>
                      <td><input className={styles.filterInput} style={{ width: "100%" }} value={editForm.slug} onChange={(e) => setEditForm(f => ({ ...f, slug: e.target.value }))} /></td>
                      <td><input className={styles.filterInput} style={{ width: "100%" }} value={editForm.icon} onChange={(e) => setEditForm(f => ({ ...f, icon: e.target.value }))} /></td>
                      <td><input type="number" className={styles.filterInput} style={{ width: 80 }} value={editForm.order} onChange={(e) => setEditForm(f => ({ ...f, order: +e.target.value }))} /></td>
                      <td>
                        <div className={styles.tableActions}>
                          <button className={styles.btnPrimary} style={{ padding: "6px 12px" }} onClick={() => handleUpdate(cat.id)} disabled={saving}>Save</button>
                          <button className={styles.btnSecondary} style={{ padding: "6px 12px" }} onClick={() => setEditingId(null)}>Cancel</button>
                        </div>
                      </td>
                    </tr>
                  ) : (
                    <tr key={cat.id}>
                      <td style={{ fontWeight: 500, color: "#e2e8f0" }}>{cat.name}</td>
                      <td style={{ color: "#94a3b8" }}>{cat.slug}</td>
                      <td style={{ color: "#64748b" }}>{cat.icon ?? "—"}</td>
                      <td style={{ color: "#64748b" }}>{cat.order}</td>
                      <td>
                        <div className={styles.tableActions}>
                          <button className={styles.btnEdit} onClick={() => startEdit(cat)}>Edit</button>
                          <button className={styles.btnDanger} onClick={() => handleDelete(cat.id, cat.name)} disabled={deleting === cat.id}>
                            {deleting === cat.id ? "..." : "Delete"}
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* Create New Category */}
        <div className={styles.sectionHeader}>
          <h2 className={styles.sectionTitle}>Add New Category</h2>
        </div>
        <div className={styles.formCard}>
          <form onSubmit={handleCreate}>
            <div className={styles.formGrid}>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Category Name *</label>
                <input
                  required
                  className={styles.formInput}
                  value={newForm.name}
                  onChange={(e) => setNewForm(f => ({ ...f, name: e.target.value, slug: slugify(e.target.value) }))}
                  placeholder="Developer Tools"
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Slug *</label>
                <input
                  required
                  className={styles.formInput}
                  value={newForm.slug}
                  onChange={(e) => setNewForm(f => ({ ...f, slug: e.target.value }))}
                  placeholder="developer-tools"
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Icon Key</label>
                <input
                  className={styles.formInput}
                  value={newForm.icon}
                  onChange={(e) => setNewForm(f => ({ ...f, icon: e.target.value }))}
                  placeholder="code"
                />
              </div>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Sort Order</label>
                <input
                  type="number"
                  className={styles.formInput}
                  value={newForm.order}
                  onChange={(e) => setNewForm(f => ({ ...f, order: +e.target.value }))}
                />
              </div>
            </div>
            <div className={styles.formActions}>
              <button type="submit" disabled={saving} className={styles.btnPrimary}>
                {saving ? "Creating..." : "➕ Create Category"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}
