import React, { useState, useEffect } from 'react';
import { useNavigate } 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');

/**
 * Form selection for the create-audit draft flow.
 * Used when adding observations before audit is created (no audit_id yet).
 * Navigating to submit-form with from_create_audit=1 saves to cache instead of API.
 */
const SelectFormForCreate = () => {
    const navigate = useNavigate();
    const [forms, setForms] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchForms = async () => {
            try {
                setLoading(true);
                setError(null);
                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 {
                setLoading(false);
            }
        };
        fetchForms();
    }, []);

    const openingForms = forms.filter(isOpeningForm);
    const submitFormUrl = (formId) => `/submit-form?form_id=${formId}&from_create_audit=1`;

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

    return (
        <div className="select-form-container">
            <div className="select-form-header">
                <div>
                    <h1 className="select-form-title">Add Observation (Draft)</h1>
                    <p className="select-form-subtitle">Choose an opening form to add. Observations will be saved locally until you create the audit.</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="forms-tabs">
                <button type="button" className="tab-button active">
                    Opening Forms
                </button>
            </div>

            <div className="forms-list-container">
                {openingForms.length === 0 ? (
                    <div className="no-forms-message">
                        <p>No opening forms available</p>
                    </div>
                ) : (
                    <div className="forms-grid">
                        {openingForms.map(form => (
                            <div
                                key={form.form_id}
                                className="form-card"
                                onClick={() => navigate(submitFormUrl(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(submitFormUrl(form.form_id));
                                        }}
                                    >
                                        Open Form
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
};

export default SelectFormForCreate;
