import React, { useEffect, useRef, useState } from 'react';
import { Button, Grid } from '@mui/material';
import axios from 'axios';
import { apiPath, appURL } from "../../../auth/utils";
import {
    GET_MERGE_PDF,
    GET_REMOVE_PDF_PASSWORD,
    GET_PDF_TEMPLATE_PATH,
    POST_UPLOAD_PDF_PATH
} from "../../../utils/ApiPathConst";
import { LIONER_BUTTON_THEME } from "../../../themes/colorConst";
import { ThemeProvider } from "@emotion/react";
import { useNavigate, useParams, useLocation } from "react-router-dom";

// Custom Modal for confirmations and alerts
const CustomModal = ({ isOpen, title, content, onConfirm, onCancel, showConfirmButton = true }) => {
    if (!isOpen) return null;

    return (
        <div style={{
            position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
            backgroundColor: 'rgba(0,0,0,0.5)',
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            zIndex: 1000
        }}>
            <div style={{
                backgroundColor: 'white', padding: '20px', borderRadius: '8px',
                boxShadow: '0 4px 12px rgba(0,0,0,0.15)', maxWidth: '400px', width: '90%'
            }}>
                <h3 style={{ marginTop: 0 }}>{title}</h3>
                <p style={{ whiteSpace: 'pre-wrap' }}>{content}</p>
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
                    {onCancel && (
                        <Button variant="outlined" color="primary" onClick={onCancel}>
                            Cancel
                        </Button>
                    )}
                    {showConfirmButton && (
                        <Button variant="contained" color="primary" onClick={onConfirm}>
                            OK
                        </Button>
                    )}
                </div>
            </div>
        </div>
    );
};

