import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'

function Sales() {
  const [payments, setPayments] = useState([])
  const [students, setStudents] = useState([])
  const [paymentDate, setPaymentDate] = useState('')
  const [amount, setAmount] = useState('')
  const [studentId, setStudentId] = useState('')
  const [editId, setEditId] = useState(null)
  const [message, setMessage] = useState('')

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

const clearForm = () => {
  setPaymentDate('')
  setAmount('')
  setStudentId('')
  setEditId(null)
}
  const handleGet = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/sales/getsales', { headers })
      setPayments(res.data)
    } catch (error) {
      console.log(error)
    }
  }

  const handleGetStudents = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/product/getproduct', { headers })
      setStudents(res.data)
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(()=>{
   handleGet()
   handleGetStudents()
  },[])
const handleSubmit= async (e) => {
 e.preventDefault()
try {
  if(editId){
  await axios.put(`http://localhost:5001/api/sales/updatesales/${editId}`,{paymentDate,amount,studentId},{headers})

  setMessage('Updated successfully')
  clearForm()
  handleGet()

  }else{
  await axios.post('http://localhost:5001/api/sales/addsales',{paymentDate,amount,studentId},{headers})

  setMessage("Added Successfully")
  clearForm()
  handleGet()

  }
} catch (error) {
  console.log(error)
}
}
const handledelete = async(id)=>{
  await axios.delete(`http://localhost:5001/api/sales/deletesales/${id}`,{headers})
   handleGet()
}

const handleEdit =(payment)=>{
 setPaymentDate(payment.paymentDate ? payment.paymentDate.split('T')[0] : '')
 setAmount(payment.amount)
 setStudentId(payment.student_FK?._id || payment.student_FK)
 setEditId(payment._id)
}

  return (
    <div className="page-shell">
    <div className="page-container">
      <div className="mb-6">
        <Link to="/dashboard" className="btn-back">
          Back to dashboard
        </Link>
      </div>

      <h1 className="page-title">Fee Payments</h1>

      {message && <p className="alert-success">{message}</p>}

      <form onSubmit={handleSubmit} className="form-card">
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="label-text">Student</label>
            <select
              value={studentId}
              onChange={(e) => setStudentId(e.target.value)}
              className="input-field"
              required
            >
              <option value="">Select student</option>
              {students.map((student) => (
                <option key={student._id} value={student._id}>
                  {student.fullName} ({student.studentId})
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="label-text">Payment Date</label>
            <input
              type="date"
              value={paymentDate}
              onChange={(e) => setPaymentDate(e.target.value)}
              className="input-field"
              required
            />
          </div>

          <div className="sm:col-span-2">
            <label className="label-text">Amount</label>
            <input
              type="text"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              className="input-field"
              placeholder="Enter amount paid"
              required
            />
          </div>
        </div>

        <button type="submit" className="btn-primary">
          {editId ? 'Update' : 'Add'}
        </button>
      </form>

      <div className="mt-6 space-y-3">
        {payments.length === 0 ? (
          <p className="text-sm text-slate-500">No payments recorded yet.</p>
        ) : (
          payments.map((payment) => (
            <div key={payment._id} className="list-card">
              <p className="text-sm text-slate-700"><span className="font-medium">Student:</span> {payment.student_FK?.fullName || 'N/A'}</p>
              <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Date:</span> {payment.paymentDate ? new Date(payment.paymentDate).toLocaleDateString() : ''}</p>
              <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Amount:</span> {payment.amount}</p>

              <div className="flex gap-4 mt-3">
                <button
                  type="button"
                  onClick={() => handleEdit(payment)}
                  className="btn-text-edit"
                >
                  Edit
                </button>
                <button
                  type="button"
                  onClick={() => handledelete(payment._id)}
                  className="btn-text-delete"
                >
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
    </div>
  )
}

export default Sales

