// Custom Studio Tool: Analytics Dashboard
// Demonstrates: definePlugin, tool API, Studio UI components, React integration

import { ChartUpwardIcon } from "@sanity/icons"
import { Box, Card, Flex, Heading, Stack, Text } from "@sanity/ui"
import { useEffect, useState } from "react"
import { definePlugin, type Tool } from "sanity"

// Component that renders the tool's UI
function AnalyticsDashboard() {
  const [stats, setStats] = useState<{
    documents: number
    drafts: number
    published: number
  } | null>(null)

  useEffect(() => {
    // In a real tool, you'd fetch data from Sanity or an external API
    // This demonstrates the pattern
    setStats({ documents: 142, drafts: 12, published: 130 })
  }, [])

  if (!stats) {
    return (
      <Card padding={4}>
        <Text>Loading...</Text>
      </Card>
    )
  }

  return (
    <Box padding={4}>
      <Stack space={4}>
        <Heading as="h1" size={3}>
          Analytics Dashboard
        </Heading>
        <Flex gap={4} wrap="wrap">
          <StatCard label="Total Documents" value={stats.documents} />
          <StatCard label="Drafts" value={stats.drafts} />
          <StatCard label="Published" value={stats.published} />
        </Flex>
      </Stack>
    </Box>
  )
}

function StatCard({ label, value }: { label: string; value: number }) {
  return (
    <Card padding={4} radius={2} shadow={1} style={{ minWidth: 200 }}>
      <Stack space={3}>
        <Text size={1} muted>
          {label}
        </Text>
        <Heading size={4}>{value}</Heading>
      </Stack>
    </Card>
  )
}

// Define the tool using Sanity's plugin API
const analyticsTool: Tool = {
  name: "analytics",
  title: "Analytics",
  icon: ChartUpwardIcon,
  component: AnalyticsDashboard,
}

// Export as a Sanity plugin
export const analyticsPlugin = definePlugin({
  name: "sanity-plugin-analytics",
  tools: [analyticsTool],
})

// Usage in sanity.config.ts:
// import { analyticsPlugin } from "./plugins/analytics"
// export default defineConfig({
//   plugins: [analyticsPlugin()],
// })
