// app/admin/platforms/page.tsx
"use client";

import { useEffect, useMemo, useState } from "react";
import { Plus, Pencil, Trash2, X } from "lucide-react";
import {
  createPlatform,
  deletePlatform,
  fetchPlatforms,
  updatePlatform,
  type Platform,
  type CreatePlatformDto,
  type UpdatePlatformDto,
} from "@/lib/api/platforms";

export default function AdminPlatformsPage() {

  const [platforms, setPlatforms] = useState<Platform[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState<"create" | "edit">("create");
  const [selected, setSelected] = useState<Platform | null>(null);

  const [form, setForm] = useState<CreatePlatformDto>({
    key: "",
    label: "",
    isActive: true,
  });

  async function load() {
    try {
      setLoading(true);
      setError(null);
      const data = await fetchPlatforms({});
      setPlatforms(data);
    } catch (e: any) {
      console.error(e);
      setError(e?.message ?? "Failed to load platforms");
      setPlatforms([]);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const sorted = useMemo(() => {
    return [...platforms].sort((a, b) => a.key.localeCompare(b.key));
  }, [platforms]);

  function openCreate() {
    setModalMode("create");
    setSelected(null);
    setForm({ key: "", label: "", isActive: true });
    setShowModal(true);
  }

  function openEdit(p: Platform) {
    setModalMode("edit");
    setSelected(p);
    setForm({ key: p.key, label: p.label, isActive: p.isActive });
    setShowModal(true);
  }

  async function onDelete(p: Platform) {
    if (!window.confirm(`Delete platform "${p.key}"? This cannot be undone.`))
      return;

    try {
      setSaving(true);
      setError(null);
      await deletePlatform({}, p.id);
      await load();
    } catch (e: any) {
      console.error(e);
      setError(e?.message ?? "Failed to delete platform");
    } finally {
      setSaving(false);
    }
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();

    const key = (form.key ?? "").trim();
    const label = (form.label ?? "").trim();

    if (!key || !label) {
      setError("Key and Label are required.");
      return;
    }

    try {
      setSaving(true);
      setError(null);

      if (modalMode === "create") {
        await createPlatform({}, { ...form, key, label });
      } else if (selected) {
        const update: UpdatePlatformDto = {};
        if (key !== selected.key) update.key = key;
        if (label !== selected.label) update.label = label;
        if ((form.isActive ?? true) !== selected.isActive)
          update.isActive = form.isActive;

        await updatePlatform({}, selected.id, update);
      }

      setShowModal(false);
      await load();
    } catch (e: any) {
      console.error(e);
      setError(e?.message ?? "Failed to save platform");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="flex flex-1 flex-col gap-4">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-base font-semibold text-zinc-100">Platforms</h1>
          <p className="mt-1 text-xs text-zinc-500">
            Manage canonical platforms used across products and filtering.
          </p>
        </div>

        <button
          type="button"
          onClick={openCreate}
          className="inline-flex items-center gap-2 rounded-md bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
          disabled={loading || saving}
        >
          <Plus size={14} />
          Add Platform
        </button>
      </div>

      {error && (
        <div className="rounded-md border border-red-900/60 bg-red-950/40 px-3 py-2 text-xs text-red-200">
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-sm text-zinc-400">Loading…</div>
      ) : sorted.length === 0 ? (
        <div className="rounded-md border border-zinc-900 bg-zinc-950 px-4 py-6 text-sm text-zinc-400">
          No platforms found.
        </div>
      ) : (
        <div className="overflow-hidden rounded-md border border-zinc-900 bg-zinc-950">
          <table className="min-w-full border-separate border-spacing-0 text-xs">
            <thead className="bg-zinc-950/80">
              <tr className="text-left text-[11px] uppercase tracking-[0.16em] text-zinc-500">
                <th className="border-b border-zinc-900 px-3 py-2">ID</th>
                <th className="border-b border-zinc-900 px-3 py-2">Key</th>
                <th className="border-b border-zinc-900 px-3 py-2">Label</th>
                <th className="border-b border-zinc-900 px-3 py-2">Active</th>
                <th className="border-b border-zinc-900 px-3 py-2 text-right">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {sorted.map((p, idx) => (
                <tr
                  key={p.id}
                  className={idx % 2 === 0 ? "bg-zinc-950" : "bg-zinc-950/60"}
                >
                  <td className="border-b border-zinc-900 px-3 py-2 text-zinc-400">
                    {p.id}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 text-zinc-100">
                    {p.key}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 text-zinc-300">
                    {p.label}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2">
                    <span
                      className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${
                        p.isActive
                          ? "border border-emerald-500/40 bg-emerald-500/10 text-emerald-200"
                          : "border border-zinc-700 bg-zinc-900 text-zinc-400"
                      }`}
                    >
                      {p.isActive ? "ACTIVE" : "INACTIVE"}
                    </span>
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 text-right">
                    <div className="inline-flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => openEdit(p)}
                        className="rounded p-1 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
                        title="Edit"
                        disabled={saving}
                      >
                        <Pencil size={14} />
                      </button>
                      <button
                        type="button"
                        onClick={() => void onDelete(p)}
                        className="rounded p-1 text-zinc-400 hover:bg-red-900/50 hover:text-red-400"
                        title="Delete"
                        disabled={saving}
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
          <div className="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-950 p-6 shadow-xl">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-base font-semibold">
                {modalMode === "create" ? "Create Platform" : "Edit Platform"}
              </h2>
              <button
                type="button"
                onClick={() => setShowModal(false)}
                className="rounded p-1 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={onSubmit} className="space-y-4">
              <div>
                <label className="mb-1 block text-xs font-medium text-zinc-300">
                  Key
                </label>
                <input
                  value={form.key}
                  onChange={(e) =>
                    setForm((s) => ({
                      ...s,
                      key: e.target.value
                        .toUpperCase()
                        .replace(/\s+/g, "") // remove spaces
                        .replace(/-/g, ""),
                    }))
                  }
                  className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400"
                  placeholder="AR15"
                  required
                />
              </div>

              <div>
                <label className="mb-1 block text-xs font-medium text-zinc-300">
                  Label
                </label>
                <input
                  value={form.label}
                  onChange={(e) =>
                    setForm((s) => ({ ...s, label: e.target.value }))
                  }
                  className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400"
                  placeholder="AR-15"
                  required
                />
              </div>

              <label className="flex items-center gap-2 text-xs text-zinc-300">
                <input
                  type="checkbox"
                  checked={!!form.isActive}
                  onChange={(e) =>
                    setForm((s) => ({ ...s, isActive: e.target.checked }))
                  }
                  className="h-4 w-4 rounded border-zinc-700 bg-zinc-900 text-amber-400"
                />
                Active
              </label>

              <div className="flex gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  className="flex-1 rounded-md border border-zinc-700 px-4 py-2 text-xs font-medium text-zinc-300 hover:bg-zinc-800"
                  disabled={saving}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 rounded-md bg-emerald-600 px-4 py-2 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
                  disabled={saving}
                >
                  {saving
                    ? "Saving…"
                    : modalMode === "create"
                    ? "Create"
                    : "Update"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