function PDF() {
    // No more pdfUrl or pdfEditorRef needed for in-browser editing
    // const [pdfUrl, setPdfUrl] = useState(null);
    // const pdfEditorRef = useRef(null); 

    const [record, setRecord] = useState(null); // Initialize record state for uploading

    const [modalOpen, setModalOpen] = useState(false);
    const [modalTitle, setModalTitle] = useState('');
    const [modalContent, setModalContent] = useState('');
    const [modalOnConfirm, setModalOnConfirm] = useState(() => () => {});
    const [modalOnCancel, setModalOnCancel] = useState(null);
    const [showConfirmButton, setShowConfirmButton] = useState(true);

    // Ref for the hidden file input
    const fileInputRef = useRef(null);

    const showModal = (title, content, onConfirm, onCancel = null, showConfirm = true) => {
        setModalTitle(title);
        setModalContent(content);
        setModalOnConfirm(() => {
            return () => {
                setModalOpen(false);
                onConfirm();
            };
        });
        setModalOnCancel(onCancel ? () => {
            return () => {
                setModalOpen(false);
                onCancel();
            };
        } : null);
        setShowConfirmButton(showConfirm);
        setModalOpen(true);
    };

    const navigate = useNavigate();
    const params = useParams();
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const refId = queryParams.get("refId");

    // This function now primarily handles initializing the 'record' state
    // based on whether it's a new template or an existing record.
    const initializeRecordData = async (id, templateId = 0) => {
        if (id > 0) {
            // For existing records, you might fetch record metadata if needed.
            // If GET_PDF_PATH/${id} returns JSON with client/template IDs:
            try {
                // IMPORTANT: If GET_PDF_PATH/${id} used to return the PDF blob directly,
                // and you now need JSON metadata, you might need a different endpoint
                // or adjust the responseType here (e.g., remove responseType: 'blob' or set to 'json').
                // Assuming it now might return { id, clientId, templateId, ... }
                // For simplicity, we'll just set it from params for now if not fetched.
                setRecord(prev => ({
                    ...prev,
                    id: id,
                    clientId: id, // Or fetch actual clientId if different from PDF ID
                    templateId: prev?.templateId || 0
                }));
            } catch (error) {
                console.error('Error initializing record data for existing PDF:', error);
                showModal('Error', 'Failed to load record data.', () => {});
            }
        } else {
            // For new templates/records
            setRecord({
                id: -1,
                clientId: templateId * -1, // If PDF ID is negative, convert it to client ID
                templateId: templateId,
            });
        }
        console.log('Record data initialized:', { id, templateId });
    };

    // Function to handle downloading the PDF template to the user's device
    const handleDownloadTemplateToDevice = async () => {
        try {
            const response = await axios.get(`${apiPath}${GET_PDF_TEMPLATE_PATH}`, {
                responseType: 'blob', // Crucial: get the response as a binary blob
            });

            if (response.status === 200) {
                const blob = response.data;
                const url = URL.createObjectURL(blob);
                
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'PDF_Template.pdf'); // Set desired filename
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url); // Clean up the object URL

                showModal(
                    'Download Success',
                    'PDF template downloaded to your device! Please fill it externally and then upload.',
                    () => {}, // Empty function, just closes modal
                    null,
                    true // Show OK button to dismiss the modal
                );
            } else {
                showModal('Download Failed', `Failed to download template. Status: ${response.status}`, () => {});
            }
        } catch (error) {
            console.error('Error downloading PDF template to device:', error);
            showModal('Download Error', 'Could not download PDF template. Please try again.', () => {});
        }
    };

    // --- New Function for Uploading Filled PDF ---
    const handleFileUploadChange = async (event) => {
        const file = event.target.files[0];
        if (!file) {
            showModal('Upload Cancelled', 'No file selected.', () => {}, null, false);
            return;
        }

        if (file.type !== 'application/pdf') {
            showModal('Invalid File Type', 'Please upload a PDF file.', () => {});
            return;
        }

        if (!record) {
            showModal('Upload Error', 'Record data missing. Cannot upload.', () => {});
            return;
        }

        try {
            const formData = new FormData();
            formData.append('file', file, file.name);
            formData.append('record', JSON.stringify(record));

            // --- START OF AUTHENTICATION ADDITION ---
            const token = localStorage.getItem('accessToken'); // Assuming your JWT token is stored here
            if (!token) {
                showModal('Authorization Error', 'No access token found. Please log in again.', () => {});
                return; // Stop the upload if no token
            }

            const headers = {
                'Authorization': `Bearer ${token}` // Add the Authorization header with your token
                // 'Content-Type': 'multipart/form-data' is automatically set by fetch when body is FormData
            };
            // --- END OF AUTHENTICATION ADDITION ---

            console.log('Attempting to upload file:', file.name, 'with record:', JSON.stringify(record));
            console.log('Sending to URL:', `${apiPath}${POST_UPLOAD_PDF_PATH}`); // Verify the full URL
            console.log('Sending with Authorization header:', headers['Authorization']); // Verify token is sent

            const response = await fetch(`${apiPath}${POST_UPLOAD_PDF_PATH}`, {
                method: 'POST',
                body: formData,
                headers: headers, // Pass the headers object here
                credentials: 'include' // Use 'include' if your backend relies on session cookies/credentials, even if it's JWT. It helps if the browser considers forms.lioner.com and forms.lioner.com:8090 as different origins due to the port.
            });

            if (response.ok) {
                const result = await response.text();
                showModal('Upload Success', result, () => {
                    // Optional: Navigate after successful upload
                    // if (record && record.clientId !== undefined) {
                    //     navigate(`/pdf/${record.clientId}`);
                    // } else {
                    //     navigate('/some-default-path-or-home');
                    // }
                });
            } else {
                const errorText = await response.text();
                console.error('Failed to upload PDF. Backend response:', errorText);
                // Provide more specific error if backend sends a message
                showModal('Upload Failed', `Failed to upload PDF. Server said: ${errorText || response.statusText}.`, () => {});
            }
        } catch (error) {
            console.error('Error uploading PDF:', error);
            showModal('Upload Error', `Error uploading PDF: ${error.message}.`, () => {});
        }
    };

    // Function to trigger the hidden file input click
    const triggerFileUpload = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click();
        }
    };
    // --- End of New Function ---

    useEffect(() => {
        if (params.id !== null) {
            const pdfData = (params.id).split("T");
            const id = parseInt(pdfData[0]);
            const templateId = parseInt(pdfData[1]);

            if (id > 0) {   // Existing Record
                initializeRecordData(id);
            } else {    // New Record
                initializeRecordData(-1, templateId);    // Initialize record for new Template
            }
        }
    }, [params.id]); // Dependency array: run effect when params.id changes
    
    const handleBackClick = () => {
        showModal(
            "Back to previous page",
            "Are you sure to leave this page?\nAny unsaved progress will be lost.",
            handleBack, // Confirm action
            () => setModalOpen(false) // Cancel action
        );
    };
    
    const doMerge = async () => {
        const response = await axios.get(`${apiPath}${GET_MERGE_PDF}`, {
                responseType: 'blob', // Crucial: get the response as a binary blob
            });
    };

    const doRemovePassword = async () => {
        const response = await axios.get(`${apiPath}${GET_REMOVE_PDF_PASSWORD}`, {
                responseType: 'blob',
            });
    };

    const handleBack = async () => {
        // No PDF editor to clear now
        // setPdfUrl(null); 
        if (record && record.clientId !== undefined) {
             navigate(`/pdf/${record.clientId}`);
        } else {
             // Fallback if record or clientId is not available (e.g., initial load failure)
             navigate('/some-default-path-or-home'); 
        }
    };

    return (
        <ThemeProvider theme={LIONER_BUTTON_THEME}>
            <div className="pdf-form-page" style={{ padding: '20px' }}>
                <header className="page-header">
                    <Grid item>
                        <Grid container>
                            {/* Hidden file input */}
                            <input
                                type="file"
                                ref={fileInputRef}
                                onChange={handleFileUploadChange}
                                style={{ display: 'none' }}
                                accept="application/pdf" // Only allow PDF files
                            />

                            <Grid item sx={{ ml: 3, mr: 1.5, mb: 2 }}>
                                <Button
                                    variant="contained"
                                    type="button" // Change type to button, not submit
                                    color="save"
                                    disabled={!record} // Disable if record data is not initialized
                                    onClick={triggerFileUpload} // Trigger the hidden file input
                                >
                                    Upload Filled PDF
                                </Button>
                            </Grid>
                            <Grid item sx={{ ml: { xs: 1.5, md: 1.5, lg: 1.5 }, mr: 1.5, mb: 2 }}>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={handleDownloadTemplateToDevice}
                                >
                                    Download PDF Template
                                </Button>
                            </Grid>
                            <Grid item sx={{ ml: { xs: 1.5, md: 1.5, lg: 1.5 }, mr: 1.5, mb: 2 }}>
                                <Button
                                    variant="contained"
                                    color="cancel"
                                    onClick={handleBackClick}
                                >
                                    Cancel
                                </Button>
                            </Grid>
                            <Grid item sx={{ ml: { xs: 1.5, md: 1.5, lg: 1.5 }, mr: 1.5, mb: 2 }}>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={doRemovePassword}
                                >
                                    Remove PDF Password named C:\\dev\\pdf\\pdfB.pdf
                                </Button>
                            </Grid>
                            <Grid item sx={{ ml: { xs: 1.5, md: 1.5, lg: 1.5 }, mr: 1.5, mb: 2 }}>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={doMerge}
                                >
                                    Merge PDF A B as Output
                                </Button>
                            </Grid>
                        </Grid>
                    </Grid>
                </header>
                {/* No PDF editor display needed */}
                <p>Download the PDF template, fill it out externally, then upload the completed file.</p>

                <CustomModal
                    isOpen={modalOpen}
                    title={modalTitle}
                    content={modalContent}
                    onConfirm={modalOnConfirm}
                    onCancel={modalOnCancel}
                    showConfirmButton={showConfirmButton}
                />
            </div>
        </ThemeProvider>
    );
}

export default PDF;