import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { IconAlertTriangle, IconLoader2, IconPlus } from '@tabler/icons-react'
import { api, type ResourceType } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'

/** Forma savo URL pridėti į katalogą. */
export function AddResourceForm({ onDone }: { onDone: () => void }) {
  const { t } = useLang()
  const qc = useQueryClient()
  const [type, setType] = useState<ResourceType>('wiki')
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [url, setUrl] = useState('')

  const add = useMutation({
    mutationFn: () => api.addResource({ type, name, description, url }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['catalog'] })
      onDone()
    },
  })

  const canSubmit = name.trim().length > 0 && url.trim().length > 0 && !add.isPending

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        if (canSubmit) add.mutate()
      }}
      className="mb-5 rounded-xl border border-arka-border bg-arka-surface p-4"
    >
      <h3 className="mb-3 text-sm font-semibold text-arka-text">{t('dl.addTitle')}</h3>

      <div className="grid gap-3 sm:grid-cols-2">
        <label className="text-xs text-arka-muted">
          {t('dl.fType')}
          <select
            value={type}
            onChange={(e) => setType(e.target.value as ResourceType)}
            className="mt-1 w-full rounded-lg border border-arka-border bg-arka-bg px-3 py-2 text-sm text-arka-text focus:border-arka-accent focus:outline-none"
          >
            <option value="wiki">{t('dl.wiki')}</option>
            <option value="map">{t('dl.map')}</option>
          </select>
        </label>

        <label className="text-xs text-arka-muted">
          {t('dl.fName')}
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder={t('dl.fNamePh')}
            className="mt-1 w-full rounded-lg border border-arka-border bg-arka-bg px-3 py-2 text-sm text-arka-text placeholder:text-arka-muted focus:border-arka-accent focus:outline-none"
          />
        </label>

        <label className="text-xs text-arka-muted sm:col-span-2">
          {t('dl.fUrl')}
          <input
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder={t('dl.fUrlPh')}
            inputMode="url"
            className="mt-1 w-full rounded-lg border border-arka-border bg-arka-bg px-3 py-2 text-sm text-arka-text placeholder:text-arka-muted focus:border-arka-accent focus:outline-none"
          />
        </label>

        <label className="text-xs text-arka-muted sm:col-span-2">
          {t('dl.fDesc')}
          <input
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="mt-1 w-full rounded-lg border border-arka-border bg-arka-bg px-3 py-2 text-sm text-arka-text focus:border-arka-accent focus:outline-none"
          />
        </label>
      </div>

      {add.isError && (
        <p className="mt-3 flex items-center gap-1.5 text-xs text-arka-offline">
          <IconAlertTriangle size={14} />
          {add.error instanceof Error ? add.error.message : 'Klaida / error'}
        </p>
      )}

      <div className="mt-4 flex gap-2">
        <button
          type="submit"
          disabled={!canSubmit}
          className="inline-flex items-center gap-1.5 rounded-lg bg-arka-accent px-4 py-2 text-sm font-semibold text-arka-bg transition-opacity hover:opacity-90 disabled:opacity-50"
        >
          {add.isPending ? (
            <IconLoader2 size={16} className="animate-spin" />
          ) : (
            <IconPlus size={16} />
          )}
          {add.isPending ? t('dl.adding') : t('dl.add')}
        </button>
        <button
          type="button"
          onClick={onDone}
          className="rounded-lg border border-arka-border px-4 py-2 text-sm font-medium text-arka-muted transition-colors hover:text-arka-text"
        >
          {t('dl.formCancel')}
        </button>
      </div>
    </form>
  )
}
