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

const api = axios.create({ baseURL: 'http://localhost:5000' });

function App() {
  const [view, setView] = useState('login');
  const [isRegistering, setIsRegistering] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  const [data, setData] = useState({ books: [], members: [], borrows: [], returns: [] });
  const [form, setForm] = useState({});

  const fetchData = async () => {
    try {
      const [b, m, br, r] = await Promise.all([
        api.get('/books'), api.get('/members'), api.get('/borrows'), api.get('/returns')
      ]);
      setData({ books: b.data, members: m.data, borrows: br.data, returns: r.data });
    } catch (e) { console.error("Error fetching data"); }
  };

  const handleAuth = async () => {
    try {
      const endpoint = isRegistering ? '/register' : '/login';
      await api.post(endpoint, { username: form.username, password: form.password });
      if (isRegistering) {
        alert("Registration successful! Please login.");
        setIsRegistering(false);
      } else {
        setView('dashboard');
        fetchData();
      }
    } catch (e) { alert(e.response?.data?.error || "Authentication failed"); }
  };

  const handleAction = async (method, endpoint, payload) => {
    try {
      if (method === 'post') await api.post(endpoint, payload);
      else if (method === 'put') await api.put(endpoint, payload);
      else await api.delete(endpoint);
      fetchData();
      setForm({});
    } catch (e) { alert("Operation failed"); }
  };

  if (view === 'login') return (
    <div className="min-h-screen flex items-center justify-center bg-gray-900">
      <div className="bg-white p-12 rounded-3xl shadow-2xl w-96 text-center">
        <h1 className="text-3xl font-bold mb-6 text-gray-800">{isRegistering ? 'Create Account' : 'Library Portal'}</h1>
        <input className="w-full p-4 mb-4 bg-gray-100 rounded-xl outline-none" placeholder="Username" onChange={e => setForm({...form, username: e.target.value})} />
        <input className="w-full p-4 mb-8 bg-gray-100 rounded-xl outline-none" type="password" placeholder="Password" onChange={e => setForm({...form, password: e.target.value})} />
        <button className="w-full bg-blue-600 text-white p-4 rounded-xl font-bold hover:bg-blue-700 transition" onClick={handleAuth}>
          {isRegistering ? 'REGISTER' : 'LOGIN'}
        </button>
        <p className="mt-6 text-gray-500 cursor-pointer hover:text-blue-600" onClick={() => setIsRegistering(!isRegistering)}>
          {isRegistering ? 'Already have an account? Login' : 'Need an account? Register'}
        </p>
      </div>
    </div>
  );

  return (
    <div className="flex h-screen bg-gray-100 font-sans">
      <aside className="w-72 bg-gray-900 text-white p-8">
        <h1 className="text-2xl font-bold mb-12 text-blue-400">LIBRARY PRO</h1>
        <nav className="space-y-3">
          {['dashboard', 'books', 'members', 'borrows', 'returns', 'reports'].map(tab => (
            <div key={tab} className={`p-4 rounded-xl cursor-pointer ${activeTab === tab ? 'bg-blue-600' : 'hover:bg-gray-800'}`} onClick={() => setActiveTab(tab)}>
              {tab.toUpperCase()}
            </div>
          ))}
        </nav>
        <button className="mt-12 text-red-400 font-bold" onClick={() => setView('login')}>LOGOUT</button>
      </aside>

      <main className="flex-1 p-10 overflow-auto">
        {activeTab === 'dashboard' ? (
          <div className="space-y-10 animate-in fade-in duration-500">
            <div>
              <h2 className="text-4xl font-extrabold text-gray-800">System Overview</h2>
              <p className="text-gray-500 mt-2">Welcome back! Here is the current status of your library.</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {Object.entries(data).map(([k, v], index) => {
                const colors = ['bg-blue-500', 'bg-emerald-500', 'bg-amber-500', 'bg-rose-500'];
                return (
                  <div key={k} className="bg-white p-6 rounded-3xl shadow-sm border border-gray-100 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                    <div className={`w-12 h-12 ${colors[index % 4]} rounded-2xl flex items-center justify-center mb-4 text-white font-bold text-lg`}>
                      {v.length}
                    </div>
                    <h3 className="text-lg font-bold text-gray-700 capitalize">{k}</h3>
                    <p className="text-gray-400 text-sm">Total Active Records</p>
                  </div>
                );
              })}
            </div>
          </div>
        ) : activeTab === 'reports' ? (
          <div className="bg-white p-8 rounded-3xl shadow-sm">
            <div className="flex justify-between items-center mb-8">
              <h2 className="text-3xl font-bold">Official Inventory Report</h2>
              <button 
                onClick={() => window.print()} 
                className="bg-gray-800 text-white px-6 py-2 rounded-xl font-bold hover:bg-black transition"
              >
                PRINT REPORT
              </button>
            </div>
            <table className="w-full text-left">
              <thead><tr className="text-gray-400 uppercase text-sm border-b"><th>Category</th><th>Count</th><th>Status</th></tr></thead>
              <tbody>
                {Object.entries(data).map(([k, v], i) => (
                  <tr key={i} className="border-b py-4">
                    <td className="p-4 font-bold capitalize">{k}</td>
                    <td className="p-4">{v.length} Records</td>
                    <td className="p-4 text-green-600 font-bold">ACTIVE</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="bg-white p-8 rounded-3xl shadow-sm">
            <h2 className="text-2xl font-bold mb-6 capitalize">{activeTab} Management</h2>
            <div className="flex gap-2 mb-6">
              {activeTab === 'books' && <input className="p-3 border rounded-xl flex-1" placeholder="Enter Book Title" onChange={e => setForm({Title: e.target.value})} />}
              {activeTab === 'members' && <input className="p-3 border rounded-xl flex-1" placeholder="Enter Member Name" onChange={e => setForm({Name: e.target.value})} />}
              {activeTab === 'borrows' && (
                <div className="flex gap-2 flex-1">
                  <select className="p-3 border rounded-xl flex-1" onChange={e => setForm({...form, BookID: e.target.value})}>
                    <option value="">Select Book</option>
                    {data.books.map(b => <option key={b.BookID} value={b.BookID}>{b.Title}</option>)}
                  </select>
                  <select className="p-3 border rounded-xl flex-1" onChange={e => setForm({...form, MemberID: e.target.value})}>
                    <option value="">Select Member</option>
                    {data.members.map(m => <option key={m.MemberID} value={m.MemberID}>{m.Name}</option>)}
                  </select>
                  <input type="date" className="p-3 border rounded-xl flex-1" onChange={e => setForm({...form, BorrowDate: e.target.value})} />
                </div>
              )}
              {activeTab === 'returns' && (
                <div className="flex gap-2 flex-1">
                  <select className="p-3 border rounded-xl flex-1" onChange={e => setForm({...form, BorrowID: e.target.value})}>
                    <option value="">Select Borrow Record</option>
                    {data.borrows.map(br => <option key={br.BorrowID} value={br.BorrowID}>ID: {br.BorrowID}</option>)}
                  </select>
                  <input type="date" className="p-3 border rounded-xl flex-1" onChange={e => setForm({...form, ReturnDate: e.target.value})} />
                </div>
              )}
              <button className="bg-blue-600 text-white px-6 rounded-xl font-bold" onClick={() => handleAction('post', `/${activeTab}`, form)}>ADD</button>
            </div>
            <table className="w-full text-left">
              <thead><tr className="text-gray-400 text-sm border-b"><th>ID</th><th>DETAILS</th><th>ACTIONS</th></tr></thead>
              <tbody>
                {data[activeTab].map((item, i) => (
                  <tr key={i} className="border-b">
                    <td className="p-4 font-mono">{item.BookID || item.MemberID || item.BorrowID || item.ReturnID}</td>
                    <td className="p-4 font-semibold">
                      {activeTab === 'borrows' ? `Book: ${item.BookID} | Member: ${item.MemberID} | Date: ${new Date(item.BorrowDate).toLocaleDateString()}` 
                      : activeTab === 'returns' ? `Borrow ID: ${item.BorrowID} | Returned: ${new Date(item.ReturnDate).toLocaleDateString()}`
                      : item.Title || item.Name || `Record ID: ${item.BookID || item.MemberID || item.BorrowID || item.ReturnID}`}
                    </td>
                    <td className="p-4 flex gap-2">
                      <button className="text-blue-500 hover:underline" onClick={() => handleAction('put', `/${activeTab}/${item.BookID || item.MemberID || item.BorrowID || item.ReturnID}`, {Title: prompt("Update Value:")})}>EDIT</button>
                      <button className="text-red-500 hover:underline" onClick={() => handleAction('delete', `/${activeTab}/${item.BookID || item.MemberID || item.BorrowID || item.ReturnID}`)}>DELETE</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </main>
    </div>
  );
}
export default App;