// page.tsx (Client Component)
"use client";

import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import axiosInstancee from "@/utils/axios";
import GroupNewEditView from "@/shared/sections/agency/groupe/edit-new-view";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import { paths } from "@/routes/paths";
import { useSettingsContext } from "@/shared/components/settings";
import { Container } from "@mui/material";
import { IGroupeAgency } from "@/shared/types/groupeAgency";

export default function GroupeEditPage() {
  const { id } = useParams();
  const settings = useSettingsContext();

  const [currentGroup, setCurrentGroup] = useState<IGroupeAgency | undefined>(undefined);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) return;

    const fetchGroup = async () => {
      try {
        const response = await axiosInstancee.get(`/api/user/groups/${id}`);
        setCurrentGroup(response.data);
      } catch (err) {
        console.error("Error fetching group:", err);
        setError("Failed to load group information.");
      } finally {
        setLoading(false);
      }
    };

    fetchGroup();
  }, [id]);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error}</p>;

  return (
    <Container maxWidth={settings.themeStretch ? false : "lg"}>
      <CustomBreadcrumbs
        heading="Edit Group"
        links={[
          { name: "Dashboard", href: paths.dashboard.root },
          { name: "Agency", href: paths.dashboard.agency.list },
          { name: "Group", href: paths.dashboard.agency.groupe.list },
          { name: currentGroup?.name || "Edit Group" },
        ]}
      />
      <GroupNewEditView currentGroup={currentGroup} />
    </Container>
  );
}
