import React, { useEffect, useState } from 'react'

function Widget({ label, value }) {
  return (
    <div className="rounded-xl border border-gray-700 bg-gray-900/70 p-4 shadow-lg transition hover:scale-[1.02]">
      <p className="text-xs uppercase tracking-wide text-gray-400">{label}</p>
      <p className="mt-2 text-2xl font-semibold text-white">{value}</p>
    </div>
  )
}

export default function CreatorAnalytics({ isCreator }) {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    async function load() {
      try {
        const response = await window.axios.get('/api/dashboard/analytics')
        if (!cancelled) {
          setData(response.data?.data || null)
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    load()

    return () => {
      cancelled = true
    }
  }, [])

  return (
    <section className="rounded-xl border border-gray-700 bg-gray-800 p-5 shadow-lg">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-semibold">Creator Analytics</h2>
        <a href="/creator/analytics" className="text-xs text-cyan-300 hover:text-cyan-200">
          Open analytics
        </a>
      </div>

      {loading ? <p className="text-sm text-gray-400">Loading analytics...</p> : null}

      {!loading && !isCreator && !data?.is_creator ? (
        <div className="rounded-xl border border-gray-700 bg-gray-900/60 p-4 text-sm text-gray-300">
          Upload your first artwork to unlock creator-only insights.
        </div>
      ) : null}

      {!loading && (isCreator || data?.is_creator) ? (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <Widget label="Total Artworks" value={data?.total_artworks ?? 0} />
          <Widget label="Total Story Views" value={data?.total_story_views ?? 0} />
          <Widget label="Total Followers" value={data?.total_followers ?? 0} />
          <Widget label="Total Likes" value={data?.total_likes ?? 0} />
        </div>
      ) : null}
    </section>
  )
}
