import { useEffect, useState } from 'react';
import axios from 'axios';

function Report() {
  const [user, setUser] = useState(null);
  const [items, setItems] = useState([]);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const [generatedAt] = useState(() => new Date().toLocaleString());

  const getAuthHeaders = () => ({
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  });

  const handleRetrieve = async () => {
    try {
      const [userRes, itemsRes] = await Promise.all([
        axios.get('http://localhost:5000/api/auth/me', { headers: getAuthHeaders() }),
        axios.get('http://localhost:5000/api/items', { headers: getAuthHeaders() }),
      ]);
      setUser(userRes.data.user);
      setItems(itemsRes.data.items);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load report data');
      console.error('Server Error:', err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

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

  const handlePrint = () => {
    window.print();
  };

  if (loading) {
    return <p className="text-slate-500">Loading report...</p>;
  }

  return (
    <div className="max-w-4xl">
      <div className="flex flex-wrap items-start justify-between gap-4 mb-6 print:hidden">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Report</h1>
          <p className="text-slate-600 mt-1">
            Summary you can reuse in every project. Print or save as PDF from the browser.
          </p>
        </div>

      </div>

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

      <article className="bg-white rounded-lg shadow-sm border border-slate-200 p-6 print:shadow-none print:border-0">
        <header className="border-b border-slate-200 pb-4 mb-6">
          <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">
            Project report
          </p>
          <h2 className="text-xl font-bold text-slate-800 mt-1">Blueprint summary</h2>
          <p className="text-sm text-slate-500 mt-2">Generated: {generatedAt}</p>
        </header>

        <section className="mb-8">
          <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide mb-3">
            Account
          </h3>
          {user ? (
            <dl className="grid gap-2 sm:grid-cols-2 text-sm">
              <div>
                <dt className="text-slate-500">Name</dt>
                <dd className="font-medium text-slate-800">{user.name}</dd>
              </div>
              <div>
                <dt className="text-slate-500">Email</dt>
                <dd className="font-medium text-slate-800">{user.email}</dd>
              </div>
            </dl>
          ) : (
            <p className="text-sm text-slate-500">No user data available.</p>
          )}
        </section>

        <section>
          <h3 className="text-sm font-semibold text-slate-700 uppercase tracking-wide mb-3">
            Items ({items.length})
          </h3>
          {items.length === 0 ? (
            <p className="text-sm text-slate-500">No items recorded.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm text-left border border-slate-200 rounded-lg overflow-hidden">
                <thead className="bg-slate-50 text-slate-600">
                  <tr>
                    <th className="px-4 py-2 font-medium">Title</th>
                    <th className="px-4 py-2 font-medium">Description</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  {items.map((item) => (
                    <tr key={item._id}>
                      <td className="px-4 py-2 text-slate-800">{item.title}</td>
                      <td className="px-4 py-2 text-slate-600">
                        {item.description || '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </section>
      </article>
    </div>
  );
}

export default Report;
