import * as React from "react";
import { ColumnDef } from "@tanstack/react-table";

import { Eye, MoreVertical, SquarePen, Trash2 } from "lucide-react";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
  DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { format } from "date-fns";
import { Link } from "@/components/navigation";
import withReactContent from "sweetalert2-react-content";
import { deleteMedia } from "@/service/content/content";
import { error } from "@/lib/swal";
import Swal from "sweetalert2";
import { useTranslations } from "next-intl";

const useTableColumns = () => {
  const t = useTranslations("Table"); // Panggil di dalam hook
  const MySwal = withReactContent(Swal);
  const userLevelId = getCookiesDecrypt("ulie");

  const columns: ColumnDef<any>[] = [
    {
      accessorKey: "no",
      header: t("no"),
      cell: ({ row }) => (
        <div className="flex items-center gap-5">
          <div className="flex-1 text-start">
            <h4 className="text-sm font-medium text-default-600 whitespace-nowrap mb-1">
              {row.getValue("no")}
            </h4>
          </div>
        </div>
      ),
    },
    {
      accessorKey: "title",
      header: t("title"),
      cell: ({ row }: { row: { getValue: (key: string) => string } }) => {
        const title: string = row.getValue("title");
        return (
          <span className="whitespace-nowrap">
            {title.length > 50 ? `${title.slice(0, 30)}...` : title}
          </span>
        );
      },
    },
    {
      accessorKey: "categoryName",
      header: t("category-name"),
      cell: ({ row }) => (
        <span className="whitespace-nowrap">
          {row.getValue("categoryName")}
        </span>
      ),
    },
    {
      accessorKey: "createdAt",
      header: t("upload-date"),
      cell: ({ row }) => {
        const createdAt = row.getValue("createdAt") as
          | string
          | number
          | undefined;

        const formattedDate =
          createdAt && !isNaN(new Date(createdAt).getTime())
            ? format(new Date(createdAt), "dd-MM-yyyy HH:mm:ss")
            : "-";
        return <span className="whitespace-nowrap">{formattedDate}</span>;
      },
    },
    {
      accessorKey: "creatorName",
      header: t("creator-group"),
      cell: ({ row }) => (
        <span className="whitespace-nowrap">{row.getValue("creatorName")}</span>
      ),
    },
    {
      accessorKey: "creatorGroupLevelName",
      header: t("source"),
      cell: ({ row }) => (
        <span className="whitespace-nowrap">
          {row.getValue("creatorGroupLevelName")}
        </span>
      ),
    },
    {
      accessorKey: "publishedOn",
      header: t("published"),
      cell: ({ row }) => {
        const isPublish = row.original.isPublish;
        const isPublishOnPolda = row.original.isPublishOnPolda;
        const creatorGroupParentLevelId = row.original.creatorGroupParentLevelId;

        let displayText = "-";
        if (isPublish && !isPublishOnPolda) {
          displayText = "Mabes";
        } else if (isPublish && isPublishOnPolda) {
          if (Number(creatorGroupParentLevelId) == 761) {
            displayText = "Mabes & Satker";
          } else {
            displayText = "Mabes & Polda";
          }
        } else if (!isPublish && isPublishOnPolda) {
          if (Number(creatorGroupParentLevelId) == 761) {
            displayText = "Satker";
          } else {
            displayText = "Polda";
          }
        }

        return (
          <div className="text-center whitespace-nowrap" title={displayText}>
            {displayText}
          </div>
        );
      },
    },
    {
      accessorKey: "statusName",
      header: "Status",
      cell: ({ row }) => {
        const statusColors: Record<string, string> = {
          diterima: "bg-green-100 text-green-600",
          "menunggu review": "bg-orange-100 text-orange-600",
        };

        const colors = [
          "bg-orange-100 text-orange-600",
          "bg-orange-100 text-orange-600",
          "bg-green-100 text-green-600",
          "bg-blue-100 text-blue-600",
          "bg-red-200 text-red-600",
        ];

        const status =
          Number(row.original?.statusId) == 2 &&
          row.original?.reviewedAtLevel !== null &&
          !row.original?.reviewedAtLevel?.includes(`:${userLevelId}:`) &&
          Number(row.original?.creatorGroupLevelId) != Number(userLevelId)
            ? "1"
            : row.original?.statusId;
        const statusStyles =
          colors[Number(status)] || "bg-red-200 text-red-600";
        // const statusStyles = statusColors[status] || "bg-red-200 text-red-600";

        return (
          <Badge
            className={cn(
              "rounded-full px-5 w-full whitespace-nowrap",
              statusStyles
            )}
          >
            {(Number(row.original?.statusId) == 2 &&
              !row.original?.reviewedAtLevel !== null &&
              !row.original?.reviewedAtLevel?.includes(
                `:${Number(userLevelId)}:`
              ) &&
              Number(row.original?.creatorGroupLevelId) !=
                Number(userLevelId)) ||
            (Number(row.original?.statusId) == 1 &&
              Number(row.original?.needApprovalFromLevel) ==
                Number(userLevelId))
              ? "Menunggu Review"
              : row.original?.statusName}{" "}
          </Badge>
        );
      },
    },
    {
      id: "actions",
      accessorKey: "action",
      header: t("action"),
      enableHiding: false,
      cell: ({ row }) => {
        const MySwal = withReactContent(Swal);

        async function doDelete(id: any) {
          // loading();
          const data = {
            id,
          };

          const response = await deleteMedia(data);

          if (response?.error) {
            error(response.message);
            return false;
          }
          success();
        }

        function success() {
          MySwal.fire({
            title: "Sukses",
            icon: "success",
            confirmButtonColor: "#3085d6",
            confirmButtonText: "OK",
          }).then((result) => {
            if (result.isConfirmed) {
              window.location.reload();
            }
          });
        }

        const handleDeleteMedia = (id: any) => {
          MySwal.fire({
            title: "Hapus Data",
            text: "",
            icon: "warning",
            showCancelButton: true,
            cancelButtonColor: "#3085d6",
            confirmButtonColor: "#d33",
            confirmButtonText: "Hapus",
          }).then((result) => {
            if (result.isConfirmed) {
              doDelete(id);
            }
          });
        };
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                size="icon"
                className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
              >
                <span className="sr-only">Open menu</span>
                <MoreVertical className="h-4 w-4 text-default-800" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="p-0" align="end">
              <Link
                href={`/contributor/content/audio/detail/${row.original.id}`}
              >
                <DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
                  <Eye className="w-4 h-4 me-1.5" />
                  View
                </DropdownMenuItem>
              </Link>
              <Link
                href={`/contributor/content/audio/update/${row.original.id}`}
              >
                <DropdownMenuItem className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none">
                  <SquarePen className="w-4 h-4 me-1.5" />
                  Edit
                </DropdownMenuItem>
              </Link>
              <DropdownMenuItem
                onClick={() => handleDeleteMedia(row.original.id)}
                className="p-2 border-b text-destructive bg-destructive/30  focus:bg-destructive focus:text-destructive-foreground rounded-none"
              >
                <Trash2 className="w-4 h-4 me-1.5" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];

  return columns;
};

export default useTableColumns;
