import { useContext, useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import NoHouseholdState from "../components/household/NoHouseholdState";
import ManageHousehold from "../components/manage/ManageHousehold";
import ManageStores from "../components/manage/ManageStores";
import { HouseholdContext } from "../context/HouseholdContext";
import "../styles/pages/Manage.css";

export default function Manage() {
  const { activeHousehold, households, loading, hasLoaded } = useContext(HouseholdContext);
  const [activeTab, setActiveTab] = useState("household");
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const tab = searchParams.get("tab");
    if (tab === "household" || tab === "stores") {
      setActiveTab(tab);
    }
  }, [searchParams]);

  if (!hasLoaded || loading || (households.length > 0 && !activeHousehold)) {
    return (
      <div className="manage-body">
        <div className="manage-container">
          <h1 className="manage-title">Manage</h1>
          <p style={{ textAlign: "center", marginTop: "2rem", color: "var(--text-secondary)" }}>
            Loading household...
          </p>
        </div>
      </div>
    );
  }

  if (!activeHousehold) {
    return (
      <div className="manage-body">
        <div className="manage-container">
          <h1 className="manage-title">Manage</h1>
          <NoHouseholdState />
        </div>
      </div>
    );
  }

  return (
    <div className="manage-body">
      <div className="manage-container">
        <h1 className="manage-title">Manage {activeHousehold.name}</h1>

        <div className="manage-tabs">
          <button
            className={`manage-tab ${activeTab === "household" ? "active" : ""}`}
            onClick={() => setActiveTab("household")}
          >
            Household
          </button>
          <button
            className={`manage-tab ${activeTab === "stores" ? "active" : ""}`}
            onClick={() => setActiveTab("stores")}
          >
            Stores
          </button>
        </div>

        <div className="manage-content">
          {activeTab === "household" && <ManageHousehold />}
          {activeTab === "stores" && <ManageStores />}
        </div>
      </div>
    </div>
  );
}
