import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../services/api';

function StatCard({ title, value, subtitle, color }) {
  const colors = {
    blue: 'bg-blue-50 text-blue-700 border-blue-200',
    green: 'bg-green-50 text-green-700 border-green-200',
    orange: 'bg-orange-50 text-orange-700 border-orange-200',
    red: 'bg-red-50 text-red-700 border-red-200',
  };
  return (
    <div className={`card border ${colors[color]}`}>
      <p className="text-sm font-medium opacity-80">{title}</p>
      <p className="text-3xl font-bold mt-1">{value}</p>
      {subtitle && <p className="text-xs mt-1 opacity-70">{subtitle}</p>}
    </div>
  );
}

export default function Dashboard() {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/reports/dashboard')
      .then(({ data }) => setStats(data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return <div className="flex justify-center py-20"><div className="animate-spin rounded-full h-10 w-10 border-b-2 border-primary-600" /></div>;
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Dashboard</h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard title="Total Books" value={stats.books.total} subtitle={`${stats.books.available} available`} color="blue" />
        <StatCard title="Active Members" value={stats.members.active} subtitle={`${stats.members.total} total`} color="green" />
        <StatCard title="Active Borrowings" value={stats.borrowings.active} subtitle={`${stats.borrowings.returned} returned`} color="orange" />
        <StatCard title="Overdue" value={stats.borrowings.overdue} subtitle="Need attention" color="red" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="card">
          <h2 className="text-lg font-semibold mb-4">Recent Borrowings</h2>
          {stats.recentBorrowings.length === 0 ? (
            <p className="text-gray-500 text-sm">No borrowings yet.</p>
          ) : (
            <div className="space-y-3">
              {stats.recentBorrowings.map((b) => (
                <div key={b.id} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-0">
                  <div>
                    <p className="font-medium text-sm">{b.title}</p>
                    <p className="text-xs text-gray-500">{b.member_name}</p>
                  </div>
                  <span className={`text-xs px-2 py-1 rounded-full ${
                    b.status === 'borrowed' ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-800'
                  }`}>
                    {b.status}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="card">
          <h2 className="text-lg font-semibold mb-4">Popular Books</h2>
          {stats.popularBooks.length === 0 ? (
            <p className="text-gray-500 text-sm">No data yet.</p>
          ) : (
            <div className="space-y-3">
              {stats.popularBooks.map((b, i) => (
                <div key={i} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-0">
                  <div>
                    <p className="font-medium text-sm">{b.title}</p>
                    <p className="text-xs text-gray-500">{b.author}</p>
                  </div>
                  <span className="text-sm font-semibold text-primary-600">{b.borrow_count} borrows</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="mt-8 flex gap-3">
        <Link to="/books" className="btn-primary">Manage Books</Link>
        <Link to="/borrowings" className="btn-secondary">Issue Book</Link>
        <Link to="/reports" className="btn-secondary">View Reports</Link>
      </div>
    </div>
  );
}
