'use client'

import type * as React from 'react'
import { Button } from '@admin/components/ui/button'
import { InputGroup, InputGroupInput } from '@admin/components/ui/input-group'
import { TrashIcon } from 'lucide-react'

export interface LinkMainProps {
  url: string
  setUrl: React.Dispatch<React.SetStateAction<string | null>>
  setLink: () => void
  removeLink: () => void
}

export function LinkMain({ url, setUrl, setLink, removeLink }: LinkMainProps) {
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      event.preventDefault()
      setLink()
    }
  }

  return (
    <div className="flex min-w-max flex-col items-center gap-2">
      <InputGroup className="h-9 min-w-64">
        <InputGroupInput
          type="url"
          placeholder="Paste a link..."
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          onKeyDown={handleKeyDown}
          autoFocus
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
        />
      </InputGroup>

      <div className="flex w-full items-center gap-1">
        {url && (
          <Button type="button" onClick={removeLink} title="Remove link" variant="destructive">
            <TrashIcon />
          </Button>
        )}

        <Button
          type="button"
          onClick={setLink}
          title="Apply link"
          variant="default"
          className="flex-1"
        >
          Insert
        </Button>
      </div>
    </div>
  )
}
