import { useEffect, useMemo, useState } from 'react';
import { fetchUserAssessments } from '../../api.js';
import { getSessionUserId } from '../../apiConfig.js';
import {
  canUserDownloadAssessmentReport,
  isUserUploadStatusComplete,
  openUserAssessmentReport
} from './userAssessmentReport.js';
import './UserDashboard.css';

function UserDashboard({ onOpenCategory, onDownloadReport }) {
  const [assessments, setAssessments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const userId = getSessionUserId();
    if (!userId) {
      setError('Unable to identify current user.');
      setLoading(false);
      return;
    }
    fetchUserAssessments(userId)
      .then((data) => setAssessments(Array.isArray(data) ? data : []))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const getLabel = (a) => a.assessment_status_name || `Status ${a.assessment_status_id}`;

  function pillClass(a) {
    const label = getLabel(a).toLowerCase();
    if (isUserUploadStatusComplete(a)) return 'status-pill--success';
    if (label.includes('progress') || label.includes('ongoing')) return 'status-pill--info';
    if (label.includes('returned')) return 'status-pill--returned';
    if (label.includes('high') || label.includes('risk')) return 'status-pill--danger';
    return 'status-pill--warning';
  }

  const completed = assessments.filter((a) => isUserUploadStatusComplete(a));
  const started = assessments.filter((a) => {
    const l = getLabel(a).toLowerCase();
    return l.includes('progress') || l.includes('ongoing');
  });
  const notStarted = assessments.filter((a) => {
    const l = getLabel(a).toLowerCase();
    return l.includes('not started') || a.assessment_status_id === 1;
  });

  const recentActivity = useMemo(() => {
    const copy = [...assessments];
    copy.sort((a, b) => {
      const da = String(a.video_capture_date || a.created_at || '');
      const db = String(b.video_capture_date || b.created_at || '');
      if (da && db) return db.localeCompare(da);
      return Number(b.assessment_id) - Number(a.assessment_id);
    });
    return copy.slice(0, 5);
  }, [assessments]);

  if (loading) {
    return (
      <main className="dashboard-main">
        <p style={{ textAlign: 'center', padding: 40, color: 'var(--theme-gray-500)' }}>Loading dashboard...</p>
      </main>
    );
  }

  return (
    <main className="dashboard-main">
      <header className="dashboard-header">
        <div className="dashboard-header-left">
          <h1>Risk overview</h1>
          <p>
            Track your site assessments, statuses, and risk posture in one place.
          </p>
          {error && <p style={{ color: 'var(--theme-red)', fontSize: 13 }}>{error}</p>}
        </div>
      </header>

      <section className="dashboard-grid dashboard-grid--stats" aria-label="Assessment status summary">
        <button
          type="button"
          className="dashboard-card dashboard-card--green dashboard-card--clickable"
          onClick={() => onOpenCategory?.('done')}
        >
          <div>
            <div className="dashboard-card-label">Completed</div>
            <div className="dashboard-card-count">{completed.length}</div>
          </div>
          <div className="dashboard-card-footer">All controls verified</div>
        </button>

        <button
          type="button"
          className="dashboard-card dashboard-card--amber dashboard-card--clickable"
          onClick={() => onOpenCategory?.('not-started')}
        >
          <div>
            <div className="dashboard-card-label">Not started</div>
            <div className="dashboard-card-count">{notStarted.length}</div>
          </div>
          <div className="dashboard-card-footer">Ready to initiate</div>
        </button>

        <button
          type="button"
          className="dashboard-card dashboard-card--blue dashboard-card--clickable"
          onClick={() => onOpenCategory?.('in-progress')}
        >
          <div>
            <div className="dashboard-card-label">Started</div>
            <div className="dashboard-card-count">{started.length}</div>
          </div>
          <div className="dashboard-card-footer">In progress with your team</div>
        </button>
      </section>

      <section className="dashboard-layout dashboard-layout--recent" aria-labelledby="user-dash-recent-title">
        <div className="dashboard-column">
          <div className="dashboard-section">
            <div className="dashboard-section-header">
              <div>
                <div className="dashboard-section-title" id="user-dash-recent-title">Recent activity</div>
                <div className="dashboard-section-subtitle">Latest changes across your assessments</div>
              </div>
            </div>

            <div className="dashboard-table">
              <div className="dashboard-table-header">
                <span>Title</span>
                <span>Contract</span>
                <span>Status</span>
                <span>Date</span>
                <span>Report</span>
              </div>

              {recentActivity.length === 0 && (
                <div className="dashboard-table-row">
                  <span style={{ color: 'var(--theme-gray-400)' }}>No assessments yet</span>
                </div>
              )}
              {recentActivity.map((row) => (
                <div className="dashboard-table-row" key={row.assessment_id}>
                  <span>{row.video_title || '—'}</span>
                  <span>{(row.contract_details ?? row.contact_details) || '—'}</span>
                  <span>
                    <span className={`status-pill ${pillClass(row)}`} style={{ color: '#ffffff' }}>
                      {getLabel(row)}
                    </span>
                  </span>
                  <span>{row.video_capture_date || '—'}</span>
                  <span>
                    {canUserDownloadAssessmentReport(row) ? (
                      <button
                        type="button"
                        className="user-dash-report-btn"
                        onClick={() =>
                          typeof onDownloadReport === 'function'
                            ? onDownloadReport(row)
                            : openUserAssessmentReport(row)
                        }
                      >
                        Download
                      </button>
                    ) : (
                      <span className="user-dash-report-muted">—</span>
                    )}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

export default UserDashboard;
