"use client";

import * as React from "react";
//import Flag from "react-flagpack";
import {
  ContextMenu,
  ContextMenuCheckboxItem,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuLabel,
  ContextMenuRadioGroup,
  ContextMenuRadioItem,
  ContextMenuSeparator,
  ContextMenuShortcut,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuTrigger,
} from "@/components/ui/context-menu";
import {
  CaretSortIcon,
  ChevronDownIcon,
  DotsHorizontalIcon,
} from "@radix-ui/react-icons";
import {
  TableRow,
  TableBody,
  TableHeader,
  TableCell,
  Table,
  TableHead,
} from "./components/ui/table";
import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useToast } from "./hooks/use-toast";
import DashSidebar from "./components/sidebar";
import { SidebarTrigger } from "./components/ui/sidebar";
import { ToastAction } from "@/components/ui/toast";
//import Topbar from "./topbar";

type Angel = {
  agent_id: string;
  country: string;
  ip: string;
  system: string;
  name: string;
  process: string;
  //activity: boolean;
  version: string;
};

export const agents: Angel[] = [
  {
    agent_id: "728ed52f",
    country: "nl-NL",
    ip: "193.173.216.118",
    system: "Windows 11 Home x64",
    name: "aeterna@pterodactyl",
    process: "9620 \\ C:\\ProgramData\\Prefetch\\na.exe",
    //activity: true,
    version: "0.3.4",
  },
  {
    agent_id: "b93ecf71",
    country: "us-US",
    ip: "192.168.1.101",
    system: "Windows 10 Pro x64",
    name: "lucas@dinosaur",
    process: "8456 \\ C:\\Program Files\\Example\\app.exe",
    version: "0.1.2",
  },
  {
    agent_id: "a56d90c2",
    country: "gb-GB",
    ip: "172.16.254.1",
    system: "Windows 11 Home x64",
    name: "mia@pterodactyl",
    process: "3045 \\ C:\\Users\\Mia\\Documents\\test.exe",
    version: "0.5.0",
  },
  {
    agent_id: "c2f1d3a8",
    country: "fr-FR",
    ip: "10.0.0.5",
    system: "Windows 10 Home x64",
    name: "noah@velociraptor",
    process: "5732 \\ C:\\ProgramData\\Example\\example.exe",
    version: "0.2.8",
  },
  {
    agent_id: "e58b60a4",
    country: "de-DE",
    ip: "198.51.100.1",
    system: "Windows 11 Pro x64",
    name: "sophia@triceratops",
    process: "1903 \\ C:\\Apps\\Example\\launcher.exe",
    version: "0.4.3",
  },
  {
    agent_id: "d75a4e0c",
    country: "it-IT",
    ip: "203.0.113.5",
    system: "Windows 10 Home x64",
    name: "liam@raptor",
    process: "6821 \\ C:\\Program Files\\App\\run.exe",
    version: "0.3.9",
  },
  {
    agent_id: "f97cbe2e",
    country: "es-ES",
    ip: "192.0.2.1",
    system: "Windows 10 Pro x64",
    name: "ava@dragon",
    process: "4593 \\ C:\\Users\\Ava\\Downloads\\program.exe",
    version: "0.6.1",
  },
  {
    agent_id: "7bcfd1c3",
    country: "jp-JP",
    ip: "255.255.255.255",
    system: "Windows 11 Home x64",
    name: "haruki@bird",
    process: "3248 \\ C:\\Program Files (x86)\\Sample\\sample.exe",
    version: "0.1.0",
  },
  {
    agent_id: "1e6f0a42",
    country: "ca-CA",
    ip: "203.0.113.10",
    system: "Windows 10 Home x64",
    name: "emma@parrot",
    process: "8345 \\ C:\\ProgramData\\Apps\\utility.exe",
    version: "0.4.2",
  },
  {
    agent_id: "a39f0b77",
    country: "au-AU",
    ip: "192.0.2.50",
    system: "Windows 11 Pro x64",
    name: "oliver@ostrich",
    process: "4926 \\ C:\\Program Files\\Example\\app.exe",
    version: "0.2.5",
  },
  {
    agent_id: "62a1c7b8",
    country: "br-BR",
    ip: "192.168.0.15",
    system: "Windows 10 Pro x64",
    name: "isabella@eagle",
    process: "1864 \\ C:\\Users\\Isabella\\Desktop\\test.exe",
    version: "0.3.7",
  },
];

