"use client"

import { useState } from "react"

type SyncStripeButtonProps = {
  userId: string
}

export default function SyncStripeButton({ userId }: SyncStripeButtonProps) {
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState("")
  const [isError, setIsError] = useState(false)

  async function handleSync() {
    setIsLoading(true)
    setMessage("")
    setIsError(false)

    try {
      const res = await fetch("/api/admin/sync-stripe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      })
      const data = await res.json()

      if (!res.ok) {
        throw new Error(data.error || "Failed to sync Stripe.")
      }

      setMessage(`Synced - role: ${data.role}`)
    } catch (caught) {
      setIsError(true)
      setMessage(caught instanceof Error ? caught.message : "Sync failed.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="flex flex-col gap-1">
      <button
        type="button"
        onClick={handleSync}
        disabled={isLoading}
        className="cursor-pointer bg-transparent text-left text-[13px] text-[var(--color-accent)] hover:underline disabled:cursor-not-allowed disabled:opacity-60"
      >
        {isLoading ? "Syncing..." : "Sync Stripe"}
      </button>
      {message ? (
        <span
          className={`text-[12px] ${isError ? "text-[#ef4444]" : "text-[#4ade80]"}`}
        >
          {isError ? message : `✓ ${message}`}
        </span>
      ) : null}
    </div>
  )
}
