"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { API } from "@/app/_lib/api";
import { useActiveOrganization, useActiveBranch, posAPI } from "./_lib/posApi";

interface OrgOption { id: number; name: string; }
interface BranchOption { id: number; name: string; code: string; }

const NAV_ITEMS = [
  { href: "/dashboard", label: "Dashboard", icon: "fa-gauge-high" },
  { href: "/terminal", label: "Terminal", icon: "fa-cash-register" },
  { href: "/products", label: "Products", icon: "fa-boxes-stacked" },
  { href: "/inventory", label: "Inventory", icon: "fa-warehouse" },
  { href: "/customers", label: "Customers", icon: "fa-users" },
  { href: "/sales", label: "Sales", icon: "fa-receipt" },
  { href: "/branches", label: "Branches", icon: "fa-store" },
];

export default function PosLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const { orgId, selectOrganization } = useActiveOrganization();
  const { branchId, selectBranch } = useActiveBranch();
  const [orgs, setOrgs] = useState<OrgOption[]>([]);
  const [branches, setBranches] = useState<BranchOption[]>([]);

  useEffect(() => {
    API.get("developers/api/organization-settings/?limit=100")
      .then(({ data }) => {
        setOrgs(data);
        if (!orgId && data.length > 0) selectOrganization(data[0].id);
      })
      .catch(() => {});
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!orgId) return;
    posAPI
      .get("pos/api/branches/")
      .then(({ data }) => {
        setBranches(data);
        if (!branchId && data.length > 0) selectBranch(data[0].id);
      })
      .catch(() => setBranches([]));
  }, [orgId]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div>
      <div className="card mb-4">
        <div className="card-body py-3">
          <div className="row g-3 align-items-center">
            <div className="col-auto">
              <span className="fw-bold">
                <span className="fa-solid fa-shop me-2 text-primary" />
                Retail POS
              </span>
            </div>
            <div className="col-auto">
              <select
                className="form-select form-select-sm"
                style={{ minWidth: 200 }}
                value={orgId ?? ""}
                onChange={(e) => selectOrganization(e.target.value)}
              >
                <option value="" disabled>Select organization</option>
                {orgs.map((o) => (
                  <option key={o.id} value={o.id}>{o.name}</option>
                ))}
              </select>
            </div>
            <div className="col-auto">
              <select
                className="form-select form-select-sm"
                style={{ minWidth: 180 }}
                value={branchId ?? ""}
                onChange={(e) => selectBranch(e.target.value)}
              >
                <option value="" disabled>Select branch</option>
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>{b.name} ({b.code})</option>
                ))}
              </select>
            </div>
            <div className="col-auto ms-auto">
              <SyncStatusBadge />
            </div>
          </div>
        </div>
        <div className="card-footer bg-body-tertiary py-0 border-top">
          <ul className="nav nav-underline">
            {NAV_ITEMS.map((item) => {
              const active = pathname?.includes(item.href);
              return (
                <li className="nav-item" key={item.href}>
                  <Link
                    href={item.href}
                    className={`nav-link py-3 ${active ? "active fw-semibold" : "text-body-secondary"}`}
                  >
                    <span className={`fa-solid ${item.icon} me-2`} />
                    {item.label}
                  </Link>
                </li>
              );
            })}
          </ul>
        </div>
      </div>
      {children}
    </div>
  );
}

/** Small indicator showing whether we're online and, if offline, how many sales are queued locally. */
function SyncStatusBadge() {
  const [isOnline, setIsOnline] = useState(true);
  const [queued, setQueued] = useState(0);

  useEffect(() => {
    setIsOnline(navigator.onLine);
    const goOnline = () => setIsOnline(true);
    const goOffline = () => setIsOnline(false);
    window.addEventListener("online", goOnline);
    window.addEventListener("offline", goOffline);

    const readQueue = () => {
      try {
        const raw = window.localStorage.getItem("pos_offline_sale_queue");
        const arr = raw ? JSON.parse(raw) : [];
        setQueued(Array.isArray(arr) ? arr.length : 0);
      } catch {
        setQueued(0);
      }
    };
    readQueue();
    const interval = setInterval(readQueue, 3000);
    return () => {
      window.removeEventListener("online", goOnline);
      window.removeEventListener("offline", goOffline);
      clearInterval(interval);
    };
  }, []);

  if (isOnline && queued === 0) {
    return <span className="badge badge-phoenix badge-phoenix-success"><span className="fa-solid fa-wifi me-1" />Online</span>;
  }
  if (!isOnline) {
    return (
      <span className="badge badge-phoenix badge-phoenix-warning">
        <span className="fa-solid fa-wifi-slash me-1" />
        Offline{queued > 0 ? ` — ${queued} sale(s) queued` : ""}
      </span>
    );
  }
  return (
    <span className="badge badge-phoenix badge-phoenix-info">
      <span className="fa-solid fa-rotate me-1" />
      Syncing {queued} queued sale(s)...
    </span>
  );
}
