import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { AUDITS_URL, FORMS_FOR_SELECTION_URL } from '../../../utils/config';
import { getUserIdFromToken } from '../../../utils/authUtils';
import { combineObservedDateAndTime } from '../../../utils/auditDatetime';
import {
    getCachedObservations,
    removeCachedObservation,
    getCachedAuditInfo,
    clearAllCreateAuditCache
} from '../../../utils/createAuditObservationsCache';
import SuccessPopup from '../../common/SuccessPopup';
import ErrorPopup from '../../common/ErrorPopup';
import { useScrollToError } from '../../../hooks/useScrollToError';
import './styles/SelectForm.css';

const MIN_OBSERVATIONS_REQUIRED = 2;

/**
 * Second page in the audit creation flow.
 * User selects and fills observations here. All observations are cached until Create Audit is clicked.
 */
// Helper: Opening Form = form_type_id 1 or form_type string match
const isOpeningForm = (form) =>
    Number(form.form_type_id) === 1 ||
    (form.form_type || '').toLowerCase().includes('opening');

const CreateAuditObservationsPage = () => {
    const navigate = useNavigate();
    const [forms, setForms] = useState([]);
    const [loading, setLoading] = useState(false);
    const [fetchingForms, setFetchingForms] = useState(true);
    const [error, setError] = useState(null);
    const [cachedObservations, setCachedObservations] = useState([]);
    const [showPopup, setShowPopup] = useState(false);
    const [popupMessage, setPopupMessage] = useState('');
    const [createdAuditId, setCreatedAuditId] = useState(null);

    useScrollToError(error);

    useEffect(() => {
        setCachedObservations(getCachedObservations());
    }, []);

    // Redirect if audit info is missing (user arrived without filling Create Audit first)
    useEffect(() => {
        const auditInfo = getCachedAuditInfo();
        if (!auditInfo || !auditInfo.auditor_id) {
            navigate('/create-audit', { replace: true, state: { message: 'Please fill the audit details first, then add observations.' } });
        }
    }, [navigate]);

    useEffect(() => {
        const fetchForms = async () => {
            try {
                setFetchingForms(true);
                const formsRes = await axiosInstance.get(FORMS_FOR_SELECTION_URL);
                if (formsRes.data.success) {
                    setForms(formsRes.data.data || []);
                } else {
                    setError('Failed to load forms.');
                }
            } catch (err) {
                console.error('Error fetching forms:', err);
                setError('Failed to load forms. Please refresh the page.');
            } finally {
                setFetchingForms(false);
            }
        };
        fetchForms();
    }, []);

    const openingForms = forms.filter(isOpeningForm);
    const hasEnoughObservations = cachedObservations.length >= MIN_OBSERVATIONS_REQUIRED;

    const getSubmitFormUrl = (formId) =>
        `/submit-form?form_id=${formId}&from_create_audit=1&return_to=${encodeURIComponent('/create-audit-observations')}`;

    const handleRemoveObservation = (index) => {
        removeCachedObservation(index);
        setCachedObservations(getCachedObservations());
    };

    const handleCreateAudit = async () => {
        setLoading(true);
        setError(null);

        const auditInfo = getCachedAuditInfo();
        if (!auditInfo || !auditInfo.auditor_id) {
            setError('Audit information is missing. Please go back to Create Audit and fill the form first.');
            setLoading(false);
            return;
        }

        const observations = getCachedObservations();
        if (!observations || observations.length < MIN_OBSERVATIONS_REQUIRED) {
            setError(`Add at least ${MIN_OBSERVATIONS_REQUIRED} observations before creating the audit.`);
            setLoading(false);
            return;
        }

        try {
            const auditorId = Number(auditInfo.auditor_id);
            const countryId = Number(auditInfo.country);
            const locationId = Number(auditInfo.location);
            const workAreaId = Number(auditInfo.work_area);
            if (isNaN(auditorId) || isNaN(countryId) || isNaN(locationId) || isNaN(workAreaId)) {
                setError('Invalid audit data. Please go back and fill the form again.');
                setLoading(false);
                return;
            }

            const userId = Number(getUserIdFromToken());
            
            const payload = {
                auditor_id: auditorId,
                audit_name: (auditInfo.audit_name || '').trim(),
                country: countryId,
                location: locationId,
                work_area: workAreaId,
                observed_at: (auditInfo.observed_at || '').trim() || undefined,
                observations: observations.map(obs => ({
                    submitter_id: obs.submitter_id || userId,
                    form_id: obs.form_id,
                    sat_answers: obs.sat_answers || []
                }))
            };
            if (auditInfo.start_time?.trim()) {
                payload.start_time = combineObservedDateAndTime(
                    auditInfo.observed_at,
                    auditInfo.start_time.trim()
                );
            }
            if (auditInfo.end_time?.trim()) {
                payload.end_time = combineObservedDateAndTime(
                    auditInfo.observed_at,
                    auditInfo.end_time.trim()
                );
            }
            if (auditInfo.coauditors?.length > 0) {
                payload.sat_coauditors = auditInfo.coauditors.map(co => ({
                    co_auditor_type: co.co_auditor_type,
                    co_auditor_user_id: co.co_auditor_user_id ?? undefined,
                    external_auditor_id: co.external_auditor_id ?? undefined,
                    co_auditor_name: co.co_auditor_name ?? undefined,
                }));
            }
            const auditeeIds = (auditInfo.auditees || [])
                .map((id) => Number(id))
                .filter((n) => !isNaN(n) && n > 0);
            if (auditeeIds.length > 0) payload.sat_auditees = auditeeIds;
            if (!payload.observed_at) delete payload.observed_at;

            const response = await axiosInstance.post(AUDITS_URL, payload);
            const isSuccess = response.data?.success === true || (response.status === 201 && response.data?.data?.audit_id);

            if (isSuccess) {
                const auditId = response.data.data?.audit_id;
                
                clearAllCreateAuditCache();
                setCreatedAuditId(auditId);
                setPopupMessage(`Audit created successfully with ${observations.length} observations! Redirecting to My Audits...`);
                setShowPopup(true);
            } else {
                setError(response.data?.message || 'Failed to create audit. Please try again.');
            }
        } catch (err) {
            console.error('Error creating audit:', err);
            setError(
                err.response?.data?.message ||
                err.response?.data?.error ||
                (err.response ? `Server error: ${err.response.status}` : err.message) ||
                'Failed to create audit. Please try again.'
            );
        } finally {
            setLoading(false);
        }
    };

    const handlePopupClose = () => {
        setShowPopup(false);
        // Always redirect to My Audits when closing this success popup (only shown after successful create)
        navigate('/my-audits');
    };

    const auditInfo = getCachedAuditInfo();

    return (
        <>
            <SuccessPopup show={showPopup} message={popupMessage} onClose={handlePopupClose} onOk={handlePopupClose} />
            <ErrorPopup show={!!error} message={error || ''} onClose={() => setError(null)} />
            <div className="select-form-container">
                <div className="select-form-header">
                    <div>
                        <h1 className="select-form-title">Add Observations</h1>
                        <p className="select-form-subtitle">
                            Step 2: Select opening forms and fill them. Add at least {MIN_OBSERVATIONS_REQUIRED} observations.
                        </p>
                        {auditInfo?.audit_name && (
                            <p style={{ marginTop: '0.35rem', fontSize: '0.875rem', color: '#4d4d4f' }}>
                                Audit: <strong>{auditInfo.audit_name}</strong>
                            </p>
                        )}
                    </div>
                    <button className="btn btn-secondary" onClick={() => navigate('/create-audit')}>
                        Back to Create Audit
                    </button>
                </div>

                {error && <div className="error-message">{error}</div>}

                <div
                    className={`select-form-observation-requirement ${hasEnoughObservations ? 'requirement-met' : 'requirement-pending'}`}
                    style={{ marginBottom: '1rem' }}
                >
                    <span className="requirement-label">Observations:</span>
                    <span className="requirement-count">
                        {cachedObservations.length} of {MIN_OBSERVATIONS_REQUIRED}
                    </span>
                </div>

                {/* Observations list */}
                {cachedObservations.length > 0 && (
                    <div style={{ marginBottom: '1.5rem' }}>
                        <h3 style={{ fontSize: '0.9375rem', marginBottom: '0.5rem', fontWeight: 600 }}>Added observations</h3>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                            {cachedObservations.map((obs, idx) => (
                                <div
                                    key={idx}
                                    className="coauditor-item"
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        padding: '0.5rem 0.75rem',
                                        background: '#f8f9fa',
                                        borderRadius: '6px'
                                    }}
                                >
                                    <span>{idx + 1}. {obs.form_title || `Form ${obs.form_id}`}</span>
                                    <button
                                        type="button"
                                        className="btn-remove"
                                        onClick={() => handleRemoveObservation(idx)}
                                        aria-label={`Remove observation ${idx + 1}`}
                                    >
                                        ×
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Form selection */}
                <div className="forms-tabs">
                    <button type="button" className="tab-button active">
                        Opening Forms
                    </button>
                </div>

                <div className="forms-list-container">
                    {fetchingForms ? (
                        <div style={{ textAlign: 'center', padding: '2rem' }}>Loading forms...</div>
                    ) : openingForms.length === 0 ? (
                        <div className="no-forms-message">
                            <p>No opening forms available to add observations.</p>
                            <p style={{ marginTop: '0.5rem', fontSize: '0.875rem', color: '#6b7280' }}>
                                Create an Opening Form from the Forms section first, or ensure forms are not archived.
                            </p>
                        </div>
                    ) : (
                        <div className="forms-grid">
                            {openingForms.map(form => (
                                <div
                                    key={form.form_id}
                                    className="form-card"
                                    onClick={() => navigate(getSubmitFormUrl(form.form_id))}
                                >
                                    <div className="form-card-header">
                                        <h3 className="form-card-title">{form.title}</h3>
                                        {form.form_type && <span className="form-card-type">{form.form_type}</span>}
                                    </div>
                                    {form.description && (
                                        <p className="form-card-description">{form.description}</p>
                                    )}
                                    <div className="form-card-footer">
                                        <span className="form-card-questions">
                                            {form.question_count || form.questions?.length || 0} question(s)
                                        </span>
                                        <button
                                            type="button"
                                            className="btn btn-primary"
                                            style={{ padding: '0.5rem 1rem', fontSize: '0.875rem' }}
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                navigate(getSubmitFormUrl(form.form_id));
                                            }}
                                        >
                                            Fill Form
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <div style={{ marginTop: '1.5rem', display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
                    <button
                        type="button"
                        className="btn btn-primary"
                        disabled={loading || !hasEnoughObservations}
                        onClick={handleCreateAudit}
                        title={!hasEnoughObservations ? `Add at least ${MIN_OBSERVATIONS_REQUIRED} observations` : ''}
                    >
                        {loading ? 'Creating...' : 'Create Audit'}
                    </button>
                    <button type="button" className="btn btn-secondary" onClick={() => navigate('/create-audit')}>
                        Back
                    </button>
                </div>
            </div>
        </>
    );
};

export default CreateAuditObservationsPage;
