import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import WorkAddModel from "./WorkAddModel";
import EditWorkModel from "./EditWorkModel";
import { useEffect, useState } from "react";
import { useGetWorkSpaceModeQuery, useWorkspaceToggleMutation } from "../../../Redux/Service/workspace.mode";
import SearchComponent from "../../../components/SearchComponent";
import { Toaster, toaster } from "../../../components/ui/toaster";



// table data

const tableHeadRow = [
  "Sr. No",
  "Title",
  "Action"

];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Title": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <EditWorkModel />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

const WorkspaceMode = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch, isError, isFetching } = useGetWorkSpaceModeQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [workspaceToggle] = useWorkspaceToggleMutation()

  console.log("Workspace Data", data?.data.data)

  useEffect(() => {
    if (data?.data?.data) {
      setLocalData(data?.data.data);
    }
  }, [data]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleToggle = async (agencyId: string, currentStatus: number) => {
    const newStatus = currentStatus ? 0 : 1;
    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );
    try {
      await workspaceToggle({ id: agencyId, is_active: newStatus }).unwrap();
      toaster.create({
        title: "Success",
        description: "Status updated successfully",
        type: "success",
      });
      refetch()
    } catch (error) {
      console.error("Error updating privacy policy:", error);
      toaster.create({
        title: "Error",
        description: "Please try again later.",
        type: "error",
      });
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  };

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const title = agency.en_name?.toLowerCase().includes(searchLower);
    return title;
  });

  const managepost = filteredData?.map((agency: any, index: number) => ({
    'id': agency.id,
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "Title": agency.en_name.length > 12
      ? agency.en_name.slice(0, 12) + '...'
      : agency.en_name,
    "is_active": agency.is_active,
    "Action": (
      <HStack justifyContent="center">
        {/* <ViewAgencyMaster agency={localData} id={agency.id} /> */}
        <EditWorkModel localData={agency} refetch={refetch} />
        <Box>
          <Switch
            colorPalette={"teal"}
            size={"xs"}
            onChange={() => handleToggle(agency.id, Number(agency.is_active))}
            checked={Boolean(Number(agency.is_active))}
          />
        </Box>
      </HStack>
    ),
  }));

  return (

    <MainFrame>
      <Box>
        <HStack
          w={"100%"}
          justifyContent={"space-between"}
          mb={4}
          py={0}
          px={3}
        >
          <Text as={"span"} fontSize={"sm"} fontWeight={500} color={"#000"}>
            Workspace Mode
          </Text>

          <HStack >
            <SearchComponent
              value={searchTerm}
              onChange={(value) => {
                setSearchTerm(value);
                // setCurrentPage(1);
                refetch()
              }}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <WorkAddModel refetch={refetch} />
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name", "Registration Date "]}
          tableHeadRow={tableHeadRow}
          data={managepost}
          paginationData={{
            current_page: data?.data.current_page || 1,
            last_page: data?.data.last_page || 1,
            per_page: data?.data.per_page || 10,
            total: data?.data.total || 0
          }}
          onPageChange={handlePageChange}
          isLoading={isFetching}
          isError={isError}
        />
      </Box>
      <Toaster />
    </MainFrame>
  )
}
export default WorkspaceMode