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

function Search() {
  const [query, setQuery] = useState('');
  const [students, setStudents] = useState([]);
  const [books, setBooks] = useState([]);
  const [message, setMessage] = useState('');

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

  const handleSearch = async (e) => {
    e.preventDefault();
    try {
      const res = await axios.get(
        `http://localhost:5001/api/search/search?q=${encodeURIComponent(query)}`,
        { headers }
      );
      setStudents(res.data.students);
      setBooks(res.data.books);
      setMessage('');
    } catch (error) {
      console.log(error);
      setMessage('Search failed');
    }
  };

  return (
    <PageLayout title="Search">
      {message && <p className="lms-alert-error">{message}</p>}

      <form onSubmit={handleSearch} className="lms-form-panel mb-6 flex flex-col gap-3 sm:flex-row sm:items-end">
        <div className="flex-1">
          <label className="lms-label">Query</label>
          <input
            type="text"
            placeholder="Search students or books..."
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            className="lms-input"
            required
          />
        </div>
        <button type="submit" className="lms-btn-primary sm:mb-0">
          Search
        </button>
      </form>

      <section className="mb-6">
        <h2 className="mb-3 text-lg font-medium text-white">Students</h2>
        <div className="space-y-2">
          {students.length === 0 ? (
            <p className="text-sm text-slate-500">No students found</p>
          ) : (
            students.map((s) => (
              <div key={s._id} className="lms-list-item">
                <p className="font-medium text-white">{s.name} — {s.studentClass}</p>
                <p className="text-sm text-slate-400">{s.email} · {s.phone}</p>
              </div>
            ))
          )}
        </div>
      </section>

      <section>
        <h2 className="mb-3 text-lg font-medium text-white">Books</h2>
        <div className="space-y-2">
          {books.length === 0 ? (
            <p className="text-sm text-slate-500">No books found</p>
          ) : (
            books.map((b) => (
              <div key={b._id} className="lms-list-item">
                <p className="font-medium text-white">{b.title} by {b.author}</p>
                <p className="text-sm text-slate-400">Copies: {b.quantity}</p>
              </div>
            ))
          )}
        </div>
      </section>
    </PageLayout>
  );
}

export default Search;
