import React, { useEffect, useState } from 'react';

const AddNewAsset = () => {
    const [assetData, setAssetData] = useState({
        serialNumber: '',                // Optional but unique
        assetId: '',                     // Required
        vendor: '',                      // Required
        applicationName: '',             // Required
        qty: '',                         // Required
        renewalCost: '',                 // Optional
        startDate: '',                   // Required
        endDate: '',                     // Required
        contactPerson: '',               // Required
        emailId: '',                     // Required
        contactNumber: ''                // Required
    });

    // Fetch existing assets to determine the next assetId
    useEffect(() => {
        const fetchExistingAssets = async () => {
            try {
                const response = await fetch('/api/assets');
                const existingAssets = await response.json();

                // Find the highest assetId and increment it
                const highestAssetId = existingAssets.reduce((maxId, asset) => {
                    const assetNumber = parseInt(asset.assetId, 10);
                    return assetNumber > maxId ? assetNumber : maxId;
                }, 0);

                // Set the next assetId (001, 002, etc.)
                const nextAssetId = String(highestAssetId + 1).padStart(3, '0'); // Ensuring it is in the format 001, 002, etc.
                setAssetData((prevData) => ({ ...prevData, assetId: nextAssetId }));
            } catch (error) {
                console.error('Error fetching existing assets:', error);
            }
        };

        fetchExistingAssets();
    }, []);

    const handleInputChange = (event) => {
        const { name, value } = event.target;
        setAssetData({
            ...assetData,
            [name]: value,
        });
    };

    const handleSubmit = async (event) => {
        event.preventDefault();

        try {
            const response = await fetch('/api/assets', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(assetData),
            });

            if (!response.ok) {
                throw new Error('Failed to add asset');
            }

            // Clear form fields on successful submission (optional)
            setAssetData({
                serialNumber: '',
                assetId: '',
                vendor: '',
                applicationName: '',
                qty: '',
                renewalCost: '',
                startDate: '',
                endDate: '',
                contactPerson: '',
                emailId: '',
                contactNumber: '',
            });

            // Redirect or show success message
            alert('Asset added successfully');
            window.location.href = '/asset-inventory'; // Redirect to asset inventory page
        } catch (error) {
            console.error('Error adding asset:', error);
            alert('Failed to add asset. Please try again.');
        }
    };

    return (
        <div className="container mx-auto p-4 w-1/2 mt-10 p-6 bg-gray-100 rounded-lg">
            <div className="text-2xl text-center font-bold mb-4 text-black">Add New License</div>
            <form onSubmit={handleSubmit} className="max-w-md mx-auto" id="assetForm">
                <div className="mb-4">
                    <label htmlFor="assetId" className="block text-sm font-medium text-gray-700">Line Item: <span className="text-red-500">*</span></label>
                    <input
                        type="text"
                        id="assetId"
                        name="assetId"
                        placeholder="Enter asset ID"
                        value={assetData.assetId}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                        readOnly // Make it read-only since it's auto-generated
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="applicationName" className="block text-sm font-medium text-gray-700">Application Name: <span className="text-red-500">*</span></label>
                    <input
                        type="text"
                        id="applicationName"
                        name="applicationName"
                        placeholder="Enter application name"
                        value={assetData.applicationName}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="qty" className="block text-sm font-medium text-gray-700">Quantity: <span className="text-red-500">*</span></label>
                    <input
                        type="number"
                        id="qty"
                        name="qty"
                        placeholder="Enter quantity"
                        value={assetData.qty}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="startDate" className="block text-sm font-medium text-gray-700">Start Date: <span className="text-red-500">*</span></label>
                    <input
                        type="date"
                        id="startDate"
                        name="startDate"
                        value={assetData.startDate}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="endDate" className="block text-sm font-medium text-gray-700">End Date: <span className="text-red-500">*</span></label>
                    <input
                        type="date"
                        id="endDate"
                        name="endDate"
                        value={assetData.endDate}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="serialNumber" className="block text-sm font-medium text-gray-700">Serial Number:</label>
                    <input
                        type="text"
                        id="serialNumber"
                        name="serialNumber"
                        placeholder="Enter serial number (optional, must be unique)"
                        value={assetData.serialNumber}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="renewalCost" className="block text-sm font-medium text-gray-700">Renewal Cost:</label>
                    <input
                        type="number"
                        id="renewalCost"
                        name="renewalCost"
                        placeholder="Enter renewal cost (optional)"
                        value={assetData.renewalCost}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="vendor" className="block text-sm font-medium text-gray-700">Vendor Name: <span className="text-red-500">*</span></label>
                    <input
                        type="text"
                        id="vendor"
                        name="vendor"
                        placeholder="Enter vendor name"
                        value={assetData.vendor}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="contactPerson" className="block text-sm font-medium text-gray-700">Contact Person: <span className="text-red-500">*</span></label>
                    <input
                        type="text"
                        id="contactPerson"
                        name="contactPerson"
                        placeholder="Enter contact person"
                        value={assetData.contactPerson}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="emailId" className="block text-sm font-medium text-gray-700">Email ID: <span className="text-red-500">*</span></label>
                    <input
                        type="email"
                        id="emailId"
                        name="emailId"
                        placeholder="Enter email ID"
                        value={assetData.emailId}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>
                <div className="mb-4">
                    <label htmlFor="contactNumber" className="block text-sm font-medium text-gray-700">Contact Number: <span className="text-red-500">*</span></label>
                    <input
                        type="text"
                        id="contactNumber"
                        name="contactNumber"
                        placeholder="Enter contact number"
                        value={assetData.contactNumber}
                        onChange={handleInputChange}
                        className="mt-1 block w-full border border-gray-400 rounded-md px-3 py-2 focus:outline-none focus:border-blue-500"
                        required
                    />
                </div>

                <div className="flex justify-center">
                    <button
                        type="submit"
                        className="bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 focus:outline-none focus:bg-blue-600"
                    >
                        Save
                    </button>
                    <button
                        type="button"
                        className="bg-gray-400 text-gray-700 py-2 px-4 ml-2 rounded-md hover:bg-gray-300 focus:outline-none focus:bg-gray-300"
                        onClick={() => {
                            window.location.href = '/asset-inventory'; 
                        }}
                    >
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    );
};

export default AddNewAsset;   in this i wanted two more feilds one after quantity that is remaining ....keep it optional  and one before renewal cost keep it Payment terms having a dropdown  for montly,quaterly, biyearly , yeraly