import React, { useState, useRef, useEffect } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronLeft, faChevronDown } from '@fortawesome/free-solid-svg-icons';
import Select from 'react-select'

const BASE_URL = process.env.REACT_APP_BASE_URL
const API_KEY = process.env.REACT_APP_API_KEY

const Verify = ({ phoneId, onVerify }) => {
    const [otpCode, setOtpCode] = useState('');
    const [generateCode, setGenerateCode] = useState('');
    const [error, setError] = useState('');

    const handleClick = async () => {
        console.log('Verify Click');
        console.log('otp code: ', otpCode);
        console.log('generate code: ', generateCode);
        console.log('phone number: ', phoneId);
    
        // Validation logic
        if (!otpCode) {
            setError("OTP Code is required."); // Set error message directly
            return; // Exit the function if there are errors
        } else if (otpCode.length !== 6) {
            setError("OTP Code must be exactly 6 characters long."); // Set error message directly
            return; // Exit the function if there are errors
        }
    
        setError(''); // Clear error if validation passes
        onVerify(); // Call the onVerify function passed from Auth
    };
    

    return (
        <div style={styles.section}>
            {/* Results Data */}
            <div className="form-group row align-items-center mt-4">
                <div className="col-md-6">
                    <div style={styles.selectWrapper}>
                        <input
                            type="text"
                            id="generateCode"
                            className="form-control"
                            placeholder="e133d538-dc40-4c43-b042-06aad864d634"
                            value={generateCode}
                            onChange={(e) => setGenerateCode(e.target.value)}
                            readOnly
                        />
                    </div>
                </div>

                <div className="col-md-6">
                    <div className="input-group">
                        <span className="input-group-prepend">
                            <span className="input-group-text">+62</span>
                        </span>
                        <input
                            type="text"
                            id="phoneId"
                            className="form-control"
                            placeholder="Phone Number"
                            value={phoneId}
                            readOnly
                        />
                    </div>
                </div>
            </div>

            {/* OTP Code */}
            <div className="form-group row align-items-center mt-3">
                <div className="col-md-6">
                    <input
                        type="text"
                        id="otpCode"
                        className="form-control"
                        placeholder="OTP Code"
                        value={otpCode}
                        onChange={(e) => {
                            const value = e.target.value;
                            // Allow only digits and enforce exactly 6 digits
                            if (/^\d{0,6}$/.test(value)) {
                                setOtpCode(value);
                            }
                        }}
                        maxLength={6} // Prevents entering more than 6 digits
                    />

                    {error && <small className="text-danger">{error}</small>}
                </div>
            </div>

            {/* Verify Button */}
            <div style={styles.submitButton}>
                <button onClick={handleClick} className="btn d-flex justify-content-center align-items-center me-2" style={{ backgroundColor: '#0542CC' }}>
                    <p className="text-white mb-0">Verify</p>
                </button>
            </div>
        </div>
    );
}


const Preview = () => {
    const [inputValue, setInputValue] = useState('');

    const handleCopy = () => {
        navigator.clipboard.writeText(inputValue);
        console.log('Copied');
    };

    return (
        <div className="form-group row align-items-center mt-4">
            <div className="col-10">
                <div style={styles.selectWrapper}>
                <input
                    type="text"
                    id="inputValue"
                    className="form-control"
                    placeholder="7976 is your verification code. For your security, do not share this code."
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    readOnly
                />
                </div>
            </div>
            <div className="col-2 d-flex">
                <div style={styles.selectWrapper}>
                <button className="btn btn-primary" onClick={handleCopy}>
                    Copy
                </button>
                </div>
            </div>
        </div>
    )
}

