import { useCallback, useEffect, useMemo, useState } from 'react';
import { getSessionUserId } from '../../apiConfig.js';
import { fetchAssessmentStatuses, fetchAssessmentsForExecutor, fetchAssessmentsForVerifier } from '../../api.js';
import {
  buildCategoryMapsFromStatuses,
  categorizeAssignmentRow,
  categorizeExecutorRow,
  categorizeVerifierRow,
  countByCategory,
  getAssignmentStatusDisplayLabel,
  getAssessmentStatusLabel,
  getVerifierReturnRemarks
} from './executorAssignmentCategories.js';
import QueueStatusSummaryBar from './QueueStatusSummaryBar.jsx';
import ExecutorAssessmentDetail from './ExecutorAssessmentDetail.jsx';
import ExecutorAssignmentDocument from './ExecutorAssignmentDocument.jsx';
import SnapDetailCreatePage from './SnapDetailCreatePage.jsx';
import VerifierRiskDocument from './VerifierRiskDocument.jsx';
import '../user/UserMyVideosPage.css';
import './ExecutorAssignments.css';

/** Page title suffix when a workflow bucket filter is active (role-specific names). */
function semanticFilterHeadingLabel(roleView, key) {
  if (roleView === 'verifier') {
    const v = {
      all: 'All',
      done: 'Done',
      in_process: 'Resubmitted by executor',
      not_started: 'Not started',
      returned: 'Returned to executor'
    };
    return v[key] || key;
  }
  const e = {
    all: 'All',
    done: 'Done',
    not_started: 'Not started',
    verification_required: 'Submitted to Verifier',
    returned: 'Returned by verifier'
  };
  return e[key] || key;
}

const EXECUTOR_BUCKET_TABS = [
  { key: 'all', label: 'All' },
  { key: 'not_started', label: 'Not started' },
  { key: 'verification_required', label: 'Submitted to Verifier' },
  { key: 'returned', label: 'Returned by verifier' },
  { key: 'done', label: 'Done' }
];

const VERIFIER_BUCKET_TABS = [
  { key: 'all', label: 'All' },
  { key: 'not_started', label: 'Not started' },
  { key: 'in_process', label: 'Resubmitted by executor' },
  { key: 'returned', label: 'Returned to executor' },
  { key: 'done', label: 'Done' }
];

