import React, { useState } from "react"
import { useTranslation } from "react-i18next"

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 { t } = useTranslation()
  const [url, setUrl] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [show404Help, setShow404Help] = useState(false)

  const handleAdd = async () => {
    const raw = url.trim()
    if (!raw) {
      return setError(t("uploader.youtube.enterUrl"))
    }

    // Validate YouTube URL format
    const ytRegex =
      /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)[A-Za-z0-9_-]{11}/
    if (!ytRegex.test(raw)) {
      return setError(t("uploader.youtube.invalidUrl"))
    }

    setError(null)
    setLoading(true)

    try {
      const key = toBase64Url(raw)
      const endpoint = `/actions/fetch/${key}`
      const resp = await fetch(endpoint)

      if (!resp.ok) {
        // Handle specific error cases
        if (resp.status === 404) {
          setShow404Help(true)
          throw new Error(t("uploader.youtube.notAvailable"))
        }
        if (resp.status === 429) {
          const retryData = await resp.json()
          throw new Error(
            retryData.error || t("uploader.youtube.tooManyRequests")
          )
        }
        if (resp.status === 500) {
          const errorData = await resp.json()
          throw new Error(
            errorData.error || t("uploader.youtube.serviceUnavailable")
          )
        }
        throw new Error(t("uploader.youtube.fetchError"))
      }

      const data = (await resp.json()) as ParsedLink

      onResult(data) // emit the parsed link immediately
      setUrl("") // clear input
      setShow404Help(false)
    } catch (err: unknown) {
      console.error(err)
      const message = err instanceof Error ? err.message : t("uploader.youtube.fetchError")
      setError(message)
    } 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={t("uploader.youtube.placeholder")}
          pattern="(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)[A-Za-z0-9_-]{11}"
          title="Please enter a valid YouTube URL (youtube.com/watch?v=... or youtu.be/...)"
          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 && (
        <div className="mt-3 text-sm bg-red-50 p-2 rounded">
          <p className="text-red-600">{error}</p>
          {show404Help && (
            <div className="mt-2 text-gray-700">
              <p>{t("uploader.youtube.notAvailableReasons.title")}</p>
              <ul className="list-disc pl-5 mt-1">
                <li>{t("uploader.youtube.notAvailableReasons.captions")}</li>
                <li>{t("uploader.youtube.notAvailableReasons.privacy")}</li>
                <li>{t("uploader.youtube.notAvailableReasons.region")}</li>
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default LinkUploader