/*export function resolve_country(country: string) {
  return <CountryFlag countryCode={country.split("-")[1]} />;
}*/

export const columns: ColumnDef<Angel>[] = [
  {
    accessorKey: "agent_id",
    header: "Agent Identifier",
    cell: ({ row }) => (
      <div className="uppercase">{row.getValue("agent_id")}</div>
    ),
  },
  {
    accessorKey: "country",
    header: "Country",
    //cell: ({ row }) => <div>{resolve_country(row.getValue("country"))}</div>,
    cell: ({ row }) => <div>{row.getValue("country")}</div>,
  },
  {
    accessorKey: "ip",
    header: "IPv4",
    cell: ({ row }) => <div>{row.getValue("ip")}</div>,
  },
  {
    accessorKey: "system",
    header: "Operating System",
    cell: ({ row }) => <div>{row.getValue("system")}</div>,
  },
  {
    accessorKey: "name",
    header: "username@hostname",
    cell: ({ row }) => <div>{row.getValue("name")}</div>,
  },
  {
    accessorKey: "process",
    header: "PID  Process",
    cell: ({ row }) => <div>{row.getValue("process")}</div>,
  },
  /*{
    accessorKey: "activity",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Activity
          <CaretSortIcon className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => (
      <div>{(row.getValue("activity") === true && "Active") ?? "Inactive"}</div>
    ),
  },*/
  {
    accessorKey: "version",
    header: "Angel Version",
    cell: ({ row }) => <div>{row.getValue("version")}</div>,
  },
  {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const agent = row.original;

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <DotsHorizontalIcon className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem
              onClick={() => navigator.clipboard.writeText(agent.agent_id)}
            >
              Copy agent ID
            </DropdownMenuItem>
            <DropdownMenuItem>Agent overview</DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem>View wallets</DropdownMenuItem>
            <DropdownMenuItem>View network</DropdownMenuItem>
            <DropdownMenuItem>View apps</DropdownMenuItem>
            <DropdownMenuItem>View browser</DropdownMenuItem>
            <DropdownMenuItem>View system info</DropdownMenuItem>
            <DropdownMenuItem>View games</DropdownMenuItem>
            <DropdownMenuItem>View messengers</DropdownMenuItem>
            <DropdownMenuItem>View files</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];

/*export function DataMeow() {
  const chunkArray = (array: Angel[], chunkSize: number): Angel[][] => {
    const chunks: Angel[][] = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize));
    }
    return chunks;
  };

  const chunks = chunkArray(agents, 5);

  return (
    <div>
      {chunks.map((chunk, index) => (
        <div key={index}>
          <DataTable tablemeow={chunk} />
        </div>
      ))}
    </div>
  );
}*/

/*interface DataTableProps {
  tablemeow: Angel[];
}*/

//export function DataTable({ tablemeow }: DataTableProps) {
export function DataTable() {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    [],
  );
  const [columnVisibility, setColumnVisibility] =
    React.useState<VisibilityState>({});
  const [rowSelection, setRowSelection] = React.useState({});

  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(0);

  const table = useReactTable({
    data: agents, // tablemeow
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    //manualPagination: false,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
      pagination: { pageSize, pageIndex },
    },
  });

  const startRow =
    table.getState().pagination.pageIndex *
      table.getState().pagination.pageSize +
    1;
  const endRow = Math.min(
    (table.getState().pagination.pageIndex + 1) *
      table.getState().pagination.pageSize,
    table.getFilteredRowModel().rows.length,
  );

  return (
    <div className="w-full h-full">
      <div className="flex flex-wrap break-all items-center py-4">
        <Input
          placeholder="Filter by name..."
          value={(table.getColumn("name")?.getFilterValue() as string) ?? ""}
          onChange={(event) =>
            table.getColumn("name")?.setFilterValue(event.target.value)
          }
          className="max-w-sm"
        />
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="ml-auto">
              Columns <ChevronDownIcon className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {table
              .getAllColumns()
              .filter((column) => column.getCanHide())
              .map((column) => {
                return (
                  <DropdownMenuCheckboxItem
                    key={column.id}
                    className="capitalize"
                    checked={column.getIsVisible()}
                    onCheckedChange={(value) =>
                      column.toggleVisibility(!!value)
                    }
                  >
                    {column.id}
                  </DropdownMenuCheckboxItem>
                );
              })}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => {
                  return (
                    <TableHead key={header.id}>
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                            header.column.columnDef.header,
                            header.getContext(),
                          )}
                    </TableHead>
                  );
                })}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id} className="break-all flex-wrap">
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24 text-center"
                >
                  No results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      <div className="flex items-center justify-end space-x-2 py-4">
        <div className="flex-1 text-sm text-muted-foreground">
          Showing {startRow}-{endRow} of{" "}
          {table.getFilteredRowModel().rows.length} rows.
        </div>
        <div className="space-x-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              if (table.getCanPreviousPage()) {
                setPageIndex((prev) => prev - 1);
              }
            }}
            disabled={!table.getCanPreviousPage()}
          >
            Previous
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              if (table.getCanNextPage()) {
                setPageIndex((prev) => prev + 1);
              }
            }}
            disabled={!table.getCanNextPage()}
          >
            Next
          </Button>
        </div>
      </div>
    </div>
  );
}