const Auth = () => {

    const [isSelectOpen, setIsSelectOpen] = useState(false);    
    const [applicationId, setApplicationId] = useState('');
    const [expiryId, setExpiryId] = useState(0);
    const [otpId, setOtpId] = useState('');
    const [phoneId, setPhoneId] = useState('');
    const [templateId, setTemplateId] = useState('');
    const [isLoading, setIsLoading] = useState(false);


    const [applicationIds, setApplicationIds] = useState([]);  
    const [showVerify, setShowVerify] = useState(false); 
    const [showPreview, setShowPreview] = useState(false);

    const [errors, setErrors] = useState({});
    const [inputValueApplication, setInputValueApplication] = useState(''); // Controlled input value for Application ID
    const [isServer, setIsServer] = useState(true);
    const [selectedQuota, setSelectedQuota] = useState(0);

    const applicationOptions = applicationIds.map(app => ({
        value: app.id,
        label: app.name
    }));

    const handleApplicationChange = (selectedOption) => {
        const selectedId = selectedOption.value;
        const selectedApp = applicationIds.find(app => app.id === parseInt(selectedId));

        setApplicationId(selectedOption ? selectedOption.value : '');

        if (selectedApp) {
            setSelectedQuota(selectedApp.quota);
        }
    };

    const handleInputChangeApplication = (newInputValue) => {
        // Limit input to 15 characters for Application ID
        if (newInputValue.length <= 15) {
            setInputValueApplication(newInputValue);
        }
    };

    useEffect(() => {
        const fetchApplicationIds = async () => {
            try {
                setIsLoading(true);
                const response = await fetch(`${BASE_URL}/application/list`, {
                    method: 'GET',
                    headers: {
                        'accept': 'application/json',
                        'x-api-key': API_KEY,
                    },
                });
        
                if (!response.ok) {
                    throw new Error('Failed to fetch application IDs');
                }
        
                const data = await response.json();
                console.log('Response Data:', data);
        
                if (data.status_code === 200) {
                    setApplicationIds(data.details.data);
                    setIsServer(true);
                } else {
                    setIsServer(false);
                    throw new Error(data.details.message || 'Failed to fetch application IDs');
                }
            } catch (error) {
                setErrors(error.message || 'Error fetching application IDs');
                setIsServer(false);
            } finally {
                setIsLoading(false);
            }
        };              

        fetchApplicationIds();
    }, []);

    const handleFocus = () => {
        setIsSelectOpen(true);
    };

    const handleBlur = () => {
        setIsSelectOpen(false);
    };

    const handleVerify = () => {
        setShowPreview(true); // Show the preview when verified
    };

    const validate = () => {
        const newErrors = {};
        if (!applicationId) newErrors.applicationId = "Application ID is required.";
        if (expiryId <= 0) newErrors.expiryId = "Expiry Time must be greater than 0.";
        if (!otpId) newErrors.otpId = "OTP Length is required.";
        if (!phoneId) newErrors.phoneId = "Phone Number is required.";
        if (!templateId) newErrors.templateId = "Template Name is required.";
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleClick = async () => {
        if (validate()) {
            // Log the input data
            console.log('Application ID:', applicationId);
            console.log('Expiry ID:', expiryId);
            console.log('OTP Length:', otpId);
            console.log('Phone Number:', '08' + phoneId); // Prepend "08" to the phone number
            console.log('Template ID:', templateId);

            console.log('Make Auth Demo');
            setShowVerify(true);
        }
    };
    
    return (
      <>        
        <div style={styles.section}>
            {/* Inject keyframes for the spinner */}
            <style>
                {`
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
                `}
            </style>

            {isLoading && (
                <div style={styles.loadingOverlay}>
                    <div style={styles.spinner}></div>
                </div>
            )}
            {/* Application ID Selection */}
            <div className="form-group row align-items-center">
                <div className="col-md-6">
                <Select
                    id="applicationId"
                    value={applicationOptions.find(option => option.value === applicationId)}
                    onChange={handleApplicationChange}
                    options={applicationOptions}
                    placeholder="Select Application ID"
                    isSearchable
                    menuPortalTarget={document.body}
                    menuPlacement="auto"
                    inputValue={inputValueApplication}
                    onInputChange={handleInputChangeApplication} // Limit input length for Application ID
                />
                </div>

                <div className="col-md-6">
                    <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', margin: '0', marginTop: '8px' }}>
                        Remaining Quota
                    </p>
                    <div style={styles.remainingQuota}>
                        <span style={styles.quotaText}>{selectedQuota}</span>
                        <span style={styles.timesText}>(times)</span>
                    </div>
                </div>
            </div>

            {/* Expiry and OTP */}
            <div className="form-group row align-items-center">
                <div className="col-md-6">
                    <div style={styles.selectWrapper}>
                        <input
                            type="number"
                            id="expiryId"
                            className="form-control"
                            style={styles.select}
                            value={expiryId}
                            onChange={(e) => {
                                const value = e.target.value;
                                // Check if the value is empty or a valid number
                                if (value === '' || /^[0-9]+$/.test(value)) {
                                    setExpiryId(value === '' ? '' : parseInt(value, 10)); // Update state as number
                                }
                            }}
                            onFocus={handleFocus}
                            onBlur={handleBlur}
                            placeholder="Expiry Time"
                        />
                        {errors.expiryId && <small className="text-danger">{errors.expiryId}</small>}
                    </div>

                </div>

                <div className="col-md-6">
                    <input
                        type="text"
                        id="otpId"
                        className="form-control"
                        placeholder="OTP Length"
                        value={otpId}
                        onChange={(e) => {
                            const value = e.target.value;
                            // Allow only digits and enforce length constraints
                            if (/^\d{0,6}$/.test(value)) {
                                setOtpId(value);
                            }
                        }}
                        minLength={6} // Enforce minimum length (for validation)
                        maxLength={6} // Enforce maximum length
                    />
                    {errors.otpId && <small className="text-danger">{errors.otpId}</small>}
                </div>
            </div>

            {/* Message and Phone */}
            <div className="form-group row align-items-center mt-4">
                <div className="col-md-6">
                    <div style={styles.selectWrapper}>
                        <input
                            type="text"
                            id="templateId"
                            className="form-control"
                            placeholder="Template Name"
                            value={templateId}
                            onChange={(e) => setTemplateId(e.target.value)}
                        />
                        {errors.templateId && <small className="text-danger">{errors.templateId}</small>}
                    </div>
                </div>

                <div className="col-md-6">
                    <div className="input-group">
                        <span className="input-group-prepend">
                            <span className="input-group-text">+62</span>
                        </span>
                        <input
                            type="text"
                            id="phoneId"
                            className="form-control"
                            placeholder="Phone Number"
                            value={phoneId}
                            onChange={(e) => {
                                const value = e.target.value;
                                // Allow only digits and enforce length constraints
                                if (/^\d*$/.test(value) && value.length <= 14) {
                                    setPhoneId(value);
                                }
                            }}
                            minLength={9} // Enforce minimum length
                            maxLength={14} // Enforce maximum length
                        />

                    </div>
                    {errors.phoneId && <small className="text-danger">{errors.phoneId}</small>}
                </div>
            </div>

            {/* Submit Button */}
            <div style={styles.submitButton}>
                <button onClick={handleClick} className="btn d-flex justify-content-center align-items-center me-2" style={{ backgroundColor: '#0542CC' }}>
                    <p className="text-white mb-0">Make Authentication</p>
                </button>
            </div>
        </div>

        {showVerify && <Verify phoneId={phoneId} onVerify={handleVerify} />}
        {showPreview && <Preview />}
      </>
    );
}

export default Auth;


const styles = {
    section: {
        margin: '1rem 0 1rem 0'
    },
    formGroup: {
        marginTop: '-45px',
    },
    selectWrapper: {
        position: 'relative',
        marginTop: '0', 
    },
    select: {
        width: '100%',
        paddingRight: '30px', 
        flex: 1,
        fontSize: '16px',
        border: 'none',
        outline: 'none',
    },
    chevronIcon: {
        position: 'absolute',
        right: '10px',
        top: '50%',
        transform: 'translateY(-50%)',
        pointerEvents: 'none',
    },
    remainingQuota: {
        display: 'flex', 
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: '4px', 
    },
    quotaText: {
        fontSize: '40px',
        color: '#0542cc',
        fontWeight: '600',
    },
    timesText: {
        marginLeft: '8px',
        verticalAlign: 'super',
        fontSize: '20px', 
    },
    buttonContainer: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center', // Center vertically within container
        position: 'absolute',
        right: '10px',
        top: '0',
        bottom: '0',
        height: '47px',
        margin: 'auto 0',
    },
    button: {
        background: 'none',
        border: 'none',
        cursor: 'pointer',
        padding: '0', // Kurangi padding tombol
        margin: '0', // Hilangkan margin antar tombol
        fontSize: '12px',
    },
    icon: {
        fontSize: '14px',
    },
    submitButton: {
        marginLeft: 'auto',
        marginTop: '1.2rem',
        textAlign: 'start',
        position: 'relative', 
        zIndex: 1, 
    },
    uploadError: {
        color: 'red',
        fontSize: '12px',
        marginTop: '5px',
    },

    containerResultStyle: {
        padding: '20px',
        border: '1px solid #0053b3',
        borderRadius: '5px',
        width: '100%', 
        margin: '20px auto',
    },
    resultContainer: {
        display: 'flex',
        justifyContent: 'flex-start', 
        alignItems: 'center',
        width: '100%', 
    },
    tableStyle: {
        width: '60%',
        borderCollapse: 'collapse',
    },
    imageContainer: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'flex-start', 
        width: '30%',
        marginLeft: '10px'
    },
    imageStyle: {
        width: '193px',
        height: '242px',
        borderRadius: '5px',
    },
    loadingOverlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.2)', 
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000, 
    },
    spinner: {
        border: '4px solid rgba(0, 0, 0, 0.1)',
        borderLeftColor: '#0542cc',
        borderRadius: '50%',
        width: '90px',
        height: '90px',
        animation: 'spin 1s ease-in-out infinite',
    },
    preview: {
        padding: '20px',
        border: '0.1px solid rgba(0, 0, 0, 0.2)',
        borderLeft: '4px solid #0542cc',
        borderRadius: '10px',
        width: '100%',
        marginTop: '1rem',
        backgroundColor: '#fff',
      },
};
