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

function Record() {
    const [recordList, setRecordList] = useState([]);
    const [paymentsList, setPaymentsList] = useState([]);
    const [termInput, setTermInput] = useState('');
    const [selectedPayment, setSelectedPayment] = useState('');
    const [error, setError] = useState('');
    
    const fetchRecord = () => {
        axios.get('http://localhost:5000/api/record')
            .then((res) => {
                setRecordList(res.data);
            })
            .catch(() => {
                setError('Could not fetch financial records.');
            });
    };

    const fetchPayments = () => {
        axios.get('http://localhost:5000/api/payments')
            .then((res) => {
                setPaymentsList(res.data);
            })
            .catch(() => {
                console.log('No payment details available.');
            });
    };

    useEffect(() => {
        fetchRecord();
        fetchPayments();
    }, []);

    const handleSubmit = (e) => {
        e.preventDefault();

        const newRecordPackage = {
            term: termInput,
            payment: selectedPayment
        };

        axios.post('http://localhost:5000/api/record', newRecordPackage)
            .then(() => {
                setTermInput('');
                setSelectedPayment('');
                fetchRecord(); 
            })
            .catch(() => {
                setError('Failed to log academic record.');
            });
    };

    let totalRevenueSum = 0;
    for (let i = 0; i < recordList.length; i++) {
        const cost = recordList[i].payment?.fees?.amount || 0;
        totalRevenueSum = totalRevenueSum + Number(cost);
    }

    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 Records</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>
            )}

            {/* TOTAL REVENUE SUMMARY CARD */}
            <div className="bg-white p-6 rounded-2xl shadow-sm border border-amber-300/40 max-w-md flex flex-col gap-2">
                <h3 className="text-lg font-bold text-gray-800 border-b border-gray-100 pb-2">
                    Total revenue report
                </h3>
                <p className="text-sm text-gray-600">
                    <span className="font-semibold text-gray-500 mr-1">Total record session:</span> 
                    {recordList.length}
                </p>
                <p className="text-xl font-black text-gray-900 mt-1">
                    <span className="text-sm font-semibold text-gray-500 block">Total Fees Collected:</span>
                    <span className="text-emerald-600">rwf {totalRevenueSum.toLocaleString()}</span>
                </p>
            </div>

            {/* INPUT LOGGING FORM */}
            <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">
                <input 
                    type="text" 
                    value={termInput} 
                    placeholder="Enter term name (e.g. Term 1)"
                    onChange={(e) => setTermInput(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"
                    required
                />
                
                <select 
                    value={selectedPayment} 
                    onChange={(e) => setSelectedPayment(e.target.value)}
                    className="flex-1 border border-gray-300 bg-white rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-orange-500 text-gray-700"
                    required
                >
                    <option value="">select payment</option>
                    {paymentsList.map((pay) => (
                        <option key={pay._id} value={pay._id}>
                            {pay.student?.name || "Unknown Student"} - ({pay.fees?.amount || 0} 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 record
                </button>
            </form>

            <h3 className="text-xl font-bold text-gray-800 mt-4">Active Records</h3>
            
            {/* STATEMENT HISTORY LEDGER */}
            <div className="flex flex-col gap-4 max-w-2xl">
                {recordList.map((rec) => (
                    <div 
                        key={rec._id} 
                        className="bg-white p-5 rounded-xl shadow-sm border border-gray-100 flex flex-col gap-2 relative overflow-hidden"
                    >
                        <div className="bg-gray-50 -mx-5 -mt-5 px-5 py-2.5 border-b border-gray-100 mb-1 flex justify-between items-center">
                            <h4 className="text-xs font-black tracking-wider text-gray-400">
                                OFFICIAL INVOICE BILL STATEMENT
                            </h4>
                            <span className="text-[10px] font-mono bg-amber-100 text-amber-800 px-2 py-0.5 rounded">
                                ID: {rec._id ? rec._id.slice(-6) : 'N/A'}
                            </span>
                        </div>
                        
                        <p className="text-sm text-gray-700">
                            <span className="font-semibold text-gray-500 w-32 inline-block">Term Reference:</span>
                            <span className="font-medium text-gray-900">{rec.term}</span>
                        </p>
                        <p className="text-sm text-gray-700">
                            <span className="font-semibold text-gray-500 w-32 inline-block">Student Name:</span>
                            <span className="font-medium text-gray-900">{rec.payment?.student?.name || 'N/A'}</span>
                        </p>
                        <p className="text-sm text-gray-700">
                            <span className="font-semibold text-gray-500 w-32 inline-block">Billed Rate:</span>
                            <span className="font-bold text-orange-600">{rec.payment?.fees?.amount ? `${rec.payment.fees.amount} RWF` : 'N/A'}</span>
                        </p>
                        <p className="text-sm text-gray-700">
                            <span className="font-semibold text-gray-500 w-32 inline-block">Payment Status:</span>
                            <span className="inline-flex items-center gap-1.5 text-emerald-700 font-medium bg-emerald-50 px-2 py-0.5 rounded text-xs border border-emerald-100">
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                                cleared on {rec.payment?.paymentDate ? new Date(rec.payment.paymentDate).toLocaleDateString() : 'N/A'}
                            </span>
                        </p>
                    </div>   
                ))}
            </div>
        </div>
    );
}

export default Record;
