"use client"
import { Button } from "@/components/ui/button"
import { useForm } from "react-hook-form"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Form, FormControl, FormField } from "@/components/ui/form"
import { Icons } from "@/components/icons"
import * as z from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useToast } from "@/components/ui/use-toast"
import React from "react"
import { generateToken } from "@/app/app/apikeys/tokenfuncs"
import { Plus } from "lucide-react"

const formSchema = z.object({
  keyname: z.string().max(255, { message: "Key name must be a shorter name" }),
})

export function CreateApiKeyDialog(): React.JSX.Element {
  const [isResultDialogOpen, setIsResultDialogOpen] = React.useState(false)
  const [token, setToken] = React.useState("")
  const [keyname, setKeyname] = React.useState("") // Only for dialog display purposes
  const { toast } = useToast()

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      keyname: "Secret Key",
    },
  })

  async function onSubmit(values: z.infer<typeof formSchema>): Promise<void> {
    const token: string = await generateToken(values.keyname)
    setToken(token)
    setKeyname(values.keyname)
    setIsResultDialogOpen(true)
  }

  async function copyToClipboard(data: string): Promise<void> {
    try {
      await navigator.clipboard.writeText(data)
      toast({
        description: "API Key Copied to Clipboard!",
      })
    } catch (err) {
      console.error("Failed to copy: ", err)
    }
  }

  return (
    <>
      <Dialog>
        <DialogTrigger asChild>
          <Button variant="outline" className="my-3">
            {" "}
            <Plus size={16} className="mr-1" />
            Create new API key
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[425px]">
          <Form {...form}>
            {/* eslint-disable-next-line @typescript-eslint/no-misused-promises */}
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              <FormField
                control={form.control}
                name="keyname"
                render={({ field }) => (
                  <>
                    <DialogHeader>
                      <DialogTitle>Create new API key</DialogTitle>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                      <div className="grid grid-rows-2 items-center">
                        <Label htmlFor="name" className="text-left">
                          Name (optional)
                        </Label>
                        <FormControl>
                          <Input id="name" className="col-span-3" {...field} />
                        </FormControl>
                      </div>
                    </div>
                  </>
                )}
              />

              <DialogFooter>
                <DialogClose asChild>
                  <Button type="submit">Create</Button>
                </DialogClose>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      <Dialog open={isResultDialogOpen} onOpenChange={setIsResultDialogOpen}>
        <DialogContent className="sm:max-w-[650px]">
          <DialogHeader>
            <DialogTitle>New API key created</DialogTitle>
          </DialogHeader>
          <DialogDescription>
            Please save this secret key somewhere safe and accessible. For security reasons, you
            won&apos;t be able to view it again. If you lose this secret key, you&apos;ll need to
            generate a new one.
          </DialogDescription>
          <div className="gap-1 py-2">
            <div className="grid grid-rows-2 items-center">
              <Label htmlFor="name" className="text-left">
                {keyname}
              </Label>
              <div className="flex">
                <Input
                  id="name"
                  readOnly={true}
                  defaultValue={token}
                  className="float-left flex-initial col-span-5 text-sm text-muted-foreground"
                />
                <Button
                  variant="outline"
                  size="icon"
                  className="float-right flex-none ml-2 "
                  onClick={() => {
                    void (async () => {
                      await copyToClipboard(token)
                    })()
                  }}
                >
                  <Icons.copy />
                </Button>
              </div>
            </div>
          </div>
          <div className="text-sm overflow-x-auto text-muted-foreground">
            <p>
              To add this key to your environment, you can add the following line to your
              <br />
              <code> ~/.zshrc</code> or <code>~/.bashrc</code>:
            </p>
            <div className="flex mt-4">
              <div className="float-left flex-initial col-span-5 p-2 bg-gray-100 rounded-md text-sm overflow-x-auto flex items-center justify-between">
                <pre>
                  <code>export CODEFLASH_API_KEY=&apos;{token}&apos;</code>
                </pre>
              </div>
              <Button
                variant="outline"
                size="icon"
                className="float-right flex-none col-span-1 ml-2 "
                onClick={() => {
                  void (async () => {
                    await copyToClipboard(`export CODEFLASH_API_KEY='${token}'`)
                  })()
                }}
              >
                <Icons.copy />
              </Button>
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <form
                onSubmit={(event) => {
                  setIsResultDialogOpen(false)
                  event.preventDefault()
                }}
              >
                <Button type="submit">Done</Button>
              </form>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
