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

const FORM_TYPE_CLOSING_ID = 2;

const SelectClosingForm = () => {
  const navigate = useNavigate();
  const { auditId, openingSubmissionId } = useParams();
  const [audit, setAudit] = useState(null);
  const [closingForms, setClosingForms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!auditId || !openingSubmissionId) {
      setError('Missing audit or observation. Please go back to observations.');
      setLoading(false);
      return;
    }

    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        const [auditRes, formsRes] = await Promise.all([
          axiosInstance.get(`${AUDITS_URL}/${auditId}`),
          axiosInstance.get(FORMS_FOR_SELECTION_URL)
        ]);

        if (auditRes.data.success && auditRes.data.data) {
          setAudit(auditRes.data.data);
        } else {
          setError('Audit not found.');
        }

        if (formsRes.data.success && Array.isArray(formsRes.data.data)) {
          const all = formsRes.data.data;
          const closing = all.filter(
            (f) => Number(f.form_type_id) === FORM_TYPE_CLOSING_ID || (f.form_type && String(f.form_type).toLowerCase().includes('closing'))
          );
          setClosingForms(closing);
        } else {
          setClosingForms([]);
        }
      } catch (err) {
        console.error('Error fetching data:', err);
        setError('Failed to load data. Please try again.');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [auditId, openingSubmissionId]);

  const handleSelectForm = (formId) => {
    const returnTo = `/audit/${auditId}/forms`;
    const url = `/submit-form?form_id=${formId}&audit_id=${auditId}&opening_sub_id=${openingSubmissionId}&return_to=${encodeURIComponent(returnTo)}`;
    navigate(url);
  };

  const goBack = () => navigate(`/audit/${auditId}/forms`);

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

  if (error && !audit) {
    return (
      <div className="select-form-container">
        <div className="error-message">{error}</div>
        <button type="button" className="btn btn-secondary" onClick={() => navigate('/audit-status')}>
          Back to Audit Status
        </button>
      </div>
    );
  }

  return (
    <div className="select-form-container">
      <div className="select-form-header">
        <div>
          <h1 className="select-form-title">Select closing form</h1>
          <p className="select-form-subtitle">
            Audit: {audit?.audit_name || `#${auditId}`} — Link closing to observation #{openingSubmissionId}
          </p>
        </div>
        <button type="button" className="btn btn-secondary" onClick={goBack}>
          Back
        </button>
      </div>

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

      <div className="forms-list-container">
        {closingForms.length === 0 ? (
          <div style={{ padding: '2rem', color: '#4d4d4f', textAlign: 'center' }}>
            No closing forms available. Add closing forms in Form Management first.
          </div>
        ) : (
          <div className="forms-grid">
            {closingForms.map((form) => (
              <div
                key={form.form_id}
                className="form-card"
                onClick={() => handleSelectForm(form.form_id)}
              >
                <div className="form-card-header">
                  <h3 className="form-card-title">{form.title || 'Untitled'}</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();
                      handleSelectForm(form.form_id);
                    }}
                  >
                    Fill form
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default SelectClosingForm;
