"use client";

import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  PaginationState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  ChevronLeft,
  ChevronRight,
  Eye,
  MoreVertical,
  Search,
  SquarePen,
  Trash2,
  TrendingDown,
  TrendingUp,
  UserIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupText } from "@/components/ui/input-group";
import { paginationBlog } from "@/service/blog/blog";
import { ticketingPagination } from "@/service/ticketing/ticketing";
import { Badge } from "@/components/ui/badge";
import { useRouter, useSearchParams } from "next/navigation";
import TablePagination from "@/components/table/table-pagination";
import columns from "./column";
import { getPlanningPagination } from "@/service/agenda-setting/agenda-setting";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { listDataMedia } from "@/service/broadcast/broadcast";
import { listEnableCategory } from "@/service/content/content";
import { Checkbox } from "@/components/ui/checkbox";
import { close, loading } from "@/config/swal";
import { Link } from "@/i18n/routing";
import { data } from "jquery";
import { useToast } from "@/components/ui/use-toast";
import { setBanner } from "@/service/settings/settings";
import { id } from "date-fns/locale";
import CustomPagination from "@/components/table/custom-pagination";

const ContentListBanner = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showData, setShowData] = React.useState("9");
  const [categories, setCategories] = React.useState<any>();
  const [data, setData] = React.useState<any[]>([]);
  const [totalData, setTotalData] = React.useState<number>(1);
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    []
  );
  const [columnVisibility, setColumnVisibility] =
    React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });
  const [categoryFilter, setCategoryFilter] = React.useState<number[]>([]);
  const [statusFilter, setStatusFilter] = React.useState<number[]>([]);
  const [selectedItems, setSelectedItems] = React.useState<number[]>([]);
  const [page, setPage] = React.useState(1);
  const [totalPage, setTotalPage] = React.useState(1);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [bannerCount, setBannerCount] = React.useState<number>(0);

  React.useEffect(() => {
    fetchBannerCount();
  }, []);

  async function fetchBannerCount() {
    try {
      const res = await listDataMedia(0, "100", "", "", "");
      const banners = res?.data?.data?.content?.filter(
        (item: any) => item.isBanner
      );
      setBannerCount(banners?.length || 0);

      setBannerCount(data?.length || 0);
    } catch (error) {
      console.error("Error fetching banner count:", error);
    }
  }

  const handleKeyUp = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  };

  const handleKeyDown = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  };

  let typingTimer: NodeJS.Timeout;
  const doneTypingInterval = 1500;

  const handleTyping = () => {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(() => {
      setPage(1);
      fetchData();
    }, doneTypingInterval);
  };

  React.useEffect(() => {
    fetchData();
  }, [categoryFilter, statusFilter]);

  async function doneTyping() {
    fetchData();
  }

  React.useEffect(() => {
    const pageFromUrl = searchParams?.get("page");
    if (pageFromUrl) {
      setPage(Number(pageFromUrl));
    }
  }, [searchParams]);

  React.useEffect(() => {
    fetchData();
    // setPagination({
    //   pageIndex: 0,
    //   pageSize: Number(showData),
    // });
  }, [page, showData]);

  async function fetchData() {
    try {
      loading();
      const res = await listDataMedia(
        page - 1,
        showData,
        searchQuery,
        categoryFilter?.sort().join(","),
        statusFilter?.sort().join(",")
      );

      const data = res?.data?.data;
      const contentData = data?.content;
      contentData.forEach((item: any, index: number) => {
        item.no = (page - 1) * Number(showData) + index + 1;
      });

      console.log("contentData : ", data);

      setData(contentData);
      setTotalData(data?.totalElements);
      setTotalPage(data?.totalPages);
      close();
    } catch (error) {
      console.error("Error fetching tasks:", error);
    }
  }

  React.useEffect(() => {
    getCategories();
  }, []);

  async function getCategories() {
    const category = await listEnableCategory("");
    const resCategory = category?.data?.data?.content;
    setCategories(resCategory);
  }

  const handleChange = (type: string, id: number, checked: boolean) => {
    if (type === "category") {
      if (checked) {
        const temp: number[] = [...categoryFilter];
        temp.push(id);
        setCategoryFilter(temp);
      } else {
        const temp = categoryFilter.filter((a) => a !== id);
        setCategoryFilter(temp);
      }
    } else {
      if (checked) {
        const temp: number[] = [...statusFilter];
        temp.push(id);
        setStatusFilter(temp);
      } else {
        const temp = statusFilter.filter((a) => a !== id);
        setStatusFilter(temp);
      }
    }
  };

  const handleSelect = (id: number) => {
    setSelectedItems((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const handleSelectAll = () => {
    if (selectedItems.length === data.length) {
      setSelectedItems([]);
    } else {
      setSelectedItems(data.map((item: any) => Number(item.id)));
    }
  };

  const { toast } = useToast();

  const handleBanner = async (ids: number[]) => {
    try {
      // const res = await Promise.all(ids.map((id) => setBanner(id, true)));

      for (const element of ids) {
        loading();
        const res = await setBanner(element, true);
        close();
        if (res?.error) {
          toast({
            title: "Gagal",
            description:
              "Banner sudah melebihi batas maksimum (4 konten). Silahkan di disable banner Lainnya.",
            variant: "destructive",
          });
        } else {
          toast({
            title: "Sukses",
            description: `item berhasil dijadikan banner.`,
          });
        }
      }
    } catch (err) {
      toast({
        title: "Gagal",
        description: "Terjadi kesalahan saat menjadikan banner.",
        variant: "destructive",
      });
    }
  };

  return (
    <>
      <div className="flex justify-between ">
        <Input
          type="text"
          placeholder="Search"
          value={searchQuery}
          onChange={(e) => {
            setSearchQuery(e.target.value);
            handleTyping();
          }}
          className="max-w-[300px]"
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              fetchData();
            }
          }}
        />

        {/* <div className="flex flex-row gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button size="md" variant="outline">
                1 - {showData} Data
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56 text-sm">
              <DropdownMenuRadioGroup
                value={showData}
                onValueChange={setShowData}
              >
                <DropdownMenuRadioItem value="10">
                  1 - 10 Data
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="20">
                  1 - 20 Data
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="25">
                  1 - 25 Data
                </DropdownMenuRadioItem>
                <DropdownMenuRadioItem value="50">
                  1 - 50 Data
                </DropdownMenuRadioItem>
              </DropdownMenuRadioGroup>
            </DropdownMenuContent>
          </DropdownMenu>
          <Popover>
            <PopoverTrigger asChild>
              <Button size="md" variant="outline">
                Filter
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-80 ">
              <div className="flex flex-col gap-2 px-2">
                <div className="flex justify-between text-sm">
                  <p>Filter</p>
                  <a
                    onClick={() => fetchData()}
                    className="cursor-pointer text-primary"
                  >
                    Simpan
                  </a>
                </div>
                <div className="flex flex-col gap-1 overflow-auto max-h-[300px] text-xs custom-scrollbar-table">
                  <p>Kategory</p>
                  {categories?.map((category: any) => (
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={category.id}
                        checked={categoryFilter.includes(category.id)}
                        onCheckedChange={(e) =>
                          handleChange("category", category.id, Boolean(e))
                        }
                      />
                      <label
                        htmlFor={category.id}
                        className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        {category.name}
                      </label>
                    </div>
                  ))}
                  <p className="mt-3">Status</p>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(1)}
                      onCheckedChange={(e) =>
                        handleChange("status", 1, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Menunggu Review
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(2)}
                      onCheckedChange={(e) =>
                        handleChange("status", 2, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Diterima
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(3)}
                      onCheckedChange={(e) =>
                        handleChange("status", 3, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Minta Update{" "}
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="accepted"
                      checked={statusFilter.includes(4)}
                      onCheckedChange={(e) =>
                        handleChange("status", 4, Boolean(e))
                      }
                    />
                    <label
                      htmlFor="accepted"
                      className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      Ditolak
                    </label>
                  </div>
                </div>
              </div>
            </PopoverContent>
          </Popover>
        </div> */}
      </div>
      <div>
        {/* Header select all + action */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Checkbox
              checked={selectedItems.length === data.length}
              onCheckedChange={handleSelectAll}
            />
            <span>Pilih Semua</span>
          </div>
          {selectedItems.length > 0 && (
            <Button color="primary" onClick={() => handleBanner(selectedItems)}>
              Jadikan Banner
            </Button>
          )}
        </div>

        {/* Grid Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
          {data?.map((item: any) => (
            <div
              key={item.id}
              className="relative rounded-lg shadow-md overflow-hidden border border-gray-200"
            >
              <div className="absolute top-2 left-2 z-10">
                <Checkbox
                  checked={selectedItems.includes(item.id)}
                  onCheckedChange={() => handleSelect(item.id)}
                />
              </div>
              <img
                src={item.smallThumbnailLink || "/placeholder.jpg"}
                alt={item.title}
                className="w-full h-48 object-cover"
              />
              <Link
                href={`/contributor/content/image/detail/${item?.id}`}
                className="p-3"
              >
                <h4 className="font-semibold text-sm">{item.title}</h4>
              </Link>
            </div>
          ))}
        </div>
        <div className="mt-3">
          {data && data?.length > 0 ? (
            <CustomPagination
              totalPage={totalPage}
              onPageChange={(data) => setPage(data)}
            />
          ) : (
            <p>No Data</p>
          )}
        </div>
      </div>
    </>
  );
};

export default ContentListBanner;
