import { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

function DashboardHome() {
  const [itemCount, setItemCount] = useState(null);
  const [error, setError] = useState('');

  const handleRetrieve = async () => {
    try {
      const response = await axios.get('http://localhost:5000/api/items', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      setItemCount(response.data.items.length);
    } catch (err) {
      setError(err.response?.data?.message || 'Could not load overview');
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

  useEffect(() => {
    handleRetrieve();
  }, []);

  return (
    <div className="max-w-4xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-2">Overview</h1>
      <p className="text-slate-600 mb-8">
        Use the sidebar to move between sections of your dashboard.
      </p>

      {error && (
        <p className="mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">
          {error}
        </p>
      )}

      <div className="grid gap-4 sm:grid-cols-2">
        <div className="bg-white rounded-lg shadow-sm border border-slate-200 p-6">
          <p className="text-sm font-medium text-slate-500">Total items</p>
          <p className="text-3xl font-bold text-slate-800 mt-2">
            {itemCount === null ? '—' : itemCount}
          </p>
          <Link
            to="/dashboard/items"
            className="inline-block mt-4 text-sm font-medium text-blue-600 hover:underline"
          >
            Manage items →
          </Link>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-slate-200 p-6">
          <p className="text-sm font-medium text-slate-500">Quick links</p>
          <ul className="mt-3 space-y-2 text-sm">
            <li>
              <Link to="/dashboard/items" className="text-blue-600 hover:underline">
                Items — create and edit
              </Link>
            </li>
            <li>
              <Link to="/dashboard/profile" className="text-blue-600 hover:underline">
                Profile — account details
              </Link>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}

export default DashboardHome;
