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

/**
 * Frontend helper mirroring backend canUserAddObservations:
 * Only the auditor or internal co-auditors (not external) can add observations.
 */
const canUserAddObservationsFrontend = (audit, userId) => {
  if (!audit || userId == null) return false;
  if (Number(audit.auditor_id) === Number(userId)) return true;
  const coauditors = audit.coauditors || [];
  const isInternalCoauditor = (c) =>
    Number(c.co_auditor_type) === 0 ||
    c.co_auditor_type === false ||
    c.co_auditor_type === '0';
  return coauditors.some(
    (c) =>
      isInternalCoauditor(c) &&
      c.co_auditor_user_id != null &&
      Number(c.co_auditor_user_id) === Number(userId)
  );
};

const AuditFormsPage = () => {
  const navigate = useNavigate();
  const { auditId } = useParams();
  const [audit, setAudit] = useState(null);
  const [submissions, setSubmissions] = useState([]);
  const [openingClosingPairs, setOpeningClosingPairs] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!auditId) return;
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        const [auditRes, submissionsRes, pairsRes] = await Promise.all([
          axiosInstance.get(`${AUDITS_URL}/${auditId}`),
          axiosInstance.get(`${SUBMISSIONS_URL}?audit_id=${auditId}`),
          axiosInstance.get(`${AUDITS_URL}/${auditId}/opening-closing-pairs`).catch(() => ({ data: { success: false } }))
        ]);
        if (auditRes.data.success && auditRes.data.data) {
          setAudit(auditRes.data.data);
        }
        if (submissionsRes.data.success && Array.isArray(submissionsRes.data.data)) {
          setSubmissions(submissionsRes.data.data);
        }
        if (pairsRes.data?.success && pairsRes.data.data) {
          setOpeningClosingPairs(pairsRes.data.data);
        }
      } catch (err) {
        console.error('Error fetching audit observations:', err);
        setError('Failed to load data. Please try again.');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [auditId]);

  const formatDate = (dateStr) => {
    if (!dateStr) return 'N/A';
    const d = new Date(dateStr);
    return d.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // Opening observations = submissions of Opening forms (form_type_id 1)
  const openingObservations = submissions.filter((s) => Number(s.form_type_id) === 1);
  const openingIdsWithClosing = openingClosingPairs?.pairs?.map((p) => p.opening_sub_id) || [];
  const openingIdsWithoutClosing = openingClosingPairs?.openingsWithoutClosing?.map((o) => o.submission_id) || [];

  const isObservationClosed = (submissionId) => openingIdsWithClosing.includes(submissionId);

  if (loading) {
    return (
      <div className="audit-forms-page">
        <div className="audit-forms-page-loading">
          <p>Loading…</p>
        </div>
      </div>
    );
  }

  const loggedInUserId = getUserIdFromToken();
  const canAddObservations = canUserAddObservationsFrontend(audit, loggedInUserId);
  const isAuditClosed = audit && String(audit.audit_status_name || '').trim().toLowerCase() === 'closed';

  return (
    <div className="audit-forms-page">
      <div className="audit-forms-page-header">
        <div>
          <h1 className="audit-forms-page-title">
            Observations: {audit?.audit_name || `#${auditId}`}
          </h1>
          <p className="audit-forms-page-subtitle">Audit ID: #{auditId}</p>
        </div>
        <div className="audit-forms-page-header-actions">
          {canAddObservations && !isAuditClosed && (
            <button
              type="button"
              className="btn btn-primary"
              onClick={() =>
                navigate(
                  `/select-form-update?audit_id=${auditId}&opening_form_count=${openingObservations.length}&from=observations`
                )
              }
            >
              Add observations
            </button>
          )}
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/audit-status')}
          >
            Back to Audit Status
          </button>
        </div>
      </div>

      {error && (
        <div className="audit-forms-page-error">
          {error}
        </div>
      )}

      {openingClosingPairs && !openingClosingPairs.allOpeningsHaveClosing && openingIdsWithoutClosing.length > 0 && (
        <div className="audit-forms-page-warning">
          <strong>Opening–Closing link:</strong> {openingIdsWithoutClosing.length} observation(s) do not have a closing yet. Use the Close button to add a closing form for each opening observation.
        </div>
      )}

      {openingObservations.length === 0 ? (
        <div className="audit-forms-page-empty">
          <p>No observations in this audit yet. Add opening form submissions from the form selection page.</p>
        </div>
      ) : (
        <div className="audit-forms-page-sections">
          <section className="audit-forms-section">
            <h2 className="audit-forms-section-title">
              <span className="audit-forms-section-name">Observations list</span>
              <span className="audit-forms-section-count">
                {openingObservations.length} observation{openingObservations.length !== 1 ? 's' : ''}
              </span>
            </h2>
            <div className="audit-forms-section-table-wrap">
              <table className="audit-forms-table">
                <thead>
                  <tr>
                    <th>Form</th>
                    <th>Submission</th>
                    <th>Submitted by</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {openingObservations.map((sub) => {
                    const closed = isObservationClosed(sub.submission_id);
                    return (
                      <tr key={sub.submission_id}>
                        <td>{sub.form_title || '—'}</td>
                        <td>#{sub.submission_id}</td>
                        <td>{sub.submitter_name || '—'}</td>
                        <td>{formatDate(sub.created_at)}</td>
                        <td>
                          <span className={`audit-forms-status-badge ${closed ? 'audit-forms-status-closed' : 'audit-forms-status-open'}`}>
                            {closed ? 'Closed' : 'Open'}
                          </span>
                        </td>
                        <td>
                          <div className="audit-forms-observation-actions">
                            <button
                              type="button"
                              className="btn btn-primary btn-sm"
                              onClick={() => navigate(`/view-submission/${sub.submission_id}`)}
                            >
                              View
                            </button>
                            {closed ? (
                              <button type="button" className="btn btn-sm btn-closed" disabled title="This observation is closed">
                                Closed
                              </button>
                            ) : (
                              <button
                                type="button"
                                className="btn btn-sm btn-close"
                                onClick={() => navigate(`/audit/${auditId}/close/${sub.submission_id}`)}
                              >
                                Close
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </section>
        </div>
      )}
    </div>
  );
};

export default AuditFormsPage;
