import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { useState } from "react"

function getSdk() {
  const sdk = (window as any).__sdk
  if (!sdk) throw new Error("SDK not available. Try refreshing the page.")
  return sdk
}

const ProductImageUrlPaste = ({ data: product }: any) => {
  const [url, setUrl] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  const currentImages = product.images || []

  const reloadPage = () => window.location.reload()

  const handleAddImage = async () => {
    const trimmedUrl = url.trim()
    if (!trimmedUrl) return

    setLoading(true)
    setError("")

    try {
      const existingImages = currentImages.map((img: any) => ({
        id: img.id,
        url: img.url,
      }))

      const sdk = getSdk()
      await sdk.admin.product.update(product.id, {
        images: [...existingImages, { url: trimmedUrl }],
      })

      reloadPage()
    } catch (e: any) {
      setError(e.message || "Failed to add image")
    } finally {
      setLoading(false)
    }
  }

  const handleRemoveImage = async (imageId: string) => {
    setLoading(true)
    setError("")

    try {
      const remainingImages = currentImages
        .filter((img: any) => img.id !== imageId)
        .map((img: any) => ({ id: img.id, url: img.url }))

      const sdk = getSdk()
      await sdk.admin.product.update(product.id, { images: remainingImages })

      reloadPage()
    } catch (e: any) {
      setError(e.message || "Failed to remove image")
    } finally {
      setLoading(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") handleAddImage()
  }

  return (
    <div className="flex flex-col gap-y-4 p-4">
      <h3 className="text-lg font-medium">Add Image from URL</h3>

      <div className="flex gap-x-2">
        <input
          type="url"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="https://example.com/image.jpg"
          className="flex-1 border rounded-md px-3 py-2 text-sm"
          disabled={loading}
        />
        <button
          onClick={handleAddImage}
          disabled={loading || !url.trim()}
          className="bg-black text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50 hover:bg-gray-800 transition-colors flex-shrink-0"
        >
          {loading ? "Adding..." : "Add Image"}
        </button>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-md p-3">
          {error}
        </div>
      )}

      {currentImages.length > 0 && (
        <div>
          <p className="text-sm text-gray-500 mb-2">
            Current images ({currentImages.length})
          </p>
          <div className="flex flex-wrap gap-2">
            {currentImages.map((image: any) => (
              <div key={image.id} className="relative group">
                <img
                  src={image.url}
                  alt=""
                  className="w-20 h-20 object-cover rounded-md border"
                />
                <button
                  onClick={() => handleRemoveImage(image.id)}
                  disabled={loading}
                  className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
                  title="Remove image"
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

export const config = defineWidgetConfig({
  zone: "product.details.after",
})

export default ProductImageUrlPaste
