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

function Payments() {
  const [payments, setPayments] = useState([]);
  const [students, setStudents] = useState([]); // Storage box for students list
  const [fees, setFees] = useState([]);         // Storage box for fees/amounts list
  const [error, setError] = useState('');
  
  const [studentInput, setStudentInput] = useState('');
  const [feesInput, setFeesInput] = useState('');

  // 1. Fetch everything from the database using separate simple calls
  const fetchAllProjectData = () => {
    // Get existing payments
    axios.get('http://localhost:5000/api/payments')
      .then((res) => {
        if (Array.isArray(res.data)) setPayments(res.data);
      })
      .catch(() => setError('Could not fetch payments data.'));

    // Get students list for the dropdown
    axios.get('http://localhost:5000/api/student') // Make sure this route matches your backend
      .then((res) => {
        if (Array.isArray(res.data)) setStudents(res.data);
      })
      .catch(() => setError('Could not fetch students list.'));

    // Get fees list for the dropdown
    axios.get('http://localhost:5000/api/fees') // Make sure this route matches your backend
      .then((res) => {
        if (Array.isArray(res.data)) setFees(res.data);
      })
      .catch(() => setError('Could not fetch fees options.'));
  };

  // 2. Submit the form data
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:5000/api/payments', {
        student: studentInput, // Sends the selected Student ID
        fees: feesInput,       // Sends the selected Fee ID
        paymentDate: new Date()
      });
      setStudentInput('');
      setFeesInput('');
      fetchAllProjectData(); // Refresh list immediately
    } catch (error) {
      setError('Failed to create payment record.');
    }
  }; 

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

  return (
    <div className="min-h-screen bg-amber-200 p-6 font-sans flex flex-col gap-6">
      <h2 className="text-3xl font-bold text-gray-900">Manage Payments</h2>
      
      {error && (
        <p className="bg-red-100 text-red-700 px-4 py-2 rounded-lg border border-red-200 text-sm font-medium w-max">
          {error}
        </p>
      )}

      {/* Changed text inputs into simple select dropdown elements */}
      <form onSubmit={handleSubmit} className="bg-white p-6 rounded-2xl shadow-sm border border-amber-300/40 flex flex-col sm:flex-row gap-3 max-w-2xl">
        
        {/* STUDENT SELECT DROPDOWN */}
        <select
          value={studentInput}
          onChange={(e) => setStudentInput(e.target.value)}
          className="flex-1 border border-gray-300 rounded-lg px-4 py-2 text-sm focus:outline-none focus:border-orange-500 bg-white"
          required
        >
          <option value="">-- Select Student --</option>
          {students.map((std) => (
            <option key={std._id} value={std._id}>
              {std.name}
            </option>
          ))}
        </select>

        {/* FEES SELECT DROPDOWN */}
        <select
          value={feesInput}
          onChange={(e) => setFeesInput(e.target.value)}
          className="flex-1 border border-gray-300 rounded-lg px-4 py-2 text-sm focus:outline-none focus:border-orange-500 bg-white"
          required
        >
          <option value="">-- Select Fee Type --</option>
          {fees.map((f) => (
            <option key={f._id} value={f._id}>
              {f.name || f.type} ({f.amount} RWF)
            </option>
          ))}
        </select>
               
        <button 
          type='submit'
          className="bg-orange-600 text-white font-medium px-5 py-2 rounded-lg hover:bg-orange-700 transition-colors text-sm whitespace-nowrap"
        >
          Add Payment
        </button>
      </form>
      
      <h2 className="text-xl font-bold text-gray-800 mt-4">Payments List</h2>

      <div className="flex flex-col gap-3 max-w-2xl">
        {payments.length === 0 ? (
          <p className="text-sm text-gray-600 bg-white/50 px-4 py-3 rounded-xl border border-dashed border-amber-400/40 w-max">
            No payments found or waiting for backend...
          </p>
        ) : (
          payments.map((p) => (
            <div 
              key={p._id} 
              className="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2"
            >
              <div className="flex flex-col gap-1">
                <p className="text-sm text-gray-700">
                  <span className="font-semibold text-gray-500 mr-1">Student:</span> 
                  {p.student?.name || p.student || 'N/A'}
                </p>
                <p className="text-sm text-gray-700">
                  <span className="font-semibold text-gray-500 mr-1">Amount:</span> 
                  <span className="text-orange-600 font-bold">{p.fees?.amount || p.fees || 'N/A'}</span>
                </p>
              </div>

              <div className="text-xs font-medium text-gray-400 bg-gray-50 px-2.5 py-1 rounded-md border border-gray-100 w-max sm:self-center">
                Date: {p.paymentDate ? new Date(p.paymentDate).toLocaleDateString() : 'N/A'}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Payments;
