"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, loading } 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";

export default function TrackingBeritaCard() {
  const [search, setSearch] = useState("");
  const [content, setContent] = useState<any[]>([]);
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [page, setPage] = React.useState(1);
  const [showData, setShowData] = React.useState("10");
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: Number(showData),
  });

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

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

  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.");
    }
  };

  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="10">
                    1 - 10 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="50">
                    1 - 50 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="100">
                    1 - 100 Data
                  </DropdownMenuRadioItem>
                  <DropdownMenuRadioItem value="250">
                    1 - 250 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.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="flex justify-center items-center gap-2 mt-4">
          <Button
            size="icon"
            variant="ghost"
            disabled={currentPage === 1}
            onClick={() => setCurrentPage((p) => p - 1)}
          >
            <ChevronLeft className="w-4 h-4" />
          </Button>
          <div className="px-3 py-1 rounded-full border">{currentPage}</div>
          <Button
            size="icon"
            variant="ghost"
            onClick={() => setCurrentPage((p) => p + 1)}
          >
            <ChevronRight className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </Card>
  );
}
