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

function Product() {

    const [students, setStudents] = useState([]);

    const [studentId, setStudentId] = useState('');
    const [fullName, setFullName] = useState('');
    const [classGrade, setClassGrade] = useState('');
    const [parentName, setParentName] = useState('');
    const [parentPhone, setParentPhone] = useState('');

    const [editId, setEditId] = useState(null);
    const [message, setMessage] = useState('');

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

    // CLEAR FORM
    const clearForm = () => {
        setStudentId('');
        setFullName('');
        setClassGrade('');
        setParentName('');
        setParentPhone('');
    };

    // GET STUDENTS
    const getProducts = async () => {
        try {

            const res = await axios.get(
                'http://localhost:5001/api/product/getproduct',
                { headers }
            );

            setStudents(res.data);

        } catch (err) {
            console.log(err);
        }
    };

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

    // CREATE + UPDATE
    const handleSubmit = async (e) => {
        e.preventDefault();
        try {

            // UPDATE
            if (editId) {

                await axios.put(
                    `http://localhost:5001/api/product/updateproduct/${editId}`,{ studentId, fullName, classGrade, parentName, parentPhone },
                    { headers }
                );

                setMessage('Student updated');

            } else {

                // CREATE
                await axios.post(
                    'http://localhost:5001/api/product/addproduct',
                    { studentId, fullName, classGrade, parentName, parentPhone },
                    { headers }
                );

                setMessage('Student added');
            }

            clearForm();
            setEditId(null);
            getProducts();

        } catch (err) {
            console.log(err);
        }
    };

    // DELETE
    const handleDelete = async (id) => {
        try {

            await axios.delete(
                `http://localhost:5001/api/product/deleteproduct/${id}`,
                { headers }
            );

            getProducts();

        } catch (err) {
            console.log(err);
        }
    };

    // EDIT
    const handleEdit = (student) => {

        setStudentId(student.studentId);
        setFullName(student.fullName);
        setClassGrade(student.classGrade);
        setParentName(student.parentName);
        setParentPhone(student.parentPhone);
        setEditId(student._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">
                Student Management
            </h1>

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

            {/* FORM */}
            <form
                onSubmit={handleSubmit}
                className="form-card"
            >

                <input
                    type="text"
                    placeholder="Student ID"
                    value={studentId}
                    onChange={(e) =>
                        setStudentId(e.target.value)
                    }
                    className="input-field"
                    required
                />

                <input
                    type="text"
                    placeholder="Full Name"
                    value={fullName}
                    onChange={(e) =>
                        setFullName(e.target.value)
                    }
                    className="input-field"
                    required
                />

                <input
                    type="text"
                    placeholder="Class / Grade"
                    value={classGrade}
                    onChange={(e) =>
                        setClassGrade(e.target.value)
                    }
                    className="input-field"
                    required
                />

                <input
                    type="text"
                    placeholder="Parent Name"
                    value={parentName}
                    onChange={(e) =>
                        setParentName(e.target.value)
                    }
                    className="input-field"
                    required
                />

                <input
                    type="text"
                    placeholder="Parent Phone"
                    value={parentPhone}
                    onChange={(e) =>
                        setParentPhone(e.target.value)
                    }
                    className="input-field"
                    required
                />

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

            </form>

            {/* STUDENTS */}
            <div className="mt-6 space-y-3">

                {students.length === 0 && (
                  <p className="text-sm text-slate-500">No students added yet.</p>
                )}

                {students.map((student) => (

                    <div
                        key={student._id}
                        className="list-card"
                    >

                        <p className="text-sm text-slate-700"><span className="font-medium">Student ID:</span> {student.studentId}</p>
                        <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Name:</span> {student.fullName}</p>
                        <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Class:</span> {student.classGrade}</p>
                        <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Parent:</span> {student.parentName}</p>
                        <p className="text-sm text-slate-700 mt-1"><span className="font-medium">Phone:</span> {student.parentPhone}</p>

                        <div className="flex gap-4 mt-3">

                            <button
                                type="button"
                                onClick={() => handleEdit(student)}
                                className="btn-text-edit"
                            >
                                Edit
                            </button>

                            <button
                                type="button"
                                onClick={() => handleDelete(student._id)}
                                className="btn-text-delete"
                            >
                                Delete
                            </button>

                        </div>

                    </div>

                ))}

            </div>

        </div>
        </div>
    );
}

export default Product;
