"use client"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import ReactMarkdown from "react-markdown"
import { DeleteApiKeyButton } from "./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 { deleteAPIKey } from "./tokenfuncs"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/components/ui/use-toast"
import { Building2, User } from "lucide-react"
import Image from "next/image"

export interface ApiKeyWithOrg {
  id: number
  key: string
  suffix: string
  name: string
  created_at: Date
  last_used: Date | null
  user_id: string | null
  organization_id: string | null
  tier: string | null
  organization?: {
    id: string
    name: string
  } | null
  user?: {
    user_id: string
    github_username: string
    name: string | null
    email: string | null
  } | null
}

export function ApiKeyTable({
  apiKeys,
  vscodeKeyName,
  currentUserId,
}: {
  apiKeys: ApiKeyWithOrg[]
  vscodeKeyName: string
  currentUserId: string
}): JSX.Element {
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false)
  const [rowToDelete, setRowToDelete] = React.useState<ApiKeyWithOrg | null>(null)
  const { toast } = useToast()

  return (
    <>
      <Table className="mt-6">
        <TableHeader>
          <TableRow>
            <TableHead className="h-8">Name</TableHead>
            <TableHead className="h-8">Owner</TableHead>
            <TableHead className="h-8">Key</TableHead>
            <TableHead className="h-8">Created</TableHead>
            <TableHead className="h-8">Last Used</TableHead>
            <TableHead className="h-8">Created by</TableHead>
            <TableHead className="h-8"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {apiKeys.map((key, index) => {
            const isVSCodeKey = key.name === vscodeKeyName
            const isOrgKey = !!key.organization
            return (
              <TableRow key={index}>
                <TableCell className="py-2">
                  {isVSCodeKey ? (
                    <div className="flex items-center gap-2">
                      <span className="font-medium">CLI Key</span>
                      <Badge
                        variant="outline"
                        className="text-xs bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"
                      >
                        Protected
                      </Badge>
                    </div>
                  ) : (
                    <span>{key.name}</span>
                  )}
                </TableCell>
                <TableCell className="py-2">
                  {isOrgKey ? (
                    <div className="flex items-center gap-2">
                      <Building2 className="h-4 w-4 text-muted-foreground" />
                      <span className="text-sm">{key.organization!.name}</span>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2">
                      <User className="h-4 w-4 text-muted-foreground" />
                      <span className="text-sm">Personal</span>
                    </div>
                  )}
                </TableCell>
                {/* Display the key using a Markdown component */}
                <TableCell className="py-2">
                  <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-2" suppressHydrationWarning>
                  {key.created_at.toLocaleString()}
                </TableCell>
                <TableCell className="py-2" suppressHydrationWarning>
                  {key.last_used != null ? key.last_used.toLocaleString() : "Never"}
                </TableCell>
                <TableCell className="py-2">
                  {key.user ? (
                    <div className="flex items-center gap-2">
                      <Image
                        src={`https://github.com/${key.user.github_username}.png`}
                        alt={key.user.github_username}
                        width={24}
                        height={24}
                        className="rounded-full"
                      />
                      <span className="text-sm">
                        {key.user.user_id === currentUserId
                          ? "Me"
                          : key.user.name || key.user.email || key.user.github_username}
                      </span>
                    </div>
                  ) : (
                    <span className="text-sm text-muted-foreground">Unknown</span>
                  )}
                </TableCell>
                <TableCell className="py-2">
                  {!isVSCodeKey && key.user?.user_id === currentUserId && (
                    <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>
              {rowToDelete?.organization && (
                <div className="flex items-center gap-2 mt-2 text-sm text-muted-foreground">
                  <Building2 className="h-4 w-4" />
                  <span>Organization: {rowToDelete.organization.name}</span>
                </div>
              )}
            </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
                      }
                      try {
                        await deleteAPIKey(rowToDelete.id)
                        setRowToDelete(null)
                        setDeleteDialogOpen(false)
                        toast({
                          title: "API Key Deleted",
                          description: "The API key has been successfully deleted.",
                        })
                      } catch (error) {
                        console.error("Error deleting API key:", error)
                        setDeleteDialogOpen(false)
                        toast({
                          title: "Deletion Failed",
                          description:
                            error instanceof Error
                              ? error.message
                              : "Failed to delete API key. Please try again.",
                          variant: "destructive",
                        })
                      }
                    })()
                  }}
                >
                  <Button type="submit" variant="destructive">
                    Delete Key
                  </Button>
                </form>
              </>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
