"use client"

import * as React from "react"
import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { DateDisplay } from "./DateDisplay"
import { CogIcon, DotIcon } from "../stories/Icon.stories"
import "../../../../app/global.css"

export const data: PortServer[] = [
  {
    id: "m5gr84i9",
    info: "800 Cobas Status",
    date: new Date("2023-10-30 15:26:04"),
    type: "status",
  },
  {
    id: "3u1reuv4",
    info: "Incoming 800 Cobas Result",
    date: new Date("2023-10-30 15:26:04"),
    type: "result",
  },
  {
    id: "derv1ws0",
    info: "Incoming 800 Cobas Query",
    date: new Date("2023-10-30 15:26:04"),
    type: "query",
  }
]

export type PortServer = {
  id: string
  info: string
  date: Date
  type : 'status' | 'result' | 'query'
}

export const columns: ColumnDef<PortServer>[] = [
    {
        accessorKey: "date",
        header: "Date",
        cell: ({ row }) => {
            const date = new Date(row.getValue("date"))
            return(
                <div className="text-[#637381] bg-[#919EAB29] rounded-md border-4 border-[#919EAB29]">
                    <DateDisplay date={date}/>
                </div>
            )
        }
      },
  {
    accessorKey: "info",
    header: "Info",
    cell: ({ row }) => (
      <div className="capitalize">{row.getValue("info")}</div>
    ),
  },
  {
    id: "actions",
    header:() => {
        return(
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                    <CogIcon />
                </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                    <DropdownMenuItem
                        onClick={() => {}}
                    >
                        <span>Change Password</span>
                    </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
        )
    },
    enableHiding: false,
    cell: ({ row }) => {
        const type = row.original
        return ( 
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                    <DotIcon />
                </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                {
                    type.type?.toLowerCase() == 'status' ? (
                    <DropdownMenuItem
                        onClick={() => {}}
                    >
                        Info
                    </DropdownMenuItem>
                    ) : ''
                }
                {
                    type.type?.toLowerCase() == 'result' ? (
                    <>
                        <DropdownMenuItem onClick={() => {}} >
                        Raw Data
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => {}}>
                        Result
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => {}}>
                        Export
                        </DropdownMenuItem>
                    </> 
                    ) : ''
                }
                {
                    type.type?.toLowerCase() == 'query' ? (
                    <>
                        <DropdownMenuItem onClick={() => {}}>
                        Raw Data
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => {}}>
                        Query Response
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => {}}>
                        Export
                        </DropdownMenuItem>
                    </>
                    ) : ''
                }
                </DropdownMenuContent>
            </DropdownMenu>
        )}
  },
]

export interface DataTableProps {
    data: PortServer[]; // Properti untuk data tabel
    columns: ColumnDef<PortServer>[];
}

export const DataTableDemo = ({
    data,
    columns,
}: DataTableProps) => {
  const [sorting, setSorting] = React.useState<SortingState>([])
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    []
  )
  const [columnVisibility, setColumnVisibility] =
    React.useState<VisibilityState>({})
  const [rowSelection, setRowSelection] = React.useState({})

  const table = useReactTable({
    data,
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
    },
  })

  return (
    <div className="w-full">
      <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}>
                      {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>
  )
}
