"use client";
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { ChevronLeft, ChevronRight } from "lucide-react";
import {
  listDataAllNonPagination,
  listDataTracking,
  mediaTrackingSave,
} from "@/service/media-tracking/media-tracking";
import { error } from "@/lib/swal";
import { toast } from "sonner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { PaginationState } from "@tanstack/react-table";
import page from "../page";
import CustomPagination from "@/components/table/custom-pagination";
import { close, loading } from "@/config/swal";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";

export default function TrackingBeritaCard() {
  const [search, setSearch] = useState("");
  const [content, setContent] = useState<any[]>([]);
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [showData, setShowData] = useState("6");
  const MySwal = withReactContent(Swal);

  useEffect(() => {
    initFecth();
  }, [showData, page]);

  const initFecth = async () => {
    loading();
    const response = await listDataTracking(showData, page - 1);
    const data = response?.data?.data;
    const newData = data?.content;
    setTotalPage(data?.totalPages || 1);
    newData.forEach((item: any, index: number) => {
      item.no = (page - 1) * Number(showData) + index + 1;
    });
    setContent(response?.data?.data?.content || []);
    close();
  };

  const fecthAll = async (keyword: string) => {
    const response = await listDataAllNonPagination(keyword);
    setContent(response?.data?.data?.content || []);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearch(value);

    if (value.trim() === "") {
      initFecth();
    } else {
      fecthAll(value);
    }
  };

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

  // const doSave = async () => {
  //   if (selectedItems.length === 0) {
  //     toast("Pilih minimal 1 berita untuk disimpan.");
  //     return;
  //   }

  //   try {
  //     const promises = selectedItems.map((id) =>
  //       mediaTrackingSave({
  //         mediaUploadId: id,
  //         duration: 24,
  //         scrapingPeriod: 3,
  //       })
  //     );
  //     await Promise.all(promises);

  //     toast("Berhasil Menambahkan", {
  //       description: "",
  //     });
  //     setSelectedItems([]);
  //     initFecth();
  //   } catch (err: any) {
  //     error(err?.message || "Gagal menyimpan data.");
  //   }
  // };

  const doSave = async () => {
    if (selectedItems.length === 0) {
      MySwal.fire(
        "Peringatan",
        "Pilih minimal 1 berita untuk disimpan.",
        "warning"
      );
      return;
    }

    try {
      loading(); 

      const promises = selectedItems.map((id) =>
        mediaTrackingSave({
          mediaUploadId: id,
          duration: 24,
          scrapingPeriod: 3,
        })
      );
      await Promise.all(promises);

      close(); 

      await MySwal.fire({
        icon: "success",
        title: "Berhasil!",
        text: "Tracking berita berhasil ditambahkan.",
        confirmButtonColor: "#2563eb",
      });

      setSelectedItems([]);
      initFecth();
    } catch (err: any) {
      close(); 
      MySwal.fire({
        icon: "error",
        title: "Gagal!",
        text: err?.message || "Terjadi kesalahan saat menyimpan data.",
        confirmButtonColor: "#dc2626", 
      });
    }
  };

  return (
    <Card>
      <div className="p-4 space-y-4">
        <div className="flex justify-between items-center">
          <Input
            placeholder="Pencarian"
            value={search}
            onChange={handleInputChange}
            className="max-w-sm"
          />
          <div className="mx-3">
            <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="12">
                    1 - 6 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="12">
                    1 - 12 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="60">
                    1 - 60 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="120">
                    1 - 120 Data
                  </DropdownMenuRadioItem>
                </DropdownMenuRadioGroup>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {selectedItems.length > 0 && (
          <div className="flex justify-between items-center">
            <div className="text-sm text-blue-600 font-medium">
              {selectedItems.length} Item Terpilih{" "}
              <span className="text-black">
                / Tracking Berita tersisa {29 - selectedItems.length}
              </span>
            </div>
            <Button className="bg-blue-600 text-white" onClick={doSave}>
              Submit
            </Button>
          </div>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
          {content?.length > 1 &&
            content.map((item: any) => (
              <Card
                key={item.id}
                className="relative overflow-hidden shadow-sm border rounded-lg cursor-pointer"
                onClick={() => handleSelect(item.id)}
              >
                <img
                  src={item.thumbnailLink}
                  alt={item.title}
                  className="w-full h-[300px] object-cover"
                />
                <div className="absolute top-2 left-2">
                  <div className="w-5 h-5 border-2 border-white bg-white rounded-sm flex items-center justify-center">
                    {selectedItems.includes(item.id) && (
                      <div className="w-3 h-3 bg-blue-600 rounded-sm" />
                    )}
                  </div>
                </div>
                <p className="p-2 text-sm font-medium text-gray-800 truncate">
                  {item.title}
                </p>
              </Card>
            ))}
        </div>
        <div className="mt-3">
          {content && content?.length > 0 ? (
            <CustomPagination
              totalPage={totalPage}
              onPageChange={(data) => setPage(data)}
            />
          ) : (
            <p>No Data</p>
          )}
        </div>
      </div>
    </Card>
  );
}
