import axios from 'axios';
import React, { useEffect, useState } from 'react';
import PageLayout from '../components/PageLayout';

function Reports() {
  const [reportType, setReportType] = useState('students');
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

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

  const loadReport = async (type) => {
    setReportType(type);
    setLoading(true);
    try {
      let url = '';
      if (type === 'students') url = 'http://localhost:5001/api/student/getstudent';
      else if (type === 'books') url = 'http://localhost:5001/api/book/getbook';
      else if (type === 'borrowed') url = 'http://localhost:5001/api/borrow/getborrowed';
      else if (type === 'returned') url = 'http://localhost:5001/api/borrow/getreturned';

      const res = await axios.get(url, { headers });
      setData(res.data);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadReport('students');
  }, []);

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

  const titleMap = {
    students: 'All students',
    books: 'All books',
    borrowed: 'Currently borrowed',
    returned: 'Returned books',
  };

  const tabClass = (active) =>
    `rounded-md px-3 py-2 text-sm font-medium transition-colors ${
      active ? 'bg-blue-600 text-white' : 'bg-slate-800 text-slate-300 hover:bg-slate-700'
    }`;

  return (
    <PageLayout title="Reports" wide>
      <div className="mb-4 flex flex-wrap gap-2 print:hidden">
        <button type="button" onClick={() => loadReport('students')} className={tabClass(reportType === 'students')}>
          All students
        </button>
        <button type="button" onClick={() => loadReport('books')} className={tabClass(reportType === 'books')}>
          All books
        </button>
        <button type="button" onClick={() => loadReport('borrowed')} className={tabClass(reportType === 'borrowed')}>
          Currently borrowed
        </button>
        <button type="button" onClick={() => loadReport('returned')} className={tabClass(reportType === 'returned')}>
          Returned
        </button>
        <button type="button" onClick={handlePrint} className="lms-btn-primary ml-auto bg-green-600 hover:bg-green-700">
          Print
        </button>
      </div>

      <h2 className="mb-3 text-lg font-medium text-white print:text-black">{titleMap[reportType]}</h2>

      {loading ? (
        <p className="text-sm text-slate-400">Loading...</p>
      ) : (
        <div className="space-y-3" id="report-content">
          {reportType === 'students' &&
            data.map((s) => (
              <div key={s._id} className="lms-list-item print:border-gray-300 print:bg-white">
                <p className="text-white print:text-black">{s.name} — Class {s.studentClass}</p>
                <p className="text-sm text-slate-400 print:text-gray-600">{s.email} · {s.phone}</p>
              </div>
            ))}

          {reportType === 'books' &&
            data.map((b) => (
              <div key={b._id} className="lms-list-item print:border-gray-300 print:bg-white">
                <p className="text-white print:text-black">{b.title} by {b.author}</p>
                <p className="text-sm text-slate-400 print:text-gray-600">Copies: {b.quantity}</p>
              </div>
            ))}

          {(reportType === 'borrowed' || reportType === 'returned') &&
            data.map((item) => (
              <div key={item._id} className="lms-list-item print:border-gray-300 print:bg-white">
                <p className="text-white print:text-black">Student: {item.student_FK?.name}</p>
                <p className="text-sm text-slate-400 print:text-gray-600">Book: {item.book_FK?.title}</p>
                <p className="text-sm text-slate-400 print:text-gray-600">
                  Borrowed: {item.borrowDate} · Due: {item.dueDate}
                </p>
                {item.returnDate && (
                  <p className="text-sm text-slate-400 print:text-gray-600">Returned: {item.returnDate}</p>
                )}
              </div>
            ))}

          {data.length === 0 && <p className="text-sm text-slate-400">No records</p>}
        </div>
      )}
    </PageLayout>
  );
}

export default Reports;
