"use client"
import Image from "next/image"
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 "./tokenfuncs"
import { Plus, User, Building2, Check } from "lucide-react"
import { useViewMode } from "@/app/app/ViewModeContext"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { cn } from "@/lib/utils"

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 [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false)
  const [token, setToken] = React.useState("")
  const [keyname, setKeyname] = React.useState("")
  const [ownerType, setOwnerType] = React.useState<"personal" | "organization">("personal")
  const [selectedOrgId, setSelectedOrgId] = React.useState<string>("")
  const { toast } = useToast()
  const { orgs } = useViewMode()

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

  const resetDialog = () => {
    setOwnerType("personal")
    setSelectedOrgId("")
    form.reset()
  }

  const handleOpenChange = (open: boolean) => {
    setIsCreateDialogOpen(open)
    if (!open) {
      resetDialog()
    }
  }

  async function onSubmit(values: z.infer<typeof formSchema>): Promise<void> {
    try {
      const organizationId = ownerType === "organization" ? selectedOrgId : undefined
      const data = await generateToken(values.keyname, organizationId || undefined)
      if (data.success) {
        setToken(data.token!)
        setKeyname(values.keyname)
        setIsCreateDialogOpen(false)
        setIsResultDialogOpen(true)
        resetDialog()
      } else {
        toast({
          variant: "destructive",
          title: "Error creating API key",
          description: data.err,
        })
      }
    } catch {
      toast({
        variant: "destructive",
        title: "Error creating API key",
        description: "An unknown error occurred",
      })
    }
  }

  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)
    }
  }

  const canSubmit = ownerType === "personal" || (ownerType === "organization" && selectedOrgId)

  return (
    <>
      <Dialog open={isCreateDialogOpen} onOpenChange={handleOpenChange}>
        <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}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <DialogHeader>
                <DialogTitle>Create new API key</DialogTitle>
                <DialogDescription>
                  Create an API key for your personal account or an organization
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-4 py-2">
                {/* Owner Selection - Toggle Buttons */}
                <div className="space-y-2">
                  <Label>Owner</Label>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => setOwnerType("personal")}
                      className={cn(
                        "flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors",
                        ownerType === "personal"
                          ? "border-primary bg-primary/10 text-primary"
                          : "border-input hover:bg-accent hover:text-accent-foreground"
                      )}
                    >
                      <User className="h-4 w-4" />
                      Personal
                      {ownerType === "personal" && <Check className="h-3 w-3 ml-1" />}
                    </button>
                    {orgs.length > 0 && (
                      <button
                        type="button"
                        onClick={() => setOwnerType("organization")}
                        className={cn(
                          "flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors",
                          ownerType === "organization"
                            ? "border-primary bg-primary/10 text-primary"
                            : "border-input hover:bg-accent hover:text-accent-foreground"
                        )}
                      >
                        <Building2 className="h-4 w-4" />
                        Organization
                        {ownerType === "organization" && <Check className="h-3 w-3 ml-1" />}
                      </button>
                    )}
                  </div>
                </div>

                {/* Organization Dropdown - only visible when organization is selected */}
                {ownerType === "organization" && orgs.length > 0 && (
                  <div className="space-y-2">
                    <Label>Organization</Label>
                    <Select value={selectedOrgId} onValueChange={setSelectedOrgId}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select an organization" />
                      </SelectTrigger>
                      <SelectContent>
                        {orgs.map(org => (
                          <SelectItem key={org.id} value={org.id}>
                            <div className="flex items-center gap-2">
                              {org.avatarUrl ? (
                                <Image
                                  src={org.avatarUrl}
                                  alt={org.name}
                                  width={20}
                                  height={20}
                                  className="h-5 w-5 rounded-full"
                                  unoptimized
                                />
                              ) : (
                                <Building2 className="h-5 w-5" />
                              )}
                              <span>{org.name}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                )}

                {/* Key Name */}
                <FormField
                  control={form.control}
                  name="keyname"
                  render={({ field }) => (
                    <div className="space-y-2">
                      <Label htmlFor="name">Name (optional)</Label>
                      <FormControl>
                        <Input id="name" {...field} />
                      </FormControl>
                    </div>
                  )}
                />
              </div>

              <DialogFooter>
                <DialogClose asChild>
                  <Button type="button" variant="outline">
                    Cancel
                  </Button>
                </DialogClose>
                <Button type="submit" disabled={!canSubmit}>
                  Create
                </Button>
              </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>
    </>
  )
}
