import {
  Box, HStack, Icon, Image,
  // Span, 
  Text
} from "@chakra-ui/react";
import MainFrame from "../../components/MainFrame";
// import { InputGroup } from "../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../components/DataTable";
// import AlertDailog from "../../components/AlertDailog";
import { Switch } from "../../components/ui/switch";
// import img from "../../assets/waterfall.jpg";
// import { RiDeleteBin5Line } from "react-icons/ri";
import ViewDailog from "./ViewDailog";
import { useGetManagePostsQuery, usePostStatusToggleMutation } from "../../Redux/Service/manage.post.service";
import { useEffect, useState } from "react";
import { Toaster, toaster } from "../../components/ui/toaster";
import { FaVideo } from "react-icons/fa";
import SearchComponent from "../../components/SearchComponent";
import { delay } from "../../components/Utils";
// import Delete from "../../components/ActionIcons/Delete";
// import ViewDailog from './ViewDailog'

const APIURL = import.meta.env.VITE_POST_IMG

const tableHeadRow = [
  "Sr. No",
  "Images",
  "Description",
  "Publish Data",
  // "Activate/Deactivate",
  "Action",
];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     Images: (
//       // <Image w={50} src={img} />
//       <Image rounded={"lg"} w={100} h={50} src={img} />
//     ),
//     Description: (
//       <Text>
//         {`Lorem ipsum dolor, sit amet consectetur adipisicing elit.}`.slice(
//           0,
//           30
//         ) + "..."}
//       </Text>
//     ),
//     "Publish Data": "12/01/2025",
//     "Activate/Deactivate": (
//       <Box w={"100%"}>
//         <Switch size={"sm"} colorPalette={"teal"} />
//       </Box>
//     ),
//     Action: (
//       <HStack justifyContent="center">
//         <ViewDailog />
//         {/* <AlertDailog
//           AltertTiggerIcon={() => <Span><Delete /> </Span>} 
//           alertText="Delete Users"
//           alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
//           alertCaption="are you sure you want to delete ?"
//           onConfirm={() => {
//             console.log("User deleted:", i + 1);
//           }}
//         /> */}
//       </HStack>
//     ),
//   })),
// ];

const ManagePost = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch, isFetching, isError } = useGetManagePostsQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [postStatusToggle] = usePostStatusToggleMutation()
  console.log('POSTS', 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 postStatusToggle({ id: agencyId, is_active: newStatus }).unwrap();
      toaster.create({
        title: "Success",
        description: "Status updated successfully",
        type: "success",
      });
      await delay(500);
      refetch()
    } catch (error) {
      console.error("Error updating:", error);
      toaster.create({
        title: "Error",
        description: "Someting went wrong.",
        type: "error",
      });
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  };


  function formatAPIDate(apiDateString: any) {
    const date = new Date(apiDateString);

    // Get month, day, and year
    const month = date.getMonth() + 1; // Months are 0-indexed
    const day = date.getDate();
    const year = date.getFullYear();

    // Pad with leading zeros if needed
    const formattedMonth = month.toString().padStart(2, '0');
    const formattedDay = day.toString().padStart(2, '0');

    return `${formattedMonth}/${formattedDay}/${year}`;
  }

  const filteredData = localData?.filter((agency) => {
    return (agency.post_content_translation.some((item: any) => {
      const searchLower = searchTerm.toLowerCase();
      const title = item.content?.toLowerCase().includes(searchLower);
      return title;
    }))
  });

  const managepost = filteredData?.flatMap((agency: any, index: number) => (agency.post_content_translation.map((translation: any) => ({
    'id': agency.id,
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    Images: (
      agency.images.length > 0 ?
        agency.images[0].type === "image" ? (
          <HStack>
            <Image
              rounded={"lg"}
              w={100}
              h={50}
              src={`${APIURL}${agency.images[0].image_name}`}
            />
            <Text fontSize="xs" color={'lightgray'}>
              {`${Number(agency.images.length) > 1 ? '+' + (Number(agency.images.length) - 1) : ''}`}
            </Text>
          </HStack>
        ) : (
          <HStack>
            <Box
              rounded={"lg"}
              w={100}
              h={50}
              bg="gray.200"
              display="flex"
              alignItems="center"
              justifyContent="center"
            >
              <Icon as={FaVideo} color="gray.500" />
            </Box>
            <Text fontSize="xs" color={'lightgray'}>
              {`${Number(agency.images.length) > 1 ? '+' + (Number(agency.images.length) - 1) : ''}`}
            </Text>
          </HStack>
        ) : ''
      // <Image rounded={"lg"} w={100} h={50} src={img} />
    ),
    Description: (
      <Text>
        {translation?.content?.length > 30
          ? `${translation.content.slice(0, 30)}...`
          : translation?.content}
      </Text>
    ),
    "Publish Data": formatAPIDate(agency.created_at),
    "is_active": agency.is_active,
    "Action": (
      <HStack justifyContent="center">
        {/* <ViewAgencyMaster agency={localData} id={agency.id} /> */}
        <ViewDailog localData={{ ...agency, translation }} 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"}>
            {/* Manage Post */}
          </Text>

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