import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { FORMS_FOR_SELECTION_URL } from '../../../utils/config';
import './styles/SelectForm.css';

// 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 SelectFormForUpdate = () => {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const auditId = searchParams.get('audit_id');
    const from = searchParams.get('from'); // 'update-audit' | 'observations' (or missing)

    const [forms, setForms] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        if (!auditId) {
            setError('No audit ID provided. Please select an audit first.');
            setLoading(false);
            return;
        }

        const fetchForms = async () => {
            try {
                setLoading(true);
                const response = await axiosInstance.get(FORMS_FOR_SELECTION_URL);

                if (response.data.success) {
                    setForms(response.data.data || []);
                } else {
                    setError('Failed to load forms.');
                }
            } catch (error) {
                console.error('Error fetching forms:', error);
                setError('Failed to load forms. Please refresh the page.');
            } finally {
                setLoading(false);
            }
        };

        fetchForms();
    }, [auditId]);

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

    if (error && !auditId) {
        return (
            <div className="select-form-container">
                <div className="error-message">
                    {error}
                </div>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate(from === 'update-audit' ? (auditId ? `/update-audit/${auditId}` : '/update-audit') : (auditId ? `/audit/${auditId}/forms` : '/audit-status'))}
                >
                    Go Back
                </button>
            </div>
        );
    }

    // Only show Opening forms (Closing forms are added via the Close flow on the observations page)
    const filteredForms = forms.filter(isOpeningForm);

    const getBackPath = () => {
        if (from === 'update-audit') return auditId ? `/update-audit/${auditId}` : '/update-audit';
        return `/audit/${auditId}/forms`;
    };

    return (
        <div className="select-form-container">
            <div className="select-form-header">
                <div>
                    <h1 className="select-form-title">Add Forms to Audit</h1>
                    <p className="select-form-subtitle">Select forms to add to this audit</p>
                </div>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate(getBackPath())}
                >
                    Back
                </button>
            </div>

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

            <div className="forms-list-container">
                {filteredForms.length === 0 ? (
                    <div style={{ padding: '2rem', color: '#4d4d4f', textAlign: 'center' }}>
                        No opening forms available
                    </div>
                ) : (
                    <div className="forms-grid">
                        {filteredForms.map(form => (
                            <div
                                key={form.form_id}
                                className="form-card"
                                onClick={() => {
                                    navigate(`/submit-form?form_id=${form.form_id}&audit_id=${auditId}`);
                                }}
                            >
                                <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
                                        className="btn btn-primary"
                                        style={{ padding: '0.5rem 1rem', fontSize: '0.875rem' }}
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            navigate(`/submit-form?form_id=${form.form_id}&audit_id=${auditId}`);
                                        }}
                                    >
                                        Add Form
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
};

export default SelectFormForUpdate;