function Dashboard() {
  const [time, setTime] = React.useState("");

  React.useEffect(() => {
    const updateTime = () => {
      const currentTime = new Date().toLocaleTimeString();
      setTime(currentTime);
    };

    updateTime();

    const intervalId = setInterval(updateTime, 1000);

    return () => clearInterval(intervalId);
  }, []);

  const { toast } = useToast();

  return (
    <>
      <div className="grid grid-cols-[auto_1fr] grid-rows-[auto_1fr] w-full">
        <DashSidebar />

        <div className="fixed top-0 left-0 w-full flex items-center bg-gray-100 p-1 border-b border-gray-400">
          <div className="flex items-center space-x-2">
            <img
              src="/angel.png"
              alt="Logo"
              className="w-8 h-8 object-cover rounded-md"
            />
          </div>

          <div className="flex-1 text-center text-sm">{time}</div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Avatar className="ml-auto w-8 h-8 text-sm">
                <AvatarImage src="/kiss.jpg" alt="@0xkiss" />
                <AvatarFallback>meow</AvatarFallback>
              </Avatar>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56">
              <DropdownMenuLabel>My Account</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuGroup>
                <DropdownMenuItem>Profile</DropdownMenuItem>
                <DropdownMenuItem>Billing</DropdownMenuItem>
                <DropdownMenuItem>Settings</DropdownMenuItem>
              </DropdownMenuGroup>
              <DropdownMenuSeparator />
              <DropdownMenuItem>Leaderboard</DropdownMenuItem>
              <DropdownMenuItem>GitHub</DropdownMenuItem>
              <DropdownMenuItem>Support</DropdownMenuItem>
              <DropdownMenuItem disabled>API</DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem>Log out</DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        <div className="p-4">
          <div className="w-full h-full mt-5">
            <DataTable />
          </div>
        </div>
      </div>
      <SidebarTrigger className="absolute bottom-0 right-0" />
    </>
  );
}

export default Dashboard;
