"use client";

import { useEffect, useState } from "react";
import { Container, Tab, Tabs, Typography } from "@mui/material";
import axiosInstancee from "@/utils/axios";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import { paths } from "@/routes/paths";
import AgencyGeneralView from "./agency-general-view";
import UserListView from "../../user/view/user-list-view-agency";
import GroupeAgency from "../groupe/groupeAgencyPage";

type Props = {
  id: string;
};

// Define the type for Agency
interface Agency {
  id: string;
  name: string;
  // Add other fields as needed
}

export default function AgencyView({ id }: Props) {
  const [currentAgency, setCurrentAgency] = useState<Agency | undefined>(undefined);
  const [currentTab, setCurrentTab] = useState("about");

  useEffect(() => {
    localStorage.setItem("selectedAgency", id); // Update selected agency in localStorage
    const fetchAgency = async () => {
      try {
        const response = await axiosInstancee.get(`/api/user/agency/${id}`);
        setCurrentAgency(response.data);
      } catch (error) {
        console.error("Failed to fetch agency:", error);
      }
    };

    fetchAgency();
  }, [id]);

  const TABS = [
    { value: "about", label: "About" },
    { value: "users", label: "Users" },
    { value: "group", label: "Groups" },
  ];

  const handleTabChange = (event: React.SyntheticEvent, newValue: string) => {
    setCurrentTab(newValue);
  };

  return (
    <Container>
      <CustomBreadcrumbs
        heading="Agency Details"
        links={[
          { name: "Dashboard", href: paths.dashboard.root },
          { name: "Agency", href: paths.dashboard.agency.list },
          { name: currentAgency?.name || "Agency" },
        ]}
      />
      <Tabs value={currentTab} onChange={handleTabChange}>
        {TABS.map((tab) => (
          <Tab key={tab.value} value={tab.value} label={tab.label} />
        ))}
      </Tabs>
      {currentTab === "about" && currentAgency && <AgencyGeneralView agency={currentAgency} />}
      {currentTab === "users" && currentAgency && <UserListView />}
      {currentTab === "group" && currentAgency && <GroupeAgency agencyId={id} />}
    </Container>
  );
}