import React, { useEffect, useMemo, useState } from "react";
import { bpFetch } from "../api/client";
import { EntityKpiCards, EntitySearchFilters, EntityStateCard } from "../components/EntityIndexControls";

const STATUS_OPTIONS = [
  { value: "all", toolbarLabel: "All statuses", sheetLabel: "All" },
  { value: "active", toolbarLabel: "Active", sheetLabel: "Active" },
  { value: "inactive", toolbarLabel: "Inactive", sheetLabel: "Inactive" },
];

const SORT_OPTIONS = [
  { value: "name", toolbarLabel: "Sort: Name", sheetLabel: "Name" },
  { value: "category", toolbarLabel: "Sort: Category", sheetLabel: "Category" },
  { value: "id", toolbarLabel: "Sort: Newest", sheetLabel: "Newest" },
];

export default function LocationsScreen() {
  const [locations, setLocations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const [search, setSearch] = useState("");
  const [status, setStatus] = useState("all");
  const [sortBy, setSortBy] = useState("name");
  const [filtersOpen, setFiltersOpen] = useState(false);

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

  async function loadLocations() {
    try {
      setError("");
      setLoading(true);
      const resp = await bpFetch("/admin/locations");
      setLocations(resp?.data || []);
    } catch (e) {
      console.error(e);
      setError(e?.message || "Failed to load locations");
    } finally {
      setLoading(false);
    }
  }

  const filtered = useMemo(() => {
    return locations
      .filter((l) => {
        const hay = `${l.name || ""} ${l.address || ""} ${l.category_name || ""}`.toLowerCase();
        return hay.includes(search.toLowerCase());
      })
      .filter((l) => {
        if (status === "all") return true;
        const isActive =
          l.status !== undefined
            ? String(l.status) === "active"
            : l.is_active !== undefined
              ? !!Number(l.is_active)
              : true;
        return status === "active" ? isActive : !isActive;
      })
      .sort((a, b) => {
        if (sortBy === "id") return (Number(b.id) || 0) - (Number(a.id) || 0);
        if (sortBy === "category") {
          const ac = (a.category_name || "").toLowerCase();
          const bc = (b.category_name || "").toLowerCase();
          return ac.localeCompare(bc);
        }
        const an = (a.name || "").toLowerCase();
        const bn = (b.name || "").toLowerCase();
        return an.localeCompare(bn);
      });
  }, [locations, search, status, sortBy]);

  const stats = useMemo(() => {
    return locations.reduce(
      (acc, l) => {
        const isActive =
          l.status !== undefined
            ? String(l.status) === "active"
            : l.is_active !== undefined
              ? !!Number(l.is_active)
              : true;
        acc.total += 1;
        if (isActive) acc.active += 1;
        else acc.inactive += 1;
        return acc;
      },
      { total: 0, active: 0, inactive: 0 }
    );
  }, [locations]);

  return (
    <div className="myplugin-page bp-locations">
      <main className="myplugin-content bp-entity-index">
        <div className="bp-page-head">
          <div>
            <div className="bp-h1">Locations</div>
            <div className="bp-muted">Manage locations, images, and assignments.</div>
          </div>
          <div className="bp-head-actions">
            <a className="bp-primary-btn" href="admin.php?page=pointlybooking_locations_edit">
              + New Location
            </a>
            <a className="bp-top-btn" href="admin.php?page=pointlybooking_location_categories_edit">
              Categories
            </a>
          </div>
        </div>

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

        <EntityKpiCards
          items={[
            { label: "Total", value: loading ? "..." : stats.total },
            { label: "Active", value: loading ? "..." : stats.active },
            { label: "Inactive", value: loading ? "..." : stats.inactive },
          ]}
        />

        <EntitySearchFilters
          desktopClassName="bp-locations__filters-inline"
          mobileClassName="bp-locations__toolbar"
          searchPlaceholder="Search locations..."
          searchValue={search}
          onSearchChange={setSearch}
          statusValue={status}
          onStatusChange={setStatus}
          statusOptions={STATUS_OPTIONS}
          sortValue={sortBy}
          onSortChange={setSortBy}
          sortOptions={SORT_OPTIONS}
          filtersOpen={filtersOpen}
          setFiltersOpen={setFiltersOpen}
          shownCount={filtered.length}
          loading={loading}
          onClear={() => {
            setSearch("");
            setStatus("all");
            setSortBy("name");
          }}
        />

        {loading ? (
          <EntityStateCard>Loading...</EntityStateCard>
        ) : filtered.length === 0 ? (
          <EntityStateCard>No locations found.</EntityStateCard>
        ) : (
          <div className="bp-entity-grid bp-locations__grid">
            {filtered.map((l) => {
              const name = l.name || `#${l.id}`;
              const address = (l.address || "").trim();
              const category = (l.category_name || "").trim();
              const imageUrl = l.image_url || l.image || "";
              const initial = (name || "L").trim().charAt(0).toUpperCase();
              const isActive =
                l.status !== undefined ? String(l.status) === "active" : l.is_active !== undefined ? !!Number(l.is_active) : true;
              const editHref = `admin.php?page=pointlybooking_locations_edit&id=${l.id}`;

              return (
                <a key={l.id} className="bp-entity-card bp-entity-card--link" href={editHref}>
                  <div className="bp-entity-head">
                    <div className="bp-entity-thumb">
                      {imageUrl ? <img src={imageUrl} alt={name} /> : <div className="bp-entity-initial">{initial}</div>}
                    </div>
                    <div className="bp-entity-main">
                      <div className="bp-entity-title">{name}</div>
                      <div className="bp-entity-sub">{address || category || "Location"}</div>
                    </div>
                    <span className={`bp-status-pill ${isActive ? "active" : "inactive"}`}>
                      {isActive ? "Active" : "Inactive"}
                    </span>
                  </div>
                  <div className="bp-entity-meta">
                    <div>
                      <div className="bp-entity-meta-label">Category</div>
                      <div className="bp-entity-meta-value">{category || "-"}</div>
                    </div>
                    <div>
                      <div className="bp-entity-meta-label">ID</div>
                      <div className="bp-entity-meta-value">#{l.id}</div>
                    </div>
                  </div>
                  <div className="bp-entity-actions">
                    <span className="bp-btn-sm">Edit</span>
                  </div>
                </a>
              );
            })}
          </div>
        )}
      </main>
    </div>
  );
}
