"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { slugify } from "@/lib/utils";
import { Plus, Pencil, Trash2, X } from "lucide-react";

interface OrganizerForm {
  name: string;
  slug: string;
}

export default function OrganizersPage() {
  const [organizers, setOrganizers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<OrganizerForm>({ name: "", slug: "" });
  const [saving, setSaving] = useState(false);

  const loadOrganizers = async () => {
    try {
      const data = await api.getOrganizers();
      setOrganizers(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  const openCreate = () => {
    setForm({ name: "", slug: "" });
    setEditingId(null);
    setShowForm(true);
  };

  const openEdit = (org: any) => {
    setForm({ name: org.name, slug: org.slug });
    setEditingId(org.id);
    setShowForm(true);
  };

  const handleNameChange = (name: string) => {
    setForm({ name, slug: editingId ? form.slug : slugify(name) });
  };

  const handleSave = async () => {
    if (!form.name.trim() || !form.slug.trim()) return;
    setSaving(true);
    setError("");
    try {
      if (editingId) {
        await api.updateOrganizer(editingId, form);
      } else {
        await api.createOrganizer(form);
      }
      setShowForm(false);
      setEditingId(null);
      await loadOrganizers();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this organizer?")) return;
    try {
      await api.deleteOrganizer(id);
      await loadOrganizers();
    } catch (err: any) {
      setError(err.message);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading organizers...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-on-surface">Organizers</h1>
        <button
          onClick={openCreate}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity"
        >
          <Plus size={16} />
          Add Organizer
        </button>
      </div>

      <p className="text-on-surface/60 text-sm max-w-2xl">
        Organizers appear on public event cards and detail pages. The default is Belgian Bitcoin Embassy;
        add other Belgian meetup groups so their events can be listed on this site.
      </p>

      {error && <p className="text-error text-sm">{error}</p>}

      {showForm && (
        <div className="bg-surface-container-low rounded-xl p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-on-surface">
              {editingId ? "Edit Organizer" : "New Organizer"}
            </h2>
            <button onClick={() => setShowForm(false)} className="text-on-surface/50 hover:text-on-surface">
              <X size={20} />
            </button>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <input
              placeholder="Display name"
              value={form.name}
              onChange={(e) => handleNameChange(e.target.value)}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40"
            />
            <input
              placeholder="URL slug (e.g. antwerp-bitcoin)"
              value={form.slug}
              onChange={(e) => setForm({ ...form, slug: e.target.value })}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40"
            />
          </div>
          <div className="flex gap-3 mt-4">
            <button
              onClick={handleSave}
              disabled={saving || !form.name.trim()}
              className="px-6 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save"}
            </button>
            <button
              onClick={() => setShowForm(false)}
              className="px-6 py-2 rounded-lg bg-surface-container-highest text-on-surface font-semibold text-sm hover:bg-surface-container-high transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="space-y-3">
        {organizers.length === 0 ? (
          <p className="text-on-surface/50 text-sm">No organizers found.</p>
        ) : (
          organizers.map((org) => (
            <div
              key={org.id}
              className="bg-surface-container-low rounded-xl p-6 flex items-center justify-between"
            >
              <div>
                <h3 className="text-on-surface font-semibold">{org.name}</h3>
                <p className="text-on-surface/50 text-sm">/events/organizer/{org.slug}</p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => openEdit(org)}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/60 hover:text-on-surface transition-colors"
                >
                  <Pencil size={16} />
                </button>
                <button
                  onClick={() => handleDelete(org.id)}
                  className="p-2 rounded-lg hover:bg-error-container/30 text-on-surface/60 hover:text-error transition-colors"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
