"use client";
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 { useRouter } from "next/navigation";
import { error } from "@/lib/swal";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { deleteUserLevel } from "@/service/tenant";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { getUserLevelDetail } from "@/service/tenant";
import {
  getUserLevelMenuAccessesByUserLevelId,
  UserLevelMenuAccess,
} from "@/service/user-level-menu-accesses";
import {
  getUserLevelMenuActionAccessesByUserLevelIdAndMenuId,
  UserLevelMenuActionAccess,
} from "@/service/user-level-menu-action-accesses";
import {
  getMenuActionsByMenuId,
  MenuAction,
} from "@/service/menu-actions";
import {
  getMasterMenus,
  MasterMenu,
} from "@/service/menu-modules";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

const useTableColumns = (onEdit?: (data: any) => void) => {
  const MySwal = withReactContent(Swal);
  const userLevelId = getCookiesDecrypt("ulie");

  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: "aliasName",
      header: "Name",
      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("aliasName")}
            </h4>
          </div>
        </div>
      ),
    },
    {
      accessorKey: "group",
      header: "Group",
      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("group")}
            </h4>
          </div>
        </div>
      ),
    },
    {
      accessorKey: "parentLevelName",
      header: "Parent Level",
      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("parentLevelName")}
            </h4>
          </div>
        </div>
      ),
    },
    // {
    //   accessorKey: "createdAt",
    //   header: "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: "Creator Group",
    //   cell: ({ row }) => (
    //     <span className="whitespace-nowrap">
    //       {row.original.creatorName || row.original.createdByName || "-"}
    //     </span>
    //   ),
    // },
    // {
    //   accessorKey: "creatorGroupLevelName",
    //   header: "Source",
    //   cell: ({ row }) => (
    //     <span className="whitespace-nowrap">
    //       {row.getValue("creatorGroupLevelName") || "-"}
    //     </span>
    //   ),
    // },
    // {
    //   accessorKey: "publishedOn",
    //   header: "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 statusId = Number(row.original?.statusId);
    //     const reviewedAtLevel = row.original?.reviewedAtLevel || "";
    //     const creatorGroupLevelId = Number(row.original?.creatorGroupLevelId);
    //     const needApprovalFromLevel = Number(row.original?.needApprovalFromLevel);

    //     const userHasReviewed = reviewedAtLevel.includes(`:${userLevelId}:`);
    //     const isCreator = creatorGroupLevelId === Number(userLevelId);

    //     const isWaitingForReview = statusId === 2 && !userHasReviewed && !isCreator;
    //     const isApprovalNeeded = statusId === 1 && needApprovalFromLevel === Number(userLevelId);

    //     const label =
    //       isWaitingForReview || isApprovalNeeded
    //         ? "Menunggu Review"
    //         : statusId === 2
    //         ? "Diterima"
    //         : row.original?.statusName;

    //     const colors: Record<string, string> = {
    //       "Menunggu Review": "bg-orange-100 text-orange-600",
    //       Diterima: "bg-green-100 text-green-600",
    //       default: "bg-red-200 text-red-600",
    //     };

    //     const statusStyles = colors[label] || colors.default;

    //     return (
    //       <Badge className={cn("rounded-full px-5 w-full whitespace-nowrap", statusStyles)}>
    //         {label}
    //       </Badge>
    //     );
    //   },
    // },
    {
      id: "actions",
      accessorKey: "action",
      header: "Action",
      enableHiding: false,
      cell: ({ row }) => {
        const router = useRouter();
        const MySwal = withReactContent(Swal);
        const [isDialogOpen, setIsDialogOpen] = React.useState(false);
        const [detailData, setDetailData] = React.useState<any>(null);

        const [menuAccesses, setMenuAccesses] = React.useState<UserLevelMenuAccess[]>([]);
        const [actionAccesses, setActionAccesses] = React.useState<Record<number, UserLevelMenuActionAccess[]>>({});
        const [menus, setMenus] = React.useState<MasterMenu[]>([]);
        const [menuActionsMap, setMenuActionsMap] = React.useState<Record<number, MenuAction[]>>({});
        const [isLoadingDetail, setIsLoadingDetail] = React.useState(false);

        const handleView = async (id: number) => {
          setIsLoadingDetail(true);
          try {
            // Load basic user level data
            const res = await getUserLevelDetail(id);
            if (!res?.error) {
              setDetailData(res?.data?.data);
              
              // Load menus
              const menusRes = await getMasterMenus({ limit: 100 });
              if (!menusRes?.error) {
                const menusData = (menusRes?.data?.data || []).map((menu: any) => ({
                  ...menu,
                  moduleId: menu.module_id || menu.moduleId,
                  parentMenuId: menu.parent_menu_id !== undefined ? menu.parent_menu_id : menu.parentMenuId,
                  statusId: menu.status_id || menu.statusId,
                  isActive: menu.is_active !== undefined ? menu.is_active : menu.isActive,
                }));
                setMenus(menusData);
                
                // Load actions for each menu
                const actionsMap: Record<number, MenuAction[]> = {};
                for (const menu of menusData) {
                  try {
                    const actionsRes = await getMenuActionsByMenuId(menu.id);
                    if (!actionsRes?.error) {
                      actionsMap[menu.id] = actionsRes?.data?.data || [];
                    }
                  } catch (error) {
                    console.error(`Error loading actions for menu ${menu.id}:`, error);
                  }
                }
                setMenuActionsMap(actionsMap);
              }
              
              // Load menu accesses
              const menuAccessRes = await getUserLevelMenuAccessesByUserLevelId(id);
              if (!menuAccessRes?.error) {
                const accesses = menuAccessRes?.data?.data || [];
                setMenuAccesses(accesses);
                
                // Load action accesses for each menu
                const actionAccessesMap: Record<number, UserLevelMenuActionAccess[]> = {};
                for (const menuAccess of accesses.filter((a: UserLevelMenuAccess) => a.canAccess)) {
                  try {
                    const actionRes = await getUserLevelMenuActionAccessesByUserLevelIdAndMenuId(id, menuAccess.menuId);
                    if (!actionRes?.error) {
                      actionAccessesMap[menuAccess.menuId] = actionRes?.data?.data || [];
                    }
                  } catch (error) {
                    console.error(`Error loading action accesses for menu ${menuAccess.menuId}:`, error);
                  }
                }
                setActionAccesses(actionAccessesMap);
              }
              
              setIsDialogOpen(true);
            } else {
              error(res?.message || "Gagal memuat detail user level");
            }
          } catch (err) {
            console.error("View error:", err);
            error("Terjadi kesalahan saat memuat data.");
          } finally {
            setIsLoadingDetail(false);
          }
        };

        async function doDelete(id: number) {
          const response = await deleteUserLevel(id);
          if (response?.error) {
            error(response.message || "Gagal menghapus data");
            return;
          }

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

        const handleDelete = (id: number) => {
          MySwal.fire({
            title: "Yakin ingin menghapus?",
            text: "Data ini tidak dapat dikembalikan!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya, hapus",
            cancelButtonText: "Batal",
            confirmButtonColor: "#d33",
            cancelButtonColor: "#3085d6",
          }).then((result) => {
            if (result.isConfirmed) {
              doDelete(id);
            }
          });
        };

        const handleDeleteMedia = (id: any) => {
          MySwal.fire({
            title: "Hapus Data",
            icon: "warning",
            showCancelButton: true,
            cancelButtonColor: "#3085d6",
            confirmButtonColor: "#d33",
            confirmButtonText: "Hapus",
          }).then((result) => {
            if (result.isConfirmed) {
              doDelete(id);
            }
          });
        };

        const [isMabesApprover, setIsMabesApprover] = React.useState(false);
        const userId = getCookiesDecrypt("uie");
        const userLevelId = getCookiesDecrypt("ulie");
        const roleId = getCookiesDecrypt("urie");
        React.useEffect(() => {
          if (userLevelId !== undefined && roleId !== undefined) {
            setIsMabesApprover(
              Number(userLevelId) === 216 && Number(roleId) === 3
            );
          }
        }, [userLevelId, roleId]);

        const [open, setOpen] = React.useState(false);

        return (
          <DropdownMenu open={open} onOpenChange={setOpen}>
            <DropdownMenuTrigger asChild>
              <Button
                size="icon"
                className="bg-transparent ring-offset-transparent hover:bg-transparent hover:ring-0 hover:ring-transparent"
              >
                <MoreVertical className="h-4 w-4 text-default-800" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="p-0 hover:text-black" align="end">
              <DropdownMenuItem
                onClick={() => {
                  setOpen(false);
                  handleView(row.original.id);
                }}
                className="p-2 border-b text-default-700 rounded-none cursor-pointer"
              >
                <Eye className="w-4 h-4 me-1.5" />
                View
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => {
                  setOpen(false); 
                  onEdit?.(row.original);
                }}
                className="p-2 border-b text-default-700 rounded-none cursor-pointer"
              >
                <SquarePen className="w-4 h-4 me-1.5" />
                Edit
              </DropdownMenuItem>

              <DropdownMenuItem
                onClick={() => {
                  setOpen(false); 
                  handleDeleteMedia(row.original.id);
                }}
                className="p-2 border-b text-destructive bg-destructive/30 focus:bg-destructive focus:text-white rounded-none"
              >
                <Trash2 className="w-4 h-4 me-1.5" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
            {/* ✅ Dialog Detail User Level */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogContent size="md" className="max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>Detail User Level</DialogTitle>
                  <DialogDescription>
                    Informasi lengkap dari user level: {detailData?.name || detailData?.aliasName}
                  </DialogDescription>
                </DialogHeader>

                {isLoadingDetail ? (
                  <div className="flex items-center justify-center py-8">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    <span className="ml-2 text-gray-600">Memuat data...</span>
                  </div>
                ) : detailData ? (
                  <Tabs defaultValue="basic" className="w-full mt-4">
                    <TabsList className="grid w-full grid-cols-3">
                      <TabsTrigger className="border border-black" value="basic">Basic Information</TabsTrigger>
                      <TabsTrigger value="menus">Menu Access</TabsTrigger>
                      <TabsTrigger value="actions">Action Access</TabsTrigger>
                    </TabsList>

                    {/* Basic Information Tab */}
                    <TabsContent value="basic" className="space-y-4 mt-4">
                      <Card>
                        <CardHeader>
                          <CardTitle>User Level Information</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-3">
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <span className="text-sm font-medium text-gray-600">ID:</span>
                              <p className="text-base font-mono">{detailData.id}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Name:</span>
                              <p className="text-base">{detailData.name || detailData.aliasName}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Alias Name:</span>
                              <p className="text-base font-mono">{detailData.aliasName}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Level Number:</span>
                              <p className="text-base">{detailData.levelNumber}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Group:</span>
                              <p className="text-base">{detailData.group || "-"}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Parent Level ID:</span>
                              <p className="text-base">{detailData.parentLevelId || "-"}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Province ID:</span>
                              <p className="text-base">{detailData.provinceId || "-"}</p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Is Approval Active:</span>
                              <Badge className={detailData.isApprovalActive ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"}>
                                {detailData.isApprovalActive ? "Yes" : "No"}
                              </Badge>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Is Active:</span>
                              <Badge className={detailData.isActive ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"}>
                                {detailData.isActive ? "Active" : "Inactive"}
                              </Badge>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Created At:</span>
                              <p className="text-sm">
                                {detailData.createdAt
                                  ? new Date(detailData.createdAt).toLocaleString("id-ID")
                                  : "-"}
                              </p>
                            </div>
                            <div>
                              <span className="text-sm font-medium text-gray-600">Updated At:</span>
                              <p className="text-sm">
                                {detailData.updatedAt
                                  ? new Date(detailData.updatedAt).toLocaleString("id-ID")
                                  : "-"}
                              </p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    </TabsContent>

                    {/* Menu Access Tab */}
                    <TabsContent value="menus" className="space-y-4 mt-4">
                      <Card>
                        <CardHeader>
                          <CardTitle>Menu Access Configuration</CardTitle>
                        </CardHeader>
                        <CardContent>
                          {menuAccesses.filter((a: UserLevelMenuAccess) => a.canAccess).length > 0 ? (
                            <div className="space-y-2 max-h-96 overflow-y-auto">
                              {menuAccesses
                                .filter((a: UserLevelMenuAccess) => a.canAccess)
                                .map((access) => {
                                  const menu = menus.find((m) => m.id === access.menuId);
                                  return (
                                    <div
                                      key={access.id}
                                      className="flex items-start gap-3 p-3 border rounded-lg hover:bg-gray-50"
                                    >
                                      <div className="flex-1">
                                        <div className="font-medium">{menu?.name || `Menu ID: ${access.menuId}`}</div>
                                        <div className="text-sm text-gray-500">{menu?.description || "-"}</div>
                                        <div className="text-xs text-gray-400 mt-1">
                                          Group: {menu?.group || "-"} • Status: {access.canAccess ? "Accessible" : "No Access"}
                                        </div>
                                      </div>
                                      <Badge className={access.canAccess ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"}>
                                        {access.canAccess ? "Accessible" : "No Access"}
                                      </Badge>
                                    </div>
                                  );
                                })}
                            </div>
                          ) : (
                            <div className="text-center py-8 text-gray-500">
                              No menu access configured
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    </TabsContent>

                    {/* Action Access Tab */}
                    <TabsContent value="actions" className="space-y-4 mt-4">
                      <Card>
                        <CardHeader>
                          <CardTitle>Action Access Configuration</CardTitle>
                        </CardHeader>
                        <CardContent>
                          {Object.keys(actionAccesses).length > 0 ? (
                            <div className="space-y-4 max-h-96 overflow-y-auto">
                              {Object.entries(actionAccesses).map(([menuId, actions]) => {
                                const menu = menus.find((m) => m.id === Number(menuId));
                                const accessibleActions = actions.filter((a: UserLevelMenuActionAccess) => a.canAccess);
                                
                                if (accessibleActions.length === 0) return null;
                                
                                return (
                                  <Card key={menuId} className="border-l-4 border-l-blue-500">
                                    <CardHeader className="pb-3">
                                      <CardTitle className="text-base">{menu?.name || `Menu ID: ${menuId}`}</CardTitle>
                                      <p className="text-sm text-gray-500">{menu?.description || "-"}</p>
                                    </CardHeader>
                                    <CardContent>
                                      <div className="space-y-2">
                                        {accessibleActions.map((actionAccess) => {
                                          const action = menuActionsMap[Number(menuId)]?.find(
                                            (a) => a.actionCode === actionAccess.actionCode
                                          );
                                          return (
                                            <div
                                              key={actionAccess.id}
                                              className="flex items-start gap-3 p-2 border rounded-lg hover:bg-gray-50"
                                            >
                                              <div className="flex-1">
                                                <div className="font-medium text-sm">
                                                  {action?.actionName || actionAccess.actionCode}
                                                </div>
                                                <div className="text-xs text-gray-500">
                                                  Code: {actionAccess.actionCode}
                                                  {action?.pathUrl && ` • Path: ${action.pathUrl}`}
                                                  {action?.httpMethod && ` • Method: ${action.httpMethod}`}
                                                </div>
                                              </div>
                                              <Badge className="bg-green-100 text-green-800">
                                                Allowed
                                              </Badge>
                                            </div>
                                          );
                                        })}
                                      </div>
                                    </CardContent>
                                  </Card>
                                );
                              })}
                            </div>
                          ) : (
                            <div className="text-center py-8 text-gray-500">
                              No action access configured
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    </TabsContent>
                  </Tabs>
                ) : (
                  <p className="text-gray-500 mt-4">Memuat data...</p>
                )}

                <div className="flex justify-end mt-5">
                  <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Tutup</Button>
                </div>
              </DialogContent>
            </Dialog>
          </DropdownMenu>
        );
      },
    },
  ];

  return columns;
};

export default useTableColumns;
