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

import {
  CheckSquare2,
  Eye,
  MoreVertical,
  SquarePen,
  Trash2,
} 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 { formatDateToIndonesian } from "@/utils/globals";
import { Link } from "@/i18n/routing";
import {
  closeTicket,
  deleteTicket,
} from "@/service/communication/communication";
import withReactContent from "sweetalert2-react-content";
import { error } from "@/lib/swal";
import Swal from "sweetalert2";

const columns: ColumnDef<any>[] = [
  {
    accessorKey: "no",
    header: "No",
    cell: ({ row }) => <span>{row.getValue("no")}</span>,
  },
  {
    accessorKey: "referenceNumber",
    header: "Ticket Number",
    cell: ({ row }) => <span>{row.getValue("referenceNumber")}</span>,
  },
  {
    accessorKey: "title",
    header: "Title",
    cell: ({ row }) => (
      <span className="normal-case">{row.getValue("title")}</span>
    ),
  },
  {
    accessorKey: "commentFromUserName",
    header: "Sender",
    cell: ({ row }) => (
      <span className="normal-case">{row.getValue("commentFromUserName")}</span>
    ),
  },
  {
    accessorKey: "type",
    header: "Channel",
    cell: ({ row }) => {
      const type = row.getValue("type") as { name: string };
      return <span className="normal-case">{type?.name}</span>;
    },
  },
  {
    accessorKey: "createdBy",
    header: "Operator",
    cell: ({ row }) => {
      const createdBy = row.getValue("createdBy") as { fullname: string };
      return <span className="normal-case">{createdBy?.fullname}</span>;
    },
  },
  {
    accessorKey: "createdAt",
    header: "Tanggal Unggah ",
    cell: ({ row }) => (
      <span className="whitespace-nowrap">
        {formatDateToIndonesian(row.getValue("createdAt"))}
      </span>
    ),
  },
  {
    accessorKey: "status",
    header: "Status",
    cell: ({ row }) => {
      const statusColors: Record<string, string> = {
        open: "bg-primary/20 text-primary",
        close: "bg-success/20 text-success",
      };
      const status = row.getValue("status") as { id: number; name: string };
      const statusName = status?.name?.toLocaleLowerCase();
      // console.log(statusName);
      const statusStyles = statusColors[statusName] || "default";
      if (statusName) {
        return (
          <Badge className={cn("rounded-full px-5", statusStyles)}>
            {statusName}{" "}
          </Badge>
        );
      }
    },
  },
  {
    id: "actions",
    accessorKey: "action",
    header: "Actions",
    enableHiding: false,
    cell: ({ row }) => {
      const MySwal = withReactContent(Swal);

      async function doDelete(id: any) {
        const response = await deleteTicket(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 handleDelete = (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);
          }
        });
      };

      async function doClose(id: any) {
        const response = await closeTicket(id);

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

      const handleClose = (id: any) => {
        MySwal.fire({
          title: "Ubah status menjadi close?",
          text: "",
          icon: "warning",
          showCancelButton: true,
          cancelButtonColor: "#3085d6",
          confirmButtonColor: "#d33",
          confirmButtonText: "Iya",
        }).then((result) => {
          if (result.isConfirmed) {
            doClose(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={`/supervisor/ticketing/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={`/supervisor/ticketing/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={() => handleClose(row.original.id)}
              className="p-2 border-b text-green-600 bg-green-200  focus:bg-green-400 focus:text-destructive-foreground rounded-none"
            >
              <CheckSquare2 className="w-4 h-4 me-1.5" />
              Close
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => handleDelete(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>
      );
    },
  },
];

export default columns;
