import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown, faChevronLeft, faImage, faTimes } from '@fortawesome/free-solid-svg-icons';

const Verify = () => {
    const BASE_URL = process.env.REACT_APP_BASE_URL;
    const API_KEY = process.env.REACT_APP_API_KEY;
    const fileTypes = ["image/jpeg", "image/png"]; // Use MIME types for better file validation
    const fileInputRef = useRef(null);

    const [isSelectOpen, setIsSelectOpen] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');
    const [selectedImageName, setSelectedImageName] = useState('');
    const [file, setFile] = useState(null);
    const [applicationId, setApplicationId] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [applicationIds, setApplicationIds] = useState([]);
    const [imageError, setImageError] = useState('');
    const [data, setData] = useState(null);
    const [showResult, setShowResult] = useState(false);

    // Fetch Application IDs
    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();
                if (data.status_code === 200) {
                    setApplicationIds(data.details.data);
                } else {
                    throw new Error('Failed to fetch application IDs');
                }
            } catch (error) {
                setErrorMessage(error.message || 'Error fetching application IDs');
            } finally {
                setIsLoading(false);
            }
        };

        fetchApplicationIds();
    }, []);

    const handleFocus = () => setIsSelectOpen(true);
    const handleBlur = () => setIsSelectOpen(false);

    // Handle file upload
    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const fileType = file.type; // Use MIME type instead of file extension
        if (!fileTypes.includes(fileType)) {
            setImageError('Image format is not supported');
            setFile(null);
            return;
        }

        if (file.size > 2 * 1024 * 1024) { // 2MB check
            setImageError('File size exceeds 2MB');
            setFile(null);
            return;
        }

        setSelectedImageName(file.name);
        setFile(file);
        setImageError('');
    };

    // Cancel file upload
    const handleImageCancel = () => {
        setSelectedImageName('');
        setFile(null);
        setImageError('');
        fileInputRef.current.value = '';
    };

    // Submit form and trigger OCR API
    const handleCheckClick = async () => {
        if (!file || !applicationId) {
            setErrorMessage('Please select an application and upload a file.');
            return;
        }
    
        setIsLoading(true);
        const formData = new FormData();
        formData.append('application_id', applicationId);
        formData.append('file', file);
    
        console.log(`id: ${applicationId}, file: ${file}`)
    
        try {
            const response = await fetch(`${BASE_URL}/ocr-ktp`, {
                method: 'POST',
                headers: {
                    'accept': 'application/json',
                    'x-api-key': API_KEY,
                },
                body: formData,
            });
    
            if (!response.ok) {
                throw new Error('OCR processing failed');
            }
    
            const result = await response.json();
            
            console.log('Full response:', result); // Log full response to inspect the structure
    
            if (result.status_code === 201) {
                console.log('Success');
                // Correct the path to access the data-ktp object
                const responseData = result.details.data?.['data-ktp'] || {};
    
                // Log each field to inspect the data
                console.log('NIK:', responseData.nik);
                console.log('District:', responseData.kecamatan);
                console.log('Name:', responseData.nama);
                console.log('City:', responseData.kabkot);
                console.log('Date of Birth:', responseData.tanggal_lahir);
                console.log('State:', responseData.provinsi);
                console.log('Gender:', responseData.jenis_kelamin);
                console.log('Religion:', responseData.agama);
                console.log('Blood Type:', responseData.golongan_darah);
                console.log('Marital Status:', responseData.status_perkawinan);
                console.log('Address:', responseData.alamat);
                console.log('Occupation:', responseData.pekerjaan);
                console.log('RT/RW:', `${responseData.rt}/${responseData.rw}`);
                console.log('Nationality:', responseData.kewarganegaraan);
                console.log('Image URL:', result.details.image_url);
                console.log('Dark:', responseData.dark);
                console.log('Blur:', responseData.blur);
                console.log('Grayscale:', responseData.grayscale);
                console.log('Flashlight:', responseData.flashlight);
    
                // Map the response data to a new object with default values if the property doesn't exist
                const data = {
                    nik: responseData.nik || 'N/A',
                    district: responseData.kecamatan || 'N/A',
                    name: responseData.nama || 'N/A',
                    city: responseData.kabkot || 'N/A',
                    dob: responseData.tanggal_lahir || 'N/A',
                    state: responseData.provinsi || 'N/A',
                    gender: responseData.jenis_kelamin || 'N/A',
                    religion: responseData.agama || 'N/A',
                    bloodType: responseData.golongan_darah || 'N/A',
                    maritalStatus: responseData.status_perkawinan || 'N/A',
                    address: responseData.alamat || 'N/A',
                    occupation: responseData.pekerjaan || 'N/A',
                    rtRw: `${responseData.rt || 'N/A'}/${responseData.rw || 'N/A'}`,
                    nationality: responseData.kewarganegaraan || 'N/A',
                    imageUrl: result.details.image_url || '',
                    dark: responseData.dark || 'N/A',
                    blur: responseData.blur || 'N/A',
                    grayscale: responseData.grayscale || 'N/A',
                    flashlight: responseData.flashlight || 'N/A',
                };
    
                setData(data);
                setShowResult(true);
                setErrorMessage('');
                setSelectedImageName('');
            } else {
                setErrorMessage('OCR processing failed');
            }
        } catch (error) {
            setErrorMessage(error.message || 'Error during OCR processing');
        } finally {
            setIsLoading(false);
        }
    };
    
    return (
        <div className="container" style={{ marginTop: '3%' }}>
            <style>
                {`
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
                `}
            </style>
            {isLoading && (
                <div style={styles.loadingOverlay}>
                    <div style={styles.spinner}></div>
                    <p style={styles.loadingText}>Loading...</p>
                </div>
            )}

            <div className="row-card border-left border-primary shadow mb-4" style={{ backgroundColor: '#E2FBEA' }}>
                <div className="d-flex flex-column justify-content-start align-items-start p-4">
                    <div>
                        <h4 className="mb-3 text-start"><i className="fas fa-warning fa-bold me-3"></i>Alert</h4>
                        <p className="mb-0 text-start">
                            Get started now by creating an Application ID and explore all the demo services available on the dashboard.
                            Experience the ease and flexibility of trying out all our features firsthand.
                        </p>
                    </div>
                    <div className="d-flex flex-row mt-3">
                        <Link to="/createApps" style={{ textDecoration: 'none' }}>
                            <button className="btn d-flex justify-content-center align-items-center me-2" style={{ backgroundColor: '#0542CC' }}>
                                <i className="fas fa-plus text-white me-2"></i>
                                <p className="text-white mb-0">Create New App ID</p>
                            </button>
                        </Link>
                    </div>
                </div>
            </div>

            <div style={{ padding: '20px', border: '0.1px solid rgba(0, 0, 0, 0.2)', borderLeft: '4px solid #0542cc', borderRadius: '10px', width: '100%' }}>
                <div className="form-group row align-items-center">
                    <div className="col-md-6">
                        <div style={styles.selectWrapper}>
                            <select
                                id="applicationId"
                                className="form-control"
                                style={styles.select}
                                value={applicationId}
                                onChange={(e) => setApplicationId(e.target.value)}
                                onFocus={handleFocus}
                                onBlur={handleBlur}
                            >
                                <option value="">Select Application ID</option>
                                {applicationIds.map((app) => (
                                    <option key={app.id} value={app.id}>
                                        {app.name}
                                    </option>
                                ))}
                            </select>
                            <FontAwesomeIcon
                                icon={isSelectOpen ? faChevronDown : faChevronLeft}
                                style={styles.chevronIcon}
                            />
                        </div>
                    </div>
                    <div className="col-md-6">
                        <p className="text-secondary" style={{ fontSize: '16px', fontWeight: '400', marginTop: '8px' }}>
                            Remaining Quota
                        </p>
                        <div style={styles.remainingQuota}>
                            <span style={styles.quotaText}>0</span>
                            <span style={styles.timesText}>(times)</span>
                        </div>
                    </div>
                </div>

                <div className="col-md-6">
                    <div className="form-group mt-4">
                        <label htmlFor="imageInput" className="form-label">Upload Image (KTP)</label>
                        <div style={styles.uploadWrapper}>
                            <input
                                ref={fileInputRef}
                                type="file"
                                id="imageInput"
                                className="form-control"
                                accept="image/jpeg, image/png"
                                onChange={handleImageUpload}
                            />
                            {selectedImageName && (
                                <div className="mt-3">
                                    <p><strong>File:</strong> {selectedImageName}</p>
                                    <button className="btn btn-danger" onClick={handleImageCancel}>
                                        <FontAwesomeIcon icon={faTimes} className="me-2" />Cancel
                                    </button>
                                </div>
                            )}
                            {imageError && <p style={{ color: 'red' }}>{imageError}</p>}
                        </div>
                    </div>
                </div>

                <div className="col-md-12 d-flex justify-content-end mt-4">
                    <button
                        className="btn btn-primary"
                        onClick={handleCheckClick}
                        disabled={isLoading || !file || !applicationId}
                    >
                        <FontAwesomeIcon icon={faImage} className="me-2" />
                        Check KTP
                    </button>
                </div>

                {errorMessage && (
                    <div style={styles.errorContainer}>
                        <p style={styles.errorText}>{errorMessage}</p>
                    </div>
                )}
            </div>

            {showResult && data && (
                <div className="mt-5">
                    <h4>OCR Result</h4>
                    <table style={styles.tableStyle}>
                        <tbody>
                            <tr>
                                <td style={styles.tableCell}>NIK</td>
                                <td style={styles.tableCell}>{data.nik}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>District</td>
                                <td style={styles.tableCell}>{data.district}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Name</td>
                                <td style={styles.tableCell}>{data.name}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>City</td>
                                <td style={styles.tableCell}>{data.city}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Date of Birth</td>
                                <td style={styles.tableCell}>{data.dob}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>State</td>
                                <td style={styles.tableCell}>{data.state}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Gender</td>
                                <td style={styles.tableCell}>{data.gender}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Religion</td>
                                <td style={styles.tableCell}>{data.religion}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Blood Type</td>
                                <td style={styles.tableCell}>{data.bloodType}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Marital Status</td>
                                <td style={styles.tableCell}>{data.maritalStatus}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Address</td>
                                <td style={styles.tableCell}>{data.address}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Occupation</td>
                                <td style={styles.tableCell}>{data.occupation}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>RT/RW</td>
                                <td style={styles.tableCell}>{data.rtRw}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Nationality</td>
                                <td style={styles.tableCell}>{data.nationality}</td>
                            </tr>
                            <tr>
                                <td style={styles.tableCell}>Image</td>
                                <td style={styles.tableCell}><img src={data.imageUrl} alt="KTP" width="150" /></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
};

const styles = {
    selectWrapper: {
        position: 'relative',
        display: 'inline-block',
        width: '100%',
    },
    select: {
        fontSize: '16px',
        padding: '10px',
        width: '100%',
        borderRadius: '4px',
        border: '1px solid #ccc',
    },
    chevronIcon: {
        position: 'absolute',
        top: '50%',
        right: '10px',
        transform: 'translateY(-50%)',
        color: '#0542cc',
    },
    remainingQuota: {
        display: 'flex',
        alignItems: 'center',
    },
    quotaText: {
        fontSize: '24px',
        fontWeight: '600',
    },
    timesText: {
        fontSize: '16px',
        fontWeight: '300',
    },
    uploadWrapper: {
        position: 'relative',
    },
    errorContainer: {
        marginTop: '10px',
        padding: '10px',
        backgroundColor: '#f8d7da',
        border: '1px solid #f5c6cb',
        borderRadius: '4px',
    },
    errorText: {
        color: '#721c24',
        fontSize: '14px',
        margin: '0',
    },
    loadingOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        color: 'white',
        fontSize: '24px',
        zIndex: 1000,
    },
    spinner: {
        border: '4px solid #f3f3f3',
        borderTop: '4px solid #3498db',
        borderRadius: '50%',
        width: '50px',
        height: '50px',
        animation: 'spin 2s linear infinite',
    },
    loadingText: {
        marginLeft: '20px',
    },
    tableStyle: {
        width: '100%',
        borderCollapse: 'collapse',
        marginTop: '20px',
    },
    tableCell: {
        padding: '8px 15px',
        border: '1px solid #ccc',
        textAlign: 'left',
    },
};

export default Verify;
