import React, { useEffect, useState } from "react";
import { bpFetch } from "../api/client";
import { pickImage } from "../ui/wpMedia";
import { queueAdminToast } from "../utils/adminToast";

function getQueryInt(key) {
  const params = new URLSearchParams(window.location.search);
  const raw = params.get(key);
  const parsed = raw ? parseInt(raw, 10) : 0;
  return Number.isFinite(parsed) ? parsed : 0;
}

export default function LocationCategoryEditScreen() {
  const categoryId = getQueryInt("id");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [edit, setEdit] = useState(null);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    setError("");
    setNotice("");

    (async () => {
      try {
        if (categoryId > 0) {
          const res = await bpFetch("/admin/location-categories");
          const rows = res?.data || [];
          const row = rows.find((r) => Number(r.id) === categoryId) || null;
          if (!alive) return;
          if (!row) {
            setError("Category not found.");
            setEdit(null);
          } else {
            setEdit(row);
          }
        } else if (alive) {
          setEdit({ name: "", image_id: 0, image_url: "" });
        }
      } catch (e) {
        if (alive) setError(e.message || "Failed to load category");
      } finally {
        if (alive) setLoading(false);
      }
    })();

    return () => {
      alive = false;
    };
  }, [categoryId]);

  useEffect(() => {
    if (!notice) return undefined;
    const timeout = window.setTimeout(() => setNotice(""), 2600);
    return () => window.clearTimeout(timeout);
  }, [notice]);

  async function pickCategoryImage() {
    try {
      const img = await pickImage({ title: "Select category image" });
      setEdit((prev) => ({ ...prev, image_id: img.id, image_url: img.url }));
    } catch (e) {
      setError(e.message || "Image picker failed");
    }
  }

  async function saveCategory() {
    if (!edit?.name) return;
    setSaving(true);
    setError("");
    setNotice("");
    try {
      if (categoryId > 0) {
        await bpFetch(`/admin/location-categories/${categoryId}`, {
          method: "PUT",
          body: { name: edit.name, image_id: edit.image_id || 0 },
        });
        setNotice("Saved changes.");
      } else {
        await bpFetch("/admin/location-categories", {
          method: "POST",
          body: { name: edit.name, image_id: edit.image_id || 0 },
        });
        try {
          const list = await bpFetch("/admin/location-categories");
          const rows = list?.data || [];
          const latest = rows.sort((a, b) => (b.id || 0) - (a.id || 0))[0];
          if (latest?.id) {
            queueAdminToast("Saved changes.");
            window.location.href = `admin.php?page=pointlybooking_location_categories_edit&id=${latest.id}`;
            return;
          }
        } catch (_) {
          // ignore and fall back to locations screen
        }
        queueAdminToast("Saved changes.");
        window.location.href = "admin.php?page=pointlybooking_locations";
        return;
      }
    } catch (e) {
      setError(e.message || "Category save failed");
    } finally {
      setSaving(false);
    }
  }

  async function deleteCategory() {
    if (!categoryId) return;
    if (!confirm("Delete this category?")) return;
    setSaving(true);
    setError("");
    try {
      await bpFetch(`/admin/location-categories/${categoryId}`, { method: "DELETE" });
      window.location.href = "admin.php?page=pointlybooking_locations";
    } catch (e) {
      setError(e.message || "Delete failed");
      setSaving(false);
    }
  }

  return (
    <div className="myplugin-page bp-category-edit bp-location-category-edit">
      <main className="myplugin-content">
        {notice ? <div className="bp-toast bp-toast-success">{notice}</div> : null}

        <div className="bp-category-edit__head">
          <div>
            <div className="bp-muted bp-text-sm" style={{ fontWeight: 900 }}>
              Locations / Categories
            </div>
            <div className="bp-h1">{categoryId ? "Edit Category" : "Add Category"}</div>
            <div className="bp-muted">Manage category profile and photo.</div>
          </div>
          <div className="bp-head-actions">
            <a className="bp-top-btn" href="admin.php?page=pointlybooking_locations">Back to Locations</a>
          </div>
        </div>

        {error ? <div className="bp-error">{error}</div> : null}

        {loading ? (
          <div className="bp-state-card">Loading category details...</div>
        ) : !edit ? (
          <div className="bp-state-card">Category not found.</div>
        ) : (
          <div className="bp-category-edit__grid">
            <section className="bp-category-edit__main">
              <div className="bp-card bp-category-edit__section">
                <div className="bp-section-title">Category details</div>
                <div>
                  <label className="bp-filter-label">Category name *</label>
                  <input
                    className="bp-input"
                    value={edit.name || ""}
                    onChange={(e) => setEdit((prev) => ({ ...prev, name: e.target.value }))}
                    placeholder="e.g., Interior"
                  />
                  <div className="bp-muted bp-text-sm" style={{ marginTop: 8 }}>
                    This label is used when grouping locations in the booking flow.
                  </div>
                </div>
              </div>
            </section>

            <aside className="bp-category-edit__side">
              <div className="bp-card bp-category-edit__sidecard">
                <div className="bp-section-title">Image</div>
                <div className="bp-category-edit__avatar">
                  {edit.image_url ? <img src={edit.image_url} alt={edit.name || "Category"} /> : <div className="bp-media-empty">No image</div>}
                </div>
                <div className="bp-category-edit__side-actions">
                  <button type="button" className="bp-top-btn" onClick={pickCategoryImage}>
                    Choose Image
                  </button>
                  <button
                    type="button"
                    className="bp-btn bp-btn-ghost"
                    onClick={() => setEdit((prev) => ({ ...prev, image_id: 0, image_url: "" }))}
                    disabled={!edit.image_id && !edit.image_url}
                  >
                    Remove
                  </button>
                </div>
                <div className="bp-muted bp-text-sm" style={{ marginTop: 10 }}>
                  Uses the WordPress Media Library and stores the attachment ID.
                </div>
              </div>

              {categoryId ? (
                <div className="bp-card bp-category-edit__sidecard">
                  <div className="bp-section-title">Danger zone</div>
                  <div className="bp-muted bp-text-sm" style={{ marginTop: 6 }}>
                    Deleting this category removes it from location assignments.
                  </div>
                  <div className="bp-category-edit__danger">
                    <button type="button" className="bp-category-edit__dangerbtn" onClick={deleteCategory} disabled={saving}>
                      Delete category
                    </button>
                  </div>
                </div>
              ) : null}
            </aside>
          </div>
        )}

        {!loading && edit ? (
          <div className="bp-category-edit__bar">
            <a className="bp-btn bp-btn-ghost" href="admin.php?page=pointlybooking_locations">
              Cancel
            </a>
            <button className="bp-btn bp-btn-primary" type="button" onClick={saveCategory} disabled={saving || !edit.name}>
              {saving ? "Saving..." : categoryId ? "Save changes" : "Create category"}
            </button>
          </div>
        ) : null}
      </main>
    </div>
  );
}
