import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { posts as postsAPI, categories as categoriesAPI } from '../../utils/api'
import { FileText, FolderOpen, Eye, TrendingUp } from 'lucide-react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

export default function AdminDashboard() {
  const [stats, setStats] = useState({
    totalPosts: 0,
    publishedPosts: 0,
    draftPosts: 0,
    totalViews: 0,
    totalCategories: 0,
  })
  const [recentPosts, setRecentPosts] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [postsRes, catsRes] = await Promise.all([
          postsAPI.getAllAdmin(),
          categoriesAPI.getAll(),
        ])

        const allPosts = postsRes.data
        setRecentPosts(allPosts.slice(0, 5))

        const stats = {
          totalPosts: allPosts.length,
          publishedPosts: allPosts.filter(p => p.status === 'published').length,
          draftPosts: allPosts.filter(p => p.status === 'draft').length,
          totalViews: allPosts.reduce((sum, p) => sum + (p.view_count || 0), 0),
          totalCategories: catsRes.data.length,
        }
        setStats(stats)
      } catch (err) {
        console.error('Failed to fetch dashboard data:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [])

  const chartData = [
    { name: 'Published', value: stats.publishedPosts },
    { name: 'Draft', value: stats.draftPosts },
  ]

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    )
  }

  return (
    <div className="p-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-gray-600 mt-2">Welcome to CardingCentral Admin</p>
      </div>

      {/* Stats Grid */}
      <div className="grid md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
        {[
          { icon: FileText, label: 'Total Posts', value: stats.totalPosts, color: 'blue' },
          { icon: TrendingUp, label: 'Published', value: stats.publishedPosts, color: 'green' },
          { icon: FileText, label: 'Drafts', value: stats.draftPosts, color: 'yellow' },
          { icon: Eye, label: 'Total Views', value: stats.totalViews, color: 'purple' },
          { icon: FolderOpen, label: 'Categories', value: stats.totalCategories, color: 'orange' },
        ].map((stat, i) => {
          const Icon = stat.icon
          const colorClass = {
            blue: 'bg-blue-50 text-blue-600',
            green: 'bg-green-50 text-green-600',
            yellow: 'bg-yellow-50 text-yellow-600',
            purple: 'bg-purple-50 text-purple-600',
            orange: 'bg-orange-50 text-orange-600',
          }[stat.color]

          return (
            <div key={i} className="bg-white rounded-lg p-6 shadow-md">
              <div className={`w-12 h-12 rounded-lg ${colorClass} flex items-center justify-center mb-4`}>
                <Icon size={24} />
              </div>
              <p className="text-gray-600 text-sm font-medium">{stat.label}</p>
              <p className="text-3xl font-bold text-gray-900">{stat.value}</p>
            </div>
          )
        })}
      </div>

      <div className="grid lg:grid-cols-3 gap-8 mb-8">
        {/* Chart */}
        <div className="lg:col-span-2 bg-white rounded-lg p-6 shadow-md">
          <h2 className="text-lg font-bold text-gray-900 mb-6">Post Distribution</h2>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Bar dataKey="value" fill="#3B82F6" name="Posts" />
            </BarChart>
          </ResponsiveContainer>
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-lg p-6 shadow-md">
          <h2 className="text-lg font-bold text-gray-900 mb-6">Quick Actions</h2>
          <div className="space-y-3">
            <Link
              to="/admin/posts/new"
              className="block w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-center font-medium transition"
            >
              ✍️ Create Post
            </Link>
            <Link
              to="/admin/categories"
              className="block w-full px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 text-center font-medium transition"
            >
              📁 Manage Categories
            </Link>
            <Link
              to="/admin/media"
              className="block w-full px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 text-center font-medium transition"
            >
              🖼️ Media Library
            </Link>
            <Link
              to="/admin/settings"
              className="block w-full px-4 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 text-center font-medium transition"
            >
              ⚙️ Settings
            </Link>
          </div>
        </div>
      </div>

      {/* Recent Posts */}
      <div className="bg-white rounded-lg p-6 shadow-md">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-bold text-gray-900">Recent Posts</h2>
          <Link to="/admin/posts" className="text-blue-600 hover:text-blue-700 font-medium">
            View All
          </Link>
        </div>

        {recentPosts.length > 0 ? (
          <div className="space-y-4">
            {recentPosts.map(post => (
              <div key={post.id} className="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50">
                <div>
                  <h3 className="font-semibold text-gray-900">{post.title}</h3>
                  <p className="text-sm text-gray-600">{post.category_name}</p>
                </div>
                <div className="text-right">
                  <span className={`inline-block px-3 py-1 rounded-full text-xs font-medium ${
                    post.status === 'published'
                      ? 'bg-green-100 text-green-700'
                      : 'bg-yellow-100 text-yellow-700'
                  }`}>
                    {post.status}
                  </span>
                  <p className="text-sm text-gray-500 mt-1">👁️ {post.view_count || 0} views</p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 text-center py-8">No posts yet. <Link to="/admin/posts/new" className="text-blue-600 hover:underline">Create one</Link></p>
        )}
      </div>
    </div>
  )
}
