import React, { useState } from "react"

export interface ParsedLink {
  url: string
  title?: string
  text?: string
  transcript?: string
  description?: string
  author?: string
  duration?: number
  thumbnail?: string
}

interface LinkUploaderProps {
  onResult: (links: ParsedLink) => void
}

const toBase64Url = (str: string) =>
  btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")

const LinkUploader: React.FC<LinkUploaderProps> = ({ onResult }) => {
  const [url, setUrl] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleAdd = async () => {
    const raw = url.trim()
    if (!raw) return setError("Please enter a URL.")
    setError(null)
    setLoading(true)

    try {
      const key = toBase64Url(raw)
      const resp = await fetch(`/actions/fetch/${key}`)
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
      const data = (await resp.json()) as ParsedLink

      onResult(data) // emit the parsed link immediately
      setUrl("") // clear input
    } catch (err: any) {
      console.error(err)
      setError(err.message || "Failed to fetch link.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-xl shadow-lg">
      <div className="flex space-x-2">
        <input
          type="url"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleAdd()}
          disabled={loading}
          placeholder="Paste your link here…"
          className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-200 transition disabled:bg-gray-100"
        />
        <button
          onClick={handleAdd}
          disabled={loading}
          className={`w-12 h-12 flex items-center justify-center rounded-lg text-white transition ${
            loading
              ? "bg-gray-400 cursor-not-allowed"
              : "bg-learnpack hover:bg-opacity-90"
          }`}
        >
          {loading ? (
            <svg
              className="animate-spin h-5 w-5 text-white"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              />
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8v4l3.5-3.5L12 0v4a8 8 0 100 16v-4l-3.5 3.5L4 12z"
              />
            </svg>
          ) : (
            <span className="text-2xl leading-none">+</span>
          )}
        </button>
      </div>

      {error && (
        <p className="mt-3 text-sm text-red-600 bg-red-50 p-2 rounded">
          {error}
        </p>
      )}
    </div>
  )
}

export default LinkUploader
