import { useContext, useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
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 } = 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 (!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>
    );
  }

  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>
  );
}
