import {
  Box, HStack,
  // Image, 
  Text
} from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame";
// import AlertDailog from "../../../components/AlertDailog";
// import { RiDeleteBin5Line } from "react-icons/ri";
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import ViewRegisterUsers from "./ViewRegisterUsers";
import EditRegisterUsers from "./EditRegisterUsers";
import AddRegisterUsers from "./AddRegisterUsers";
import { useEffect, useState } from "react";
import { useGetManageUserQuery, UserData, useUserToggleMutation } from "../../../Redux/Service/manage.user";
import SearchComponent from "../../../components/SearchComponent";
// import Delete from "../../../components/ActionIcons/Delete";

const tableHeadRow = [
  "Sr. No",
  "First Name",
  "Mobile Number",
  "Gender",
  "DOB",
  "Type Of User",
  "Language",
  "Activate/Deactivate",
  "Action",
];

// const registerUser: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "First Name": "Ritesh",
//     "Mobile Number": "akanksha@gmail.com",
//     "Gender": "9876543210",
//     "DOB": "Female",
//     "Type Of User": "15-01-1990",
//     "Language": "Mumbai",
//     "Activate/Deactivate": (
//       <Box>
//         <Switch size={'sm'} colorPalette={'teal'} />
//       </Box>
//     ),
//     "Action": (
//       <HStack justifyContent="center">
//         <ViewRegisterUsers />
//         <EditRegisterUsers />
//         {/* <RiDeleteBin5Line style={{ cursor: "pointer" }} /> */}
//         {/* <AlertDailog
//           AltertTiggerIcon={() =><Delete /> } // Pass as function
//           alertText="Delete Users"
//           alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
//           alertCaption="Are You Sure You Want To Delete This User ?"
//           onConfirm={() => {
//             console.log("User deleted:", i + 1);
//           }}
//         /> */}
//       </HStack>
//     ),
//   })),
// ];

const RegisterUsers = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch } = useGetManageUserQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [userToggle] = useUserToggleMutation()
  console.log("Register Users Data", data?.data.data);

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

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

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const firstName = agency.first_name?.toLowerCase().includes(searchLower);
    // const email = agency.capital?.toLowerCase().includes(searchLower);
    return firstName;
  });

  const handleToggle = async (agencyId: number, currentStatus: string) => {
    const newStatus = currentStatus === '1' ? '0' : '1';

    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );

    try {
      await userToggle({ id: agencyId, is_active: newStatus }).unwrap();
      refetch()
    } catch (error) {
      console.error("Error updating privacy policy:", error);
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  }

  const managepost = filteredData?.flatMap((agency: UserData, index: number) => ({
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "First Name": agency.first_name,
    "Mobile Number": agency.phone_number,
    "Gender": agency.gender,
    "DOB": agency.date_of_birth ? new Date(agency.date_of_birth).toLocaleDateString('en-GB').replace(/\//g, '-') : 'N/A',
    "Type Of User": agency.principal_type?.principal_type_title || 'N/A',
    // "Language": agency.principle_language_links.map(lang => lang.language_name).join(', ') || 'N/A',
    "Action": (   
      <HStack justifyContent="center">
        <EditRegisterUsers
        // rowData={{ id: agency.id, en_name: agency.en_name, country_code: agency.country_code, phonecode: agency.phonecode, capital: agency.capital, currency: agency.currency, currency_name: agency.currency_name, currency_symbol: agency.currency_symbol }} 
        // refetch={refetch} 
        />
        <ViewRegisterUsers />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            checked={agency.is_active === true}
            onChange={() => handleToggle(agency.id, agency.is_active ? '1' : '0')}
          />
        </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"}>
            Register Users
          </Text>

          <HStack>
            <SearchComponent
              value={searchTerm}
              onChange={(value) => {
                setSearchTerm(value);
                // setCurrentPage(1);
                refetch()
              }}
            />
            <AddRegisterUsers />
          </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}
        />
      </Box>
    </MainFrame>
  );
};

export default RegisterUsers;
