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: "price", toolbarLabel: "Sort: Price", sheetLabel: "Price" },
  { value: "sort", toolbarLabel: "Sort: Order", sheetLabel: "Order" },
];

export default function ExtrasScreen() {
  const [extras, setExtras] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const defaultCurrency = (window.pointlybooking_ADMIN?.currency || "USD").toUpperCase();

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

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

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

  const filtered = useMemo(() => {
    return extras
      .filter((x) => {
        const hay = `${x.name || ""} ${x.title || ""} ${x.description || ""} ${x.type || ""}`.toLowerCase();
        return hay.includes(search.toLowerCase());
      })
      .filter((x) => {
        if (status === "all") return true;
        const isActive =
          x.is_active !== undefined ? !!Number(x.is_active) : x.is_enabled !== undefined ? !!Number(x.is_enabled) : true;
        return status === "active" ? isActive : !isActive;
      })
      .sort((a, b) => {
        if (sortBy === "price") {
          const ap = a.price_cents ?? (a.price !== undefined && a.price !== null ? Math.round(parseFloat(a.price) * 100) : 0);
          const bp = b.price_cents ?? (b.price !== undefined && b.price !== null ? Math.round(parseFloat(b.price) * 100) : 0);
          return ap - bp;
        }
        if (sortBy === "sort") {
          const as = Number(a.sort_order || 0) || 0;
          const bs = Number(b.sort_order || 0) || 0;
          return as - bs;
        }
        const an = (a.name || "").toLowerCase();
        const bn = (b.name || "").toLowerCase();
        return an.localeCompare(bn);
      });
  }, [extras, search, status, sortBy]);

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

  return (
    <div className="myplugin-page bp-extras">
      <main className="myplugin-content bp-entity-index">
        <div className="bp-page-head">
          <div>
            <div className="bp-h1">Service Extras</div>
            <div className="bp-muted">Upsell add-ons and extras for services.</div>
          </div>
          <div className="bp-head-actions">
            <a className="bp-primary-btn" href="admin.php?page=pointlybooking_extras_edit">
              + New Extra
            </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-extras__filters-inline"
          mobileClassName="bp-extras__toolbar"
          searchPlaceholder="Search extras..."
          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 extras found.</EntityStateCard>
        ) : (
          <div className="bp-entity-grid bp-extras__grid">
            {filtered.map((x) => {
              const name = x.name || x.title || `#${x.id}`;
              const description = (x.description || "").trim();
              const isActive =
                x.is_active !== undefined ? !!Number(x.is_active) : x.is_enabled !== undefined ? !!Number(x.is_enabled) : true;
              const imageUrl = x.image_url || x.image || "";
              const initial = (name || "E").trim().charAt(0).toUpperCase();
              const priceCents =
                x.price_cents ??
                (x.price !== undefined && x.price !== null ? Math.round(parseFloat(x.price) * 100) : null);
              const currency = (x.currency || defaultCurrency || "USD").toUpperCase();
              const priceDisplay = priceCents !== null ? `${currency} ${(priceCents / 100).toFixed(2)}` : "???";
              const typeDisplay = x.type || (x.duration_min ? `Duration ${x.duration_min} min` : "");
              const editHref = `admin.php?page=pointlybooking_extras_edit&id=${x.id}`;

              return (
                <a key={x.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">{description || typeDisplay || "Extra"}</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">Price</div>
                      <div className="bp-entity-meta-value">{priceDisplay}</div>
                    </div>
                    {typeDisplay ? (
                      <div>
                        <div className="bp-entity-meta-label">Type</div>
                        <div className="bp-entity-meta-value">{typeDisplay}</div>
                      </div>
                    ) : null}
                  </div>
                  <div className="bp-entity-actions">
                    <span className="bp-btn-sm">Edit</span>
                  </div>
                </a>
              );
            })}
          </div>
        )}
      </main>
    </div>
  );
}
