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

const MIN_OBSERVATIONS_REQUIRED = 2;

// Helpers: form type matching by ID or string
const isOpeningForm = (form) =>
    Number(form.form_type_id) === 1 ||
    (form.form_type || '').toLowerCase().includes('opening');
const isClosingForm = (form) =>
    Number(form.form_type_id) === 2 ||
    (form.form_type || '').toLowerCase().includes('closing');

const SelectForm = () => {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const auditId = searchParams.get('audit_id');

    const [forms, setForms] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [activeTab, setActiveTab] = useState('opening'); // keep state for compatibility, but only use opening
    const [observationCount, setObservationCount] = useState(0);

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

        const fetchFormsAndSubmissions = async () => {
            try {
                setLoading(true);
                setError(null);
                const [formsRes, submissionsRes] = await Promise.all([
                    axiosInstance.get(FORMS_FOR_SELECTION_URL),
                    axiosInstance.get(`${SUBMISSIONS_URL}?audit_id=${auditId}`)
                ]);

                if (formsRes.data.success) {
                    setForms(formsRes.data.data || []);
                } else {
                    setError('Failed to load forms.');
                }

                // Opening observations = submissions with form_type_id 1
                if (submissionsRes.data?.success && Array.isArray(submissionsRes.data.data)) {
                    const openingCount = submissionsRes.data.data.filter(
                        (s) => Number(s.form_type_id) === 1
                    ).length;
                    setObservationCount(openingCount);
                }
            } catch (err) {
                console.error('Error fetching data:', err);
                setError('Failed to load forms. Please refresh the page.');
            } finally {
                setLoading(false);
            }
        };

        fetchFormsAndSubmissions();
    }, [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('/create-audit')}
                >
                    Go Back to Create Audit
                </button>
            </div>
        );
    }

    // Filter forms based on active tab
    const filteredForms = forms.filter(form => {
        if (activeTab === 'opening') {
            return isOpeningForm(form);
        } else {
            return isClosingForm(form);
        }
    });

    const hasEnoughObservations = observationCount >= MIN_OBSERVATIONS_REQUIRED;
    const returnToSelectForm = `/select-form?audit_id=${auditId}`;

    return (
        <div className="select-form-container">
            <div className="select-form-header">
                <div>
                    <h1 className="select-form-title">Select Form to Submit</h1>
                    <p className="select-form-subtitle">Choose a form to fill out for this audit</p>
                </div>
                <div className="select-form-header-actions">
                    <button
                        className="btn btn-primary"
                        disabled={!hasEnoughObservations}
                        onClick={() => navigate(`/audit/${auditId}/forms`)}
                        title={hasEnoughObservations ? 'View audit and observations' : `Add at least ${MIN_OBSERVATIONS_REQUIRED} observations to continue`}
                    >
                        View audit & observations
                    </button>
                    <button
                        className="btn btn-secondary"
                        onClick={() => navigate('/create-audit')}
                    >
                        Back
                    </button>
                </div>
            </div>

            {/* Requirement: at least 2 observations */}
            <div
                className={`select-form-observation-requirement ${hasEnoughObservations ? 'requirement-met' : 'requirement-pending'}`}
                role="status"
                aria-live="polite"
            >
                <span className="requirement-label">Observations required:</span>
                <span className="requirement-count">
                    {observationCount} of {MIN_OBSERVATIONS_REQUIRED}
                </span>
                {!hasEnoughObservations && (
                    <span className="requirement-hint">
                        Add at least {MIN_OBSERVATIONS_REQUIRED} opening form submission(s) before you can continue.
                    </span>
                )}
            </div>

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

            {/* Tabs - only Opening Forms visible on create flow */}
            <div className="forms-tabs">
                <button
                    type="button"
                    className={`tab-button ${activeTab === 'opening' ? 'active' : ''}`}
                    onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setActiveTab('opening');
                    }}
                >
                    Opening Forms
                </button>
            </div>

            {/* Forms List */}
            <div className="forms-list-container">
                {filteredForms.length === 0 ? (
                    <div className="no-forms-message">
                        <p>No {activeTab === 'opening' ? 'opening' : 'closing'} forms available</p>
                    </div>
                ) : (
                    <div className="forms-grid">
                        {filteredForms.map(form => {
                            const submitFormUrl = `/submit-form?form_id=${form.form_id}&audit_id=${auditId}&return_to=${encodeURIComponent(returnToSelectForm)}`;
                            return (
                                <div 
                                    key={form.form_id} 
                                    className="form-card"
                                    onClick={() => navigate(submitFormUrl)}
                                >
                                    <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(submitFormUrl);
                                            }}
                                        >
                                            Open Form
                                        </button>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>
        </div>
    );
};

export default SelectForm;