function ExecutorAssignedPage({
  assignmentsLink,
  onAssignmentsLinkConsumed,
  onNavigateExecutorVideos,
  onNavigateToReview,
  onNavigateExecutorDashboard,
  routePreset
}) {
  const [videos, setVideos] = useState([]);
  const [statusList, setStatusList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [roleView, setRoleView] = useState(() => assignmentsLink?.view || routePreset?.view || 'executor');
  const [semanticFilter, setSemanticFilter] = useState(
    () => assignmentsLink?.category || routePreset?.category || 'all'
  );
  const [selectedAssessment, setSelectedAssessment] = useState(null);
  const [assignmentDocOpen, setAssignmentDocOpen] = useState(false);
  const [verifierReviewAssessment, setVerifierReviewAssessment] = useState(null);
  const [snapRiskDraft, setSnapRiskDraft] = useState(null);
  /** Seek video to this time (seconds) when returning from snap ORAC form. */
  const [snapResumeSeek, setSnapResumeSeek] = useState(null);
  const [assessmentDetailNotice, setAssessmentDetailNotice] = useState(null);

  useEffect(() => {
    setAssignmentDocOpen(false);
  }, [selectedAssessment?.assessment_id]);

  useEffect(() => {
    fetchAssessmentStatuses()
      .then((rows) => setStatusList(Array.isArray(rows) ? rows : []))
      .catch(() => setStatusList([]));
  }, []);

  const { executorMap } = useMemo(() => buildCategoryMapsFromStatuses(statusList), [statusList]);

  const categorizeRow = useCallback(
    (v) => categorizeAssignmentRow(v, { roleView, executorMap }),
    [roleView, executorMap]
  );

  const queueCounts = useMemo(
    () =>
      countByCategory(
        videos,
        roleView === 'verifier' ? categorizeVerifierRow : categorizeExecutorRow,
        // Verifier buckets for status 5 depend on `vf_max_occurrence`; do not use static status-id map.
        roleView === 'verifier' ? null : executorMap
      ),
    [videos, roleView, executorMap]
  );

  const load = useCallback((view) => {
    const userId = getSessionUserId();
    if (!userId) {
      setError('Unable to identify current user.');
      setLoading(false);
      return Promise.resolve();
    }

    setLoading(true);
    setError('');

    const req =
      view === 'verifier' ? fetchAssessmentsForVerifier() : fetchAssessmentsForExecutor();

    return req
      .then((vids) => setVideos(Array.isArray(vids) ? vids : []))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    load(roleView);
  }, [load, roleView]);

  useEffect(() => {
    if (semanticFilter === 'other') setSemanticFilter('all');
  }, [semanticFilter]);

  useEffect(() => {
    if (assignmentsLink?.token) {
      setRoleView(assignmentsLink.view);
      setSemanticFilter(assignmentsLink.category ?? 'all');
      setFilterStatus('all');
      onAssignmentsLinkConsumed?.();
      return;
    }
    if (routePreset) {
      setRoleView(routePreset.view);
      setSemanticFilter(routePreset.category ?? 'all');
      setFilterStatus('all');
    }
  }, [assignmentsLink, routePreset, onAssignmentsLinkConsumed]);

  const filtered = videos.filter((v) => {
    const matchesSearch =
      !search ||
      (v.video_title || '').toLowerCase().includes(search.toLowerCase()) ||
      ((v.contract_details ?? v.contact_details) || '').toLowerCase().includes(search.toLowerCase()) ||
      (v.remarks || '').toLowerCase().includes(search.toLowerCase()) ||
      (getVerifierReturnRemarks(v) || '').toLowerCase().includes(search.toLowerCase());
    const matchesStatus =
      filterStatus === 'all' || String(v.assessment_status_id) === filterStatus;
    const cat = categorizeRow(v);
    const matchesSemantic = semanticFilter === 'all' || cat === semanticFilter;
    return matchesSearch && matchesStatus && matchesSemantic;
  });

  const statusIds = [...new Set(videos.map((v) => String(v.assessment_status_id)))];

  function pillClassForRow(v) {
    const cat = categorizeRow(v);
    if (cat === 'done') return 'status-pill--success';
    if (cat === 'in_process') return 'status-pill--info';
    if (cat === 'not_started') return 'status-pill--warning';
    if (cat === 'verification_required') return 'status-pill--verification';
    if (cat === 'returned') {
      return roleView === 'verifier' ? 'status-pill--return-ver' : 'status-pill--return-ex';
    }
    const label = getAssessmentStatusLabel(v).toLowerCase();
    if (label.includes('high') || label.includes('risk')) return 'status-pill--danger';
    return 'status-pill--neutral';
  }

  function statusLabelForId(statusId) {
    const match = videos.find((v) => String(v.assessment_status_id) === String(statusId));
    return getAssignmentStatusDisplayLabel(
      {
        assessment_status_id: statusId,
        assessment_status_name: match?.assessment_status_name
      },
      { forVerifier: roleView === 'verifier' }
    );
  }

  function statusDisplayForRow(v) {
    return getAssignmentStatusDisplayLabel(v, { forVerifier: roleView === 'verifier' });
  }

  function formatDate(val) {
    if (!val) return '--';
    try {
      const d = new Date(val);
      return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
    } catch {
      return val;
    }
  }

  const roleSubtitle =
    roleView === 'verifier'
      ? 'Assessments where you verify executor work—click a row to open the risk document; filter by workflow bucket or raw status.'
      : 'Assessments where you execute the assessment—filter by workflow bucket or raw status.';

  const bucketTabs = roleView === 'verifier' ? VERIFIER_BUCKET_TABS : EXECUTOR_BUCKET_TABS;

  const bucketCounts = useMemo(() => {
    const counts = {
      all: videos.length,
      done: 0,
      in_process: 0,
      not_started: 0,
      verification_required: 0,
      returned: 0,
      other: 0
    };
    for (const v of videos) {
      const c = categorizeRow(v);
      if (counts[c] !== undefined) counts[c] += 1;
    }
    return counts;
  }, [videos, categorizeRow]);

  const pageHeading =
    semanticFilter === 'all'
      ? 'My assignments'
      : `My assignments · ${semanticFilterHeadingLabel(roleView, semanticFilter)}`;

  const emptyPrimary =
    roleView === 'verifier'
      ? 'You have no assessments assigned as verifier yet.'
      : 'You have no assessments assigned as executor yet.';

  // ── Snap risk form (after Add Observation in modal) ──
  if (snapRiskDraft) {
    return (
      <SnapDetailCreatePage
        draft={snapRiskDraft}
        onObservationsSubmitted={({ observationCount, assessmentRow }) => {
          if (assessmentRow) {
            setSelectedAssessment((prev) => (prev ? { ...prev, ...assessmentRow } : prev));
          }
          setAssessmentDetailNotice(
            `Saved ${observationCount} observation${observationCount !== 1 ? 's' : ''} to the database. ` +
              'Open View Assignment Document when you are ready to review, remove observations, or submit the assignment to your verifier.'
          );
          load(roleView);
        }}
        onBack={(payload) => {
          if (payload != null && typeof payload === 'object' && payload.resumeVideoSeconds != null) {
            setSnapResumeSeek(Number(payload.resumeVideoSeconds));
          } else {
            setSnapResumeSeek(null);
          }
          setSnapRiskDraft(null);
          if (payload?.afterSubmit && payload?.assessment) {
            setSelectedAssessment(payload.assessment);
          }
        }}
      />
    );
  }

  // ── Executor: assignment document (saved observations, delete, submit for verification) ──
  if (selectedAssessment && assignmentDocOpen) {
    return (
      <ExecutorAssignmentDocument
        assessment={selectedAssessment}
        onBack={() => setAssignmentDocOpen(false)}
        onAssessmentUpdated={(row) => {
          if (row) setSelectedAssessment((prev) => (prev ? { ...prev, ...row } : row));
          load(roleView);
        }}
        onSubmittedToVerifier={() => {
          setAssignmentDocOpen(false);
          setSelectedAssessment(null);
          onNavigateExecutorDashboard?.();
        }}
      />
    );
  }

  // ── Verifier: risk document / sign-off (same flow as Verifier review page) ──
  if (verifierReviewAssessment) {
    return (
      <VerifierRiskDocument
        assessment={verifierReviewAssessment}
        onBack={() => {
          setVerifierReviewAssessment(null);
          load(roleView);
        }}
      />
    );
  }

  // ── Video / assessment detail ──
  if (selectedAssessment) {
    return (
      <ExecutorAssessmentDetail
        key={selectedAssessment.assessment_id}
        assessment={selectedAssessment}
        snapResumeSeekSeconds={snapResumeSeek}
        onSnapResumeSeekConsumed={() => setSnapResumeSeek(null)}
        detailNotice={assessmentDetailNotice}
        onDetailNoticeConsumed={() => setAssessmentDetailNotice(null)}
        onBack={() => setSelectedAssessment(null)}
        onOpenSnapRiskForm={(ctx) => setSnapRiskDraft(ctx)}
        onOpenAssignmentDocument={() => setAssignmentDocOpen(true)}
        onAssessmentUpdated={(row) => {
          setSelectedAssessment((prev) => (prev && row ? { ...prev, ...row } : row));
        }}
      />
    );
  }

  return (
    <main className="dashboard-main exec-assign ea-page">
      <header className="ea-hero">
        <div className="ea-hero-text">
          <p className="ea-hero-eyebrow">EHS · Risk assessment workspace</p>
          <h1 className="ea-hero-title">{pageHeading}</h1>
          <p className="ea-hero-lede">{roleSubtitle}</p>
        </div>
        {(typeof onNavigateExecutorVideos === 'function' ||
          typeof onNavigateToReview === 'function') && (
          <div className="ea-hero-actions">
            {typeof onNavigateExecutorVideos === 'function' && (
              <button
                type="button"
                className="ea-nav-btn ea-nav-btn--secondary"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  onNavigateExecutorVideos();
                }}
              >
                <span className="ea-nav-btn__label">Field videos</span>
                <span className="ea-nav-btn__hint">Executor queue</span>
              </button>
            )}
            {typeof onNavigateToReview === 'function' && (
              <button
                type="button"
                className="ea-nav-btn ea-nav-btn--primary"
                title="Open the verifier review queue"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  onNavigateToReview();
                }}
              >
                <span className="ea-nav-btn__label">Verifier review</span>
                <span className="ea-nav-btn__hint">Sign-off queue</span>
              </button>
            )}
          </div>
        )}
      </header>

      {error && <div className="exec-assign-error" role="alert">{error}</div>}

      {!loading && (
        <QueueStatusSummaryBar
          role={roleView === 'verifier' ? 'verifier' : 'executor'}
          counts={queueCounts}
          total={videos.length}
        />
      )}

      <div className="uv-filter-bar ea-stack ea-filters-panel">
        <div className="ea-filter-block">
          <span className="ea-filter-heading" id="ea-role-label">
            Perspective
          </span>
          <div className="ea-role-tabs" role="tablist" aria-labelledby="ea-role-label">
            <button
              type="button"
              data-role="executor"
              className={`ea-role-tab ${roleView === 'executor' ? 'ea-role-tab--active' : ''}`}
              onClick={() => {
                setRoleView('executor');
                setSemanticFilter('all');
                setFilterStatus('all');
                setVerifierReviewAssessment(null);
              }}
            >
              Executor
            </button>
            <button
              type="button"
              data-role="verifier"
              className={`ea-role-tab ${roleView === 'verifier' ? 'ea-role-tab--active' : ''}`}
              onClick={() => {
                setRoleView('verifier');
                setSemanticFilter('all');
                setFilterStatus('all');
                setSelectedAssessment(null);
              }}
            >
              Verifier
            </button>
          </div>
        </div>

        <div className="ea-filter-block">
          <span className="ea-filter-heading" id="ea-bucket-label">
            Workflow
          </span>
          <div className="ea-bucket-tabs" role="tablist" aria-labelledby="ea-bucket-label">
            {bucketTabs.map((tab) => (
              <button
                key={tab.key}
                type="button"
                className={`ea-bucket-tab ${semanticFilter === tab.key ? 'ea-bucket-tab--active' : ''}`}
                onClick={() => {
                  setSemanticFilter(tab.key);
                  setFilterStatus('all');
                }}
              >
                {tab.label}
                <span className="ea-bucket-count">{bucketCounts[tab.key] ?? 0}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="ea-filter-block ea-filter-block--scroll">
          <span className="ea-filter-heading" id="ea-status-label">
            System status
          </span>
          <div className="ea-status-tabs uv-filter-tabs" role="tablist" aria-labelledby="ea-status-label">
            <button
              type="button"
              className={`uv-filter-tab ${filterStatus === 'all' ? 'uv-filter-tab--active' : ''}`}
              onClick={() => {
                setFilterStatus('all');
              }}
            >
              All <span className="uv-filter-count">{videos.length}</span>
            </button>
            {statusIds.map((id) => (
              <button
                key={id}
                type="button"
                className={`uv-filter-tab ${filterStatus === id ? 'uv-filter-tab--active' : ''}`}
                onClick={() => {
                  setFilterStatus(id);
                  setSemanticFilter('all');
                }}
              >
                {statusLabelForId(id)}
                <span className="uv-filter-count">
                  {videos.filter((v) => String(v.assessment_status_id) === id).length}
                </span>
              </button>
            ))}
          </div>
        </div>

        <div className="ea-filter-block ea-filter-block--search">
          <label className="ea-filter-heading" htmlFor="ea-assignments-search">
            Search
          </label>
          <div className="ea-search-wrap">
            <span className="ea-search-icon" aria-hidden>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="11" cy="11" r="7" />
                <path d="M21 21l-4.3-4.3" />
              </svg>
            </span>
            <input
              id="ea-assignments-search"
              className="uv-search ea-search-input"
              type="search"
              placeholder="Title, contract, or remarks"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              autoComplete="off"
            />
          </div>
        </div>
      </div>

      <section className="uv-table-card ea-table-panel">
        {loading ? (
          <div className="ea-loading" aria-busy="true" aria-live="polite">
            <div className="ea-loading-spinner" />
            <span>Loading assignments…</span>
          </div>
        ) : (
          <>
            <div className="uv-table-wrapper">
              <table className="uv-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Video Title</th>
                    <th>Location</th>
                    <th>Work Area</th>
                    <th>Contract Details</th>
                    <th>{roleView === 'verifier' ? 'Executor' : 'Verifier'}</th>
                    <th>Capture Date</th>
                    <th>Capture Time</th>
                    <th>Remarks</th>
                    {roleView === 'executor' ? (
                      <th title="Note from verifier when this assessment was returned to you">Verifier return note</th>
                    ) : null}
                    <th>Status</th>
                    <th className="ea-review-col">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr>
                      <td colSpan={roleView === 'executor' ? 12 : 11} className="uv-empty">
                        {videos.length === 0 ? emptyPrimary : 'No assessments match your filters.'}
                      </td>
                    </tr>
                  )}
                  {filtered.map((v, idx) => {
                    const cat = categorizeRow(v);
                    const executorOpenable =
                      cat === 'not_started' ||
                      cat === 'in_process' ||
                      cat === 'returned' ||
                      cat === 'other';
                    const executorClickable = roleView === 'executor' && executorOpenable;
                    const verifierClickable = roleView === 'verifier';
                    const isClickable = executorClickable || verifierClickable;
                    const rowClick = () => {
                      if (executorClickable) setSelectedAssessment(v);
                      else if (verifierClickable) setVerifierReviewAssessment(v);
                    };
                    const executorAwaitingVerifier =
                      roleView === 'executor' && cat === 'verification_required';
                    return (
                      <tr
                        key={v.assessment_id}
                        onClick={isClickable ? rowClick : undefined}
                        style={isClickable ? { cursor: 'pointer' } : undefined}
                        title={
                          executorAwaitingVerifier
                            ? 'Awaiting verifier review — you can open this again when it is returned to you'
                            : executorClickable
                              ? 'Click to open assessment'
                              : verifierClickable
                                ? 'Click to review risk document'
                                : undefined
                        }
                      >
                        <td>{idx + 1}</td>
                        <td className="uv-cell-title">{v.video_title || '--'}</td>
                        <td>{v.location_name || '--'}</td>
                        <td>{v.department_name || '--'}</td>
                        <td>{(v.contract_details ?? v.contact_details) || '--'}</td>
                        <td>{roleView === 'verifier' ? (v.executor_name ?? v.executor_id ?? '--') : (v.verifier_name ?? v.verifier_id ?? '--')}</td>
                        <td>{formatDate(v.video_capture_date)}</td>
                        <td>{v.video_capture_time || '--'}</td>
                        <td className="uv-cell-remarks">{v.remarks || '--'}</td>
                        {roleView === 'executor' ? (
                          <td className="uv-cell-remarks ea-verifier-return-note">
                            {cat === 'returned' && getVerifierReturnRemarks(v)
                              ? getVerifierReturnRemarks(v)
                              : '—'}
                          </td>
                        ) : null}
                        <td>
                          <span className={`status-pill ${pillClassForRow(v)}`}>
                            {statusDisplayForRow(v)}
                          </span>
                        </td>
                        <td className="ea-review-action-cell">
                          {roleView === 'verifier' ? (
                            <button
                              type="button"
                              className="ea-review-row-btn"
                              title="Review risk document"
                              onClick={(e) => {
                                e.stopPropagation();
                                setVerifierReviewAssessment(v);
                              }}
                            >
                              Review
                            </button>
                          ) : (
                            <button
                              type="button"
                              className="ea-action-primary-btn"
                              disabled={!executorOpenable}
                              title={
                                executorAwaitingVerifier
                                  ? 'Awaiting verifier review — opens when returned to you'
                                  : executorOpenable
                                    ? 'Open field video and assessment tasks'
                                    : 'No further work on this assessment'
                              }
                              onClick={(e) => {
                                e.stopPropagation();
                                if (executorOpenable) setSelectedAssessment(v);
                              }}
                            >
                              <svg
                                width="14"
                                height="14"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2.5"
                                className="ea-action-primary-btn__icon"
                                aria-hidden
                              >
                                <polygon points="5 3 19 12 5 21 5 3" />
                              </svg>
                              <span>Execute</span>
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div className="uv-table-footer">
              <span className="uv-table-meta">
                Showing {filtered.length} of {videos.length} assignment{videos.length !== 1 ? 's' : ''}
              </span>
            </div>
          </>
        )}
      </section>
    </main>
  );
}

export default ExecutorAssignedPage;
