import { useState } from 'react';
import api from '../services/api';

const reportTypes = [
  { id: 'inventory', label: 'Book Inventory', endpoint: '/reports/inventory', pdf: '/reports/pdf/inventory' },
  { id: 'borrowings', label: 'Borrowings History', endpoint: '/reports/borrowings', pdf: '/reports/pdf/borrowings' },
  { id: 'overdue', label: 'Overdue Books', endpoint: '/reports/overdue', pdf: '/reports/pdf/overdue' },
  { id: 'members', label: 'Members Report', endpoint: '/reports/members', pdf: null },
];

export default function Reports() {
  const [activeReport, setActiveReport] = useState(null);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  const generateReport = async (report) => {
    setLoading(true);
    setActiveReport(report.id);
    try {
      const { data: result } = await api.get(report.endpoint);
      setData(result);
    } catch (err) {
      alert('Failed to generate report.');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const downloadPdf = async (pdfPath) => {
    try {
      const response = await api.get(pdfPath, { responseType: 'blob' });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${pdfPath.split('/').pop()}.pdf`);
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (err) {
      alert('Failed to download PDF.');
    }
  };

  const renderTable = () => {
    if (!data) return null;

    if (activeReport === 'inventory' && data.books) {
      return (
        <table className="w-full text-sm">
          <thead><tr className="border-b text-left text-gray-500">
            <th className="pb-2 pr-3">Title</th><th className="pb-2 pr-3">Author</th>
            <th className="pb-2 pr-3">ISBN</th><th className="pb-2 pr-3">Category</th>
            <th className="pb-2 pr-3">Qty</th><th className="pb-2">Available</th>
          </tr></thead>
          <tbody>
            {data.books.map((b) => (
              <tr key={b.id} className="border-b border-gray-50">
                <td className="py-2 pr-3">{b.title}</td><td className="py-2 pr-3">{b.author}</td>
                <td className="py-2 pr-3">{b.isbn || '-'}</td><td className="py-2 pr-3">{b.category || '-'}</td>
                <td className="py-2 pr-3">{b.quantity}</td><td className="py-2">{b.available}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }

    if (activeReport === 'borrowings' && data.borrowings) {
      return (
        <table className="w-full text-sm">
          <thead><tr className="border-b text-left text-gray-500">
            <th className="pb-2 pr-3">Book</th><th className="pb-2 pr-3">Member</th>
            <th className="pb-2 pr-3">Borrowed</th><th className="pb-2 pr-3">Due</th><th className="pb-2">Status</th>
          </tr></thead>
          <tbody>
            {data.borrowings.map((b) => (
              <tr key={b.id} className="border-b border-gray-50">
                <td className="py-2 pr-3">{b.book_title}</td><td className="py-2 pr-3">{b.member_name}</td>
                <td className="py-2 pr-3">{b.borrow_date?.split('T')[0]}</td>
                <td className="py-2 pr-3">{b.due_date?.split('T')[0]}</td>
                <td className="py-2">{b.status}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }

    if (activeReport === 'overdue' && data.overdue) {
      return data.overdue.length === 0 ? (
        <p className="text-green-600">No overdue books!</p>
      ) : (
        <table className="w-full text-sm">
          <thead><tr className="border-b text-left text-gray-500">
            <th className="pb-2 pr-3">Book</th><th className="pb-2 pr-3">Member</th>
            <th className="pb-2 pr-3">Due Date</th><th className="pb-2">Days Overdue</th>
          </tr></thead>
          <tbody>
            {data.overdue.map((b) => (
              <tr key={b.id} className="border-b border-gray-50">
                <td className="py-2 pr-3">{b.book_title}</td><td className="py-2 pr-3">{b.member_name}</td>
                <td className="py-2 pr-3">{b.due_date?.split('T')[0]}</td>
                <td className="py-2 text-red-600 font-medium">{b.days_overdue}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }

    if (activeReport === 'members' && data.members) {
      return (
        <table className="w-full text-sm">
          <thead><tr className="border-b text-left text-gray-500">
            <th className="pb-2 pr-3">Name</th><th className="pb-2 pr-3">Email</th>
            <th className="pb-2 pr-3">Status</th><th className="pb-2 pr-3">Total Borrows</th><th className="pb-2">Active</th>
          </tr></thead>
          <tbody>
            {data.members.map((m) => (
              <tr key={m.id} className="border-b border-gray-50">
                <td className="py-2 pr-3">{m.name}</td><td className="py-2 pr-3">{m.email}</td>
                <td className="py-2 pr-3">{m.status}</td>
                <td className="py-2 pr-3">{m.total_borrowings}</td>
                <td className="py-2">{m.active_borrowings}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }

    return null;
  };

  const currentReport = reportTypes.find((r) => r.id === activeReport);

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

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {reportTypes.map((report) => (
          <div key={report.id} className="card hover:shadow-md transition-shadow">
            <h3 className="font-semibold mb-2">{report.label}</h3>
            <div className="flex gap-2">
              <button onClick={() => generateReport(report)} className="btn-primary text-sm flex-1">
                View
              </button>
              {report.pdf && (
                <button onClick={() => downloadPdf(report.pdf)} className="btn-secondary text-sm">
                  PDF
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

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

      {data && !loading && (
        <div className="card overflow-x-auto">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold">{currentReport?.label}</h2>
            <span className="text-xs text-gray-500">
              Generated: {new Date(data.generatedAt).toLocaleString()}
            </span>
          </div>
          {renderTable()}
        </div>
      )}
    </div>
  );
}
