import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { SUBMISSIONS_URL } from '../../../utils/config';
import './styles/ViewSubmission.css';

// Create a blob URL from media stored in submission (data URL or base64 string)
function createBlobUrlFromMedia(mediaValue) {
    if (!mediaValue) return null;
    let base64 = null;
    let mime = 'image/jpeg';
    let raw = mediaValue;
    if (typeof raw !== 'string') {
        if (raw && typeof raw === 'object' && raw.type === 'Buffer' && Array.isArray(raw.data)) {
            try {
                raw = btoa(String.fromCharCode.apply(null, new Uint8Array(raw.data)));
            } catch (e) {
                return null;
            }
        } else {
            return null;
        }
    }
    raw = raw.replace(/\r?\n/g, '').replace(/\s/g, '').trim();
    if (!raw) return null;
    if (raw.startsWith('data:')) {
        const comma = raw.indexOf(',');
        if (comma === -1) return null;
        const m = raw.match(/^data:([^;]+);/);
        if (m) mime = m[1].trim();
        base64 = raw.slice(comma + 1);
    } else {
        base64 = raw;
    }
    if (!base64) return null;
    try {
        // Fix base64: restore URL-safe chars, add padding if needed
        let b64 = base64.replace(/-/g, '+').replace(/_/g, '/');
        const pad = b64.length % 4;
        if (pad) b64 += '='.repeat(4 - pad);
        const binary = atob(b64);
        const bytes = new Uint8Array(binary.length);
        for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
        const blob = new Blob([bytes], { type: mime });
        return URL.createObjectURL(blob);
    } catch (e) {
        return null;
    }
}

// Hook: create and hold a blob URL from inline media, revoke on unmount
function useMediaBlobUrl(inlineMedia) {
    const [url, setUrl] = useState(null);
    const ref = useRef(null);
    useEffect(() => {
        const blobUrl = createBlobUrlFromMedia(inlineMedia);
        if (blobUrl) {
            ref.current = blobUrl;
            setUrl(blobUrl);
        } else {
            setUrl(null);
        }
        return () => {
            if (ref.current) {
                URL.revokeObjectURL(ref.current);
                ref.current = null;
            }
            setUrl(null);
        };
    }, [inlineMedia]);
    return url;
}

// Fetch media from API when inline is missing or failed
function useMediaApiUrl(submissionId, answersId, occurrence) {
    const [url, setUrl] = useState(null);
    const [failed, setFailed] = useState(false);
    const ref = useRef(null);
    useEffect(() => {
        if (!submissionId || !answersId || occurrence == null) return;
        const path = `${SUBMISSIONS_URL}/${submissionId}/media/${answersId}/${occurrence}`;
        axiosInstance.get(path, { responseType: 'blob' })
            .then((res) => {
                if (res.status === 200 && res.data instanceof Blob && res.data.size > 0) {
                    const u = URL.createObjectURL(res.data);
                    ref.current = u;
                    setUrl(u);
                    setFailed(false);
                } else {
                    setFailed(true);
                }
            })
            .catch(() => setFailed(true));
        return () => {
            if (ref.current) {
                URL.revokeObjectURL(ref.current);
                ref.current = null;
            }
            setUrl(null);
        };
    }, [submissionId, answersId, occurrence]);
    return { url, failed };
}

