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

import { Eye, MoreVertical, SquarePen, Trash2, Upload } 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 Swal from "sweetalert2";
import { error } from "@/lib/swal";
import { deleteMedia } from "@/service/content/content";
import { publishContest } from "@/service/contest/contest";

const columns: ColumnDef<any>[] = [
  {
    accessorKey: "no",
    header: "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: "hastagCode",
    header: "Kode",
    cell: ({ row }) => (
      <div className="flex items-center gap-5">
        <div className="flex-1 text-start">
          <h4
            className="text-sm font-bold
           text-default-600 whitespace-nowrap mb-1"
          >
            {row.getValue("hastagCode")}
          </h4>
        </div>
      </div>
    ),
  },
  {
    accessorKey: "theme",
    header: "Judul",
    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("theme")}
          </h4>
        </div>
      </div>
    ),
  },
  {
    accessorKey: "duration",
    header: "Durasi ",
    cell: ({ row }) => (
      <span className="whitespace-nowrap">{row.getValue("duration")}</span>
    ),
  },
  {
    accessorKey: "targetOutput",
    header: "Target Output ",
    cell: ({ row }) => (
      <span className="whitespace-nowrap">{row.getValue("targetOutput")}</span>
    ),
  },
  {
    accessorKey: "targetParticipantTopLevel",
    header: "Target Participant ",
    cell: ({ row }) => (
      <span className="whitespace-nowrap">
        {row.getValue("targetParticipantTopLevel")}
      </span>
    ),
  },
  {
    accessorKey: "isPublishForAll", // Bisa menggunakan ini untuk membaca default data
    header: "Status",
    cell: ({
      row,
    }: {
      row: {
        original: { isPublishForAll?: boolean; isPublishForMabes?: boolean };
      };
    }) => {
      const userRoleId: number = Number(getCookiesDecrypt("urie"));
      const userLevelNumber: number = Number(getCookiesDecrypt("ulne"));

      // Mengambil data dari row.original agar lebih aman
      const isPublishForAll: boolean = Boolean(row.original.isPublishForAll);
      const isPublishForMabes: boolean = Boolean(
        row.original.isPublishForMabes
      );

      // Logika status berdasarkan role dan data dari API
      const isPending: boolean =
        (userRoleId === 3 && userLevelNumber === 1 && !isPublishForAll) || // Role 3 dengan level 1 hanya publish jika isPublishForAll true
        ((userRoleId === 11 || userRoleId === 12) && !isPublishForMabes); // Role 11 dan 12 hanya publish jika isPublishForMabes true

      return (
        <Badge
          className={`whitespace-nowrap px-2 py-1 rounded-full ${
            isPending
              ? "bg-orange-100 text-orange-600" // Warna kuning untuk "Pending"
              : "bg-green-100 text-green-600" // Warna hijau untuk "Publish"
          }`}
        >
          {isPending ? "Pending" : "Publish"}
        </Badge>
      );
    },
  },

  {
    id: "actions",
    accessorKey: "action",
    header: "Actions",
    enableHiding: false,
    cell: ({ row }) => {
      const MySwal = withReactContent(Swal);
      const userRoleId = Number(getCookiesDecrypt("urie"));
      const userLevelId = Number(getCookiesDecrypt("ulie"));
      const userLevelNumber = Number(getCookiesDecrypt("ulne"));

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

        const response = await publishContest(id);

        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 handlePublishContest = (id: any) => {
        MySwal.fire({
          title: "Apakah anda ingin publish Lomba?",
          showCancelButton: true,
          cancelButtonColor: "#3085d6",
          confirmButtonColor: "#d33",
          confirmButtonText: "Ya",
          cancelButtonText: "Tidak",
        }).then((result) => {
          if (result.isConfirmed) {
            doPublish(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">
            {((userRoleId == 11 || userRoleId == 12) &&
              row?.original?.isPublishForMabes != true) ||
            (userRoleId == 3 &&
              userLevelNumber == 1 &&
              row?.original?.isPublishForAll != true) ? (
              <DropdownMenuItem
                className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none"
                onClick={() => handlePublishContest(row.original.id)}
              >
                <Upload className="w-4 h-4 me-1.5" />
                Publish
              </DropdownMenuItem>
            ) : (
              ""
            )}
            <Link href={`/shared/contest/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>
            {/* <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>
            <DropdownMenuItem 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>
      );
    },
  },
];

export default columns;
