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

function Widget({ label, value }) {
  return (
    <div className="rounded-2xl border border-white/8 bg-white/[0.04] p-4 shadow-lg transition hover:-translate-y-0.5 hover:border-white/15 hover:bg-white/[0.06]">
      <p className="text-[11px] uppercase tracking-[0.16em] text-slate-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-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.82))] p-5 shadow-[0_24px_90px_rgba(2,8,23,0.32)]">
      <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <p className="text-[11px] uppercase tracking-[0.24em] text-sky-200/70">Creator space</p>
          <h2 className="mt-2 text-xl font-semibold text-white">Creator Analytics</h2>
          <p className="mt-2 max-w-md text-sm leading-6 text-slate-300">Snapshot metrics for the work you publish and the audience building around it.</p>
        </div>
        <a href="/creator/analytics" className="inline-flex items-center justify-center gap-2 rounded-full border border-sky-400/25 bg-sky-400/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-400/15 sm:justify-start">
          Open analytics
          <i className="fa-solid fa-arrow-right text-[10px]" />
        </a>
      </div>

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

      {!loading && !isCreator && !data?.is_creator ? (
        <div className="rounded-2xl border border-white/8 bg-white/[0.04] p-4 text-sm text-slate-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>
  )
}