// Renders a single media item: inline media first, then API if needed
const MediaDisplay = ({ submissionId, answersId, occurrence, index, inlineMedia }) => {
    const blobUrl = useMediaBlobUrl(inlineMedia);
    const { url: apiUrl } = useMediaApiUrl(
        !blobUrl && submissionId && answersId && occurrence != null ? submissionId : null,
        !blobUrl ? answersId : null,
        !blobUrl ? occurrence : null
    );
    const displayUrl = blobUrl || apiUrl;

    if (!displayUrl) {
        return (
            <div className="media-item">
                <div className="media-placeholder">
                    <p>Media {index + 1}</p>
                    <p style={{ fontSize: '0.75rem', color: 'var(--neutral-500)' }}>
                        {inlineMedia ? 'Could not decode image' : 'Loading or no media data'}
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="media-item">
            <a
                href={displayUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="media-image-link"
                title="Open image in browser (new tab)"
            >
                <img
                    src={displayUrl}
                    alt={`Media ${index + 1}`}
                    className="media-image"
                />
            </a>
            <a
                href={displayUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="media-view-in-browser"
            >
                Tap to View
            </a>
        </div>
    );
};

const ViewSubmission = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const [submission, setSubmission] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchSubmission = async () => {
            if (!id) {
                setError('No submission ID provided');
                setLoading(false);
                return;
            }

            try {
                setLoading(true);
                const response = await axiosInstance.get(`${SUBMISSIONS_URL}/${id}`);

                if (response.data.success && response.data.data) {
                    setSubmission(response.data.data);
                } else {
                    setError('Failed to load submission details.');
                }
            } catch (error) {
                console.error('Error fetching submission:', error);
                setError('Failed to load submission details. Please try again.');
            } finally {
                setLoading(false);
            }
        };

        fetchSubmission();
    }, [id]);

    const formatDate = (dateString) => {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    const renderMedia = (mediaArray, submissionId, answersId) => {
        if (!mediaArray || mediaArray.length === 0) return null;

        return (
            <div className="media-gallery">
                {mediaArray.map((mediaItem, index) => (
                    <MediaDisplay
                        key={mediaItem.occurrence ?? index}
                        submissionId={submissionId}
                        answersId={answersId}
                        occurrence={mediaItem.occurrence ?? index + 1}
                        index={index}
                        inlineMedia={mediaItem.media}
                    />
                ))}
            </div>
        );
    };

    if (loading) {
        return (
            <div className="view-submission-container">
                <div style={{ textAlign: 'center', padding: '2rem' }}>
                    <p>Loading submission...</p>
                </div>
            </div>
        );
    }

    if (error && !submission) {
        return (
            <div className="view-submission-container">
                <div className="error-message">
                    {error}
                </div>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/submissions')}
                >
                    Go Back
                </button>
            </div>
        );
    }

    if (!submission) {
        return null;
    }

    return (
        <div className="view-submission-container">
            <div className="view-submission-header">
                <div>
                    <h1 className="view-submission-title">Submission Preview</h1>
                    <div className="submission-meta">
                        <span className="meta-item">
                            <strong>Form:</strong> {submission.form_title || 'N/A'}
                        </span>
                        <span className="meta-item">
                            <strong>Audit:</strong> {submission.audit_name || 'N/A'}
                        </span>
                        <span className="meta-item">
                            <strong>Submitted By:</strong> {submission.submitter_name || 'N/A'}
                        </span>
                        <span className="meta-item">
                            <strong>Date:</strong> {formatDate(submission.created_at)}
                        </span>
                    </div>
                </div>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/submissions')}
                >
                    Back to List
                </button>
            </div>
            {console.log("submission", submission)}

            {submission.sat_answers && submission.sat_answers.length > 0 ? (
                <div className="answers-by-version">
                    <section className="view-submission-version">
                        <h2 className="view-submission-version-title">Answers</h2>
                        <div className="answers-section">
                            
                            {submission.sat_answers.map((sat_answer, index) => (
                                <div key={sat_answer.answers_id || index} className="answer-item">
                                    <div className="answer-question">
                                        <span className="question-number">{index + 1}.</span>
                                        <span className="question-text">{sat_answer.question || 'Question not found'}</span>
                                    </div>
                                    <div className="answer-content">
                                        {sat_answer.is_media ? (
                                            <div className="answer-media">
                                                <p className="media-label">Media Answer:</p>
                                                {renderMedia(sat_answer.media, id, sat_answer.answers_id)}
                                            </div>
                                        ) : (
                                            <div className="answer-text">
                                                <p className="answer-value">{sat_answer.answer_value || 'No answer provided'}</p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </section>
                    
                </div>
            ) : (
                
                <div className="no-answers">
                    <p>No answers found for this submission.</p>
                </div>
            )}

            <div className="view-submission-actions">
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/submissions')}
                >
                    Back to List
                </button>
            </div>
        </div>
    );
};

export default ViewSubmission;
