"use client";

import { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"; // pastikan path sesuai
import { format } from "date-fns";
import { id } from "date-fns/locale";
import { Badge } from "@/components/ui/badge";
import { listDataImage, listDataVideo } from "@/service/content";
import { Button } from "../ui/button";
import page from "@/app/page";
import { getCookiesDecrypt } from "@/lib/utils";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Edit, Eye, Trash, View } from "lucide-react";

export default function VideoTable() {
  const [dataTable, setDataTable] = useState([]);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const searchParams = useSearchParams();

  const params = useParams();
  const locale = params?.locale;
  const MySwal = withReactContent(Swal);
  const [totalData, setTotalData] = useState<number>(1);

  const [showData, setShowData] = useState("10");

  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [search, setSearch] = useState("");
  const userId = getCookiesDecrypt("uie");
  const userLevelId = getCookiesDecrypt("ulie");

  const [categories, setCategories] = useState<any[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<number[]>([]);

  const [categoryFilter, setCategoryFilter] = useState<string>("");
  const [statusFilter, setStatusFilter] = useState<any[]>([]);
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [filterByCreator, setFilterByCreator] = useState("");
  const [filterBySource, setFilterBySource] = useState("");
  const [filterByCreatorGroup, setFilterByCreatorGroup] = useState("");

  const roleId = getCookiesDecrypt("urie");

  async function fetchData() {
    const formattedStartDate = startDate
      ? format(new Date(startDate), "yyyy-MM-dd")
      : "";
    const formattedEndDate = endDate
      ? format(new Date(endDate), "yyyy-MM-dd")
      : "";
    try {
      const isForSelf = Number(roleId) === 4;
      setLoading(true);
      const res = await listDataVideo(
        showData,
        page - 1,
        isForSelf,
        !isForSelf,
        categoryFilter,
        statusFilter,
        statusFilter?.sort().join(",").includes("1") ? userLevelId : "",
        filterByCreator,
        filterBySource,
        formattedStartDate,
        formattedEndDate,
        search,
        filterByCreatorGroup
      );
      const contentData = res?.data?.data?.content || [];

      const formattedData = contentData.map((item: any, index: number) => ({
        no: index + 1,
        ...item,
      }));

      setDataTable(formattedData);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchData();
  }, []);

  const getStatusBadge = (status: number) => {
    switch (status) {
      case 1:
        return <Badge className="bg-green-500">Done</Badge>;
      case 2:
        return <Badge className="bg-blue-500">Queue</Badge>;
      case 3:
        return <Badge className="bg-red-500">Trigger Error</Badge>;
      default:
        return <Badge variant="secondary">Unknown</Badge>;
    }
  };

  return (
    <div className="rounded-md border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="text-center w-[70px]">No</TableHead>
            <TableHead>Title</TableHead>
            <TableHead>Category</TableHead>
            <TableHead>Created At</TableHead>
            <TableHead>Creator Name</TableHead>
            <TableHead>Creator Group</TableHead>
            <TableHead>Status</TableHead>
            <TableHead className="text-center">Action</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            <TableRow>
              <TableCell colSpan={8} className="text-center">
                Loading...
              </TableCell>
            </TableRow>
          ) : dataTable.length > 0 ? (
            dataTable.map((item: any) => (
              <TableRow key={item.id}>
                <TableCell className="text-center">{item.no}</TableCell>
                <TableCell>{item.title}</TableCell>
                <TableCell>{item.categoryName}</TableCell>
                <TableCell>
                  {item.createdAt
                    ? format(new Date(item.createdAt), "dd-MM-yyyy HH:mm", {
                        locale: id,
                      })
                    : "-"}
                </TableCell>
                <TableCell>{item.creatorName}</TableCell>
                <TableCell>{item.creatorGroup}</TableCell>
                <TableCell>{getStatusBadge(item.status)}</TableCell>
                <TableCell className="flex flex-row text-center space-x-2">
                  <Button
                    size="sm"
                    variant="outline"
                    className="flex items-center gap-2"
                  >
                    <Eye size={15} />
                    Detail
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    className="flex items-center gap-2"
                  >
                    <Edit size={15} />
                    Edit
                  </Button>
                  <Button
                    size="sm"
                    className="flex items-center gap-2 bg-red-500 text-white"
                  >
                    <Trash size={15} />
                    Delete
                  </Button>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={8} className="text-center">
                No data found
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
}
