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

import {
  Eye,
  MoreVertical,
  SquarePen,
  Trash2,
  Upload,
  UploadCloud,
} from "lucide-react";
import { cn } 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, useRouter } from "@/components/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { deleteBlog } from "@/service/blog/blog";
import { error, loading, close } from "@/lib/swal";
import { useTranslations } from "next-intl";
import axios from "axios";
import { downloadReport } from "@/service/report/report";

const useTableColumns = ({
  handlePreview,
}: {
  handlePreview: (id: string) => void;
}) => {
  const t = useTranslations("Table"); // Panggil di dalam hook

  const columns: ColumnDef<any>[] = [
    {
      accessorKey: "no",
      header: t("no", { defaultValue: "No" }),
      cell: ({ row }) => <span>{row.getValue("no")}</span>,
    },
    {
      accessorKey: "title",
      header: t("title", { defaultValue: "Title" }),
      cell: ({ row }) => (
        <span className="whitespace-normal">{row.getValue("title")}</span>
      ),
    },
    {
      accessorKey: "createdAt",
      header: t("generate-date", { defaultValue: "Generate 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: "version",
      header: t("version", { defaultValue: "Version" }),
      cell: ({ row }) => <span className="">{row.getValue("version")}</span>,
    },

    {
      accessorKey: "status",
      header: t("status", { defaultValue: "Status" }),
      cell: ({ row }) => <span className="">{row.getValue("status")}</span>,
    },

    {
      id: "actions",
      accessorKey: "action",
      header: t("action", { defaultValue: "Action" }),
      enableHiding: false,
      cell: ({ row }) => {
        const router = useRouter();
        const MySwal = withReactContent(Swal);

        async function deleteProcess(id: any) {
          loading();
          const resDelete = await deleteBlog(id);

          if (resDelete?.error) {
            error(resDelete.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 handleDeleteBlog = (id: any) => {
          MySwal.fire({
            title: "Hapus Data",
            text: "",
            icon: "warning",
            showCancelButton: true,
            cancelButtonColor: "#3085d6",
            confirmButtonColor: "#d33",
            confirmButtonText: "Hapus",
          }).then((result) => {
            if (result.isConfirmed) {
              deleteProcess(id);
            }
          });
        };

        const handleDownload = async (id: string) => {
          try {
            loading();

            const response = await downloadReport(id);
            console.log(response?.data);
            const url = window.URL.createObjectURL(new Blob([response?.data], { type : "application/pdf"}));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", `report-${id}.pdf`);
            document.body.appendChild(link);
            link.click();
            link.remove();
            close();
          } catch (error) {
            console.error("Download failed", error);
            MySwal.fire({
              title: "Gagal",
              text: "Terjadi kesalahan saat mengunduh file.",
              icon: "error",
            });
          }
        };

        // const handleDownload = async (id: string) => {
        //   try {
        //     loading();
        //     const response = await axios.get(
        //       `https://new.netidhub.com/api/media/report/download?id=${id}`,
        //       {
        //         responseType: "blob",
        //       }
        //     );

        //     const url = window.URL.createObjectURL(new Blob([response.data]));
        //     const link = document.createElement("a");
        //     link.href = url;
        //     link.setAttribute("download", `report-${id}.pdf`);
        //     document.body.appendChild(link);
        //     link.click();
        //     link.remove();
        //     close();
        //   } catch (error) {
        //     console.error("Download failed", error);
        //     MySwal.fire({
        //       title: "Gagal",
        //       text: "Terjadi kesalahan saat mengunduh file.",
        //       icon: "error",
        //     });
        //   }
        // };

        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">
              <DropdownMenuItem
                onClick={() => handlePreview(row.original.id)}
                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" />
                Preview
              </DropdownMenuItem>

              <DropdownMenuItem
                onClick={() => handleDownload(row.original.id)}
                className="p-2 border-b text-default-700 group focus:bg-default focus:text-primary-foreground rounded-none"
              >
                <Upload className="w-4 h-4 me-1.5" />
                Download
              </DropdownMenuItem>

              <DropdownMenuItem
                onClick={() => handleDeleteBlog(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;
