"use client";

import { useEffect, useState } from "react";
import { formatMoney } from "@/lib/format";

type Service = {
  id: string;
  name: string;
  description: string;
  durationMinutes: number;
  priceCents: number;
  active: boolean;
};

const emptyForm = { name: "", description: "", durationMinutes: 60, priceCents: 0 };

export default function AdminServicesPage() {
  const [services, setServices] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState(emptyForm);
  const [submitting, setSubmitting] = useState(false);

  async function refresh() {
    const data = await fetch("/api/admin/services").then((r) => r.json());
    setServices(data.services ?? []);
    setLoading(false);
  }

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

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    await fetch("/api/admin/services", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    setForm(emptyForm);
    setSubmitting(false);
    refresh();
  }

  async function toggleActive(service: Service) {
    await fetch(`/api/admin/services/${service.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ active: !service.active }),
    });
    refresh();
  }

  async function handleDelete(id: string) {
    if (!confirm("Delete this service? This cannot be undone.")) return;
    await fetch(`/api/admin/services/${id}`, { method: "DELETE" });
    refresh();
  }

  return (
    <div>
      <h1 className="font-display text-3xl text-rosewood">Services</h1>

      <div className="mt-8 overflow-x-auto rounded-2xl border border-blush-dark/50 bg-white">
        <table className="w-full text-left text-sm">
          <thead className="bg-blush/60 text-xs uppercase tracking-wide-plus text-rose-dark">
            <tr>
              <th className="px-4 py-3">Name</th>
              <th className="px-4 py-3">Duration</th>
              <th className="px-4 py-3">Price</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3"></th>
            </tr>
          </thead>
          <tbody>
            {services.map((service) => (
              <tr key={service.id} className="border-t border-blush-dark/30">
                <td className="px-4 py-3">
                  <p className="font-medium">{service.name}</p>
                  <p className="text-xs text-ink/50">{service.description}</p>
                </td>
                <td className="px-4 py-3">{service.durationMinutes} min</td>
                <td className="px-4 py-3">{formatMoney(service.priceCents)}</td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => toggleActive(service)}
                    className={`rounded-full px-3 py-1 text-xs ${
                      service.active ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-600"
                    }`}
                  >
                    {service.active ? "Active" : "Hidden"}
                  </button>
                </td>
                <td className="px-4 py-3">
                  <button
                    onClick={() => handleDelete(service.id)}
                    className="text-xs text-red-600 hover:underline"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
            {!loading && services.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-10 text-center text-ink/50">
                  No services yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="mt-10 max-w-lg rounded-2xl border border-blush-dark/50 bg-white p-6">
        <h2 className="font-display text-xl text-rosewood">Add a Service</h2>
        <form onSubmit={handleCreate} className="mt-4 space-y-3">
          <input
            required
            placeholder="Name"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2 text-sm"
          />
          <textarea
            required
            placeholder="Description"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
            rows={2}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2 text-sm"
          />
          <div className="flex gap-3">
            <input
              required
              type="number"
              min={5}
              placeholder="Duration (min)"
              value={form.durationMinutes}
              onChange={(e) => setForm({ ...form, durationMinutes: Number(e.target.value) })}
              className="w-full rounded-lg border border-blush-dark/60 px-4 py-2 text-sm"
            />
            <input
              required
              type="number"
              min={0}
              placeholder="Price (cents)"
              value={form.priceCents}
              onChange={(e) => setForm({ ...form, priceCents: Number(e.target.value) })}
              className="w-full rounded-lg border border-blush-dark/60 px-4 py-2 text-sm"
            />
          </div>
          <button
            type="submit"
            disabled={submitting}
            className="rounded-full bg-rosewood px-6 py-2.5 text-xs uppercase tracking-wide-plus text-cream transition hover:bg-rose-dark disabled:opacity-50"
          >
            {submitting ? "Adding…" : "Add Service"}
          </button>
        </form>
      </div>
    </div>
  );
}
