"use client"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import ReactMarkdown from "react-markdown"
import { DeleteApiKeyButton } from "@/app/app/apikeys/delete-api-key-button"
import React, { type JSX } from "react"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { type cf_api_keys } from "@prisma/client"
import { deleteAPIKey } from "@/app/app/apikeys/tokenfuncs"
import { Badge } from "@/components/ui/badge"

export function ApiKeyTable({ apiKeys }: { apiKeys: cf_api_keys[] }): JSX.Element {
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
  const [rowToDelete, setRowToDelete] = React.useState<cf_api_keys | null>(null)
  return (
    <>
      <Table className="mt-6">
        <TableHeader>
          <TableRow>
            <TableHead className="h-8">Name</TableHead>
            <TableHead className="h-8">Key</TableHead>
            <TableHead className="h-8">Created</TableHead>
            <TableHead className="h-8">Last Used</TableHead>
            <TableHead className="h-8"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {apiKeys.map((key, index) => (
            <TableRow key={index}>
              <TableCell className="py-0">{key.name}</TableCell>
              {/* Display the key using a Markdown component */}
              <TableCell className="py-0">
                <div className="inline-flex items-center gap-2">
                  <ReactMarkdown>{`\`\`\`cf-${"*".repeat(3)}${key.suffix}\`\`\``}</ReactMarkdown>
                  {key.tier === "pro" && <Badge style={{ backgroundColor: "#FFC043" }}>Pro</Badge>}
                </div>
              </TableCell>
              <TableCell className="py-0" suppressHydrationWarning>
                {key.created_at.toLocaleString()}
              </TableCell>
              <TableCell className="py-0" suppressHydrationWarning>
                {key.last_used != null ? key.last_used.toLocaleString() : "Never"}
              </TableCell>
              <TableCell className="py-0">
                <DeleteApiKeyButton
                  deleteDialog={setDeleteDialogOpen}
                  rowToDelete={key}
                  setRowTodelete={setRowToDelete}
                />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader>
            <DialogTitle>Delete secret key</DialogTitle>
          </DialogHeader>
          <DialogDescription>
            This API key will immediately be disabled. API requests made using this key will be
            rejected, which could cause any systems still depending on it to break. Once deleted,
            you&apos;ll no longer be able to view or modify this API key.
          </DialogDescription>
          <div className="gap-4 py-4">
            <div className="grid grid-rows-2 items-center">
              <Label htmlFor="name" className="text-left">
                {rowToDelete?.name + " - cf-***" + rowToDelete?.suffix}
              </Label>
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <>
                <Button
                  onClick={() => {
                    setRowToDelete(null)
                    setDeleteDialogOpen(false)
                  }}
                >
                  Cancel
                </Button>
                <form
                  onSubmit={(event): void => {
                    void (async (): Promise<void> => {
                      event.preventDefault()
                      if (rowToDelete == null) {
                        console.log("rowToDelete is null!!")
                        return
                      }
                      await deleteAPIKey(rowToDelete?.id)
                      setRowToDelete(null)
                      setDeleteDialogOpen(false)
                    })()
                  }}
                >
                  <Button type="submit" variant="destructive">
                    Delete Key
                  </Button>
                </form>
              </>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
