import { AppLayout } from '@/components/layout';
import { sharePoint } from '@/lib/sharepoint';
import { TrainingModule, PolicyDocument } from '@/lib/types';
import { CheckCircle2, Lock, Play, FileText, ExternalLink, ClipboardCheck, AlertCircle, CreditCard } from 'lucide-react';

function ModuleStepIndicator({ order, total, status }: { order: number; total: number; status: string }) {
  const isComplete = status === 'Completed';
  const isActive = status === 'In Progress';
  return (
    <div className="step-indicator">
      <div className={`step-dot ${isComplete ? 'step-complete' : isActive ? 'step-active' : 'step-locked'}`}>
        {isComplete ? <CheckCircle2 size={18} /> : order}
      </div>
      {order < total && <div className={`step-line ${isComplete ? 'step-line-complete' : ''}`} />}
    </div>
  );
}

function TrainingModuleCard({ mod, totalSteps }: { mod: TrainingModule; totalSteps: number }) {
  const isLocked = mod.status === 'Locked';
  const isComplete = mod.status === 'Completed';
  const isActive = mod.status === 'In Progress';
  const quizPassed = mod.quizScore !== undefined && mod.quizScore >= mod.passingScore;

  return (
    <div className={`module-card ${isLocked ? 'module-locked' : ''} ${isActive ? 'module-active' : ''} ${isComplete ? 'module-complete' : ''}`}>
      <ModuleStepIndicator order={mod.order} total={totalSteps} status={mod.status} />

      <div className="module-body">
        <div className="module-header">
          <div className="module-title-row">
            <h3 className="module-title">
              {isLocked && <Lock size={16} className="lock-inline" />}
              Module {mod.order}: {mod.title}
            </h3>
            {isComplete && <span className="status completed"><CheckCircle2 size={14} /> Passed</span>}
            {isActive && <span className="status progress">In Progress</span>}
            {isLocked && <span className="status locked"><Lock size={14} /> Locked</span>}
          </div>
          <p className="module-desc">{mod.description}</p>
        </div>

        {/* Video area — shown for active or completed modules */}
        {!isLocked && (
          <div className="module-content">
            <div className="video-box">
              <div>
                <Play size={48} style={{ opacity: 0.6, marginBottom: 12 }} />
                <p style={{ color: 'rgba(255,255,255,.8)', margin: '0 0 4px', fontSize: 14 }}>
                  Training video will be embedded from SharePoint Stream
                </p>
                <p style={{ color: 'rgba(255,255,255,.5)', margin: 0, fontSize: 12 }}>
                  {mod.videoSharePointPath}
                </p>
              </div>
            </div>

            <div className="module-meta-row">
              <div className="module-progress-section">
                <div className="module-progress-label">
                  <span>Video Progress</span>
                  <strong>{mod.percentWatched}%</strong>
                </div>
                <div className="progress-wrap"><div className="progress-bar" style={{ width: `${mod.percentWatched}%` }} /></div>
              </div>

              {mod.quizScore !== undefined && (
                <div className="quiz-result">
                  <span className="quiz-result-label">Quiz Score</span>
                  <span className={`quiz-score ${quizPassed ? 'quiz-pass' : 'quiz-fail'}`}>
                    {mod.quizScore}%
                    {quizPassed ? ' ✓' : ` (need ${mod.passingScore}%)`}
                  </span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Locked message */}
        {isLocked && (
          <div className="module-locked-msg">
            <AlertCircle size={16} />
            Complete the previous module and pass the quiz with ≥ {mod.passingScore}% to unlock this module.
          </div>
        )}

        {/* Action buttons */}
        {!isLocked && (
          <div className="module-actions">
            <a
              href={mod.quizUrl}
              target="_blank"
              rel="noopener noreferrer"
              className={`btn ${isComplete && quizPassed ? 'btn-soft' : 'btn-primary'}`}
            >
              <ClipboardCheck size={16} />
              {isComplete && quizPassed ? 'Retake Quiz' : 'Take Quiz'}
              <ExternalLink size={14} />
            </a>
            <span className="module-quiz-note">
              Minimum passing score: {mod.passingScore}% · Opens in Microsoft Forms
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

function PolicyDocCard({ doc, totalSteps }: { doc: PolicyDocument; totalSteps: number }) {
  const isLocked = doc.status === 'Locked';
  const isComplete = doc.acknowledged;

  return (
    <div className={`module-card module-policy ${isLocked ? 'module-locked' : ''} ${isComplete ? 'module-complete' : ''}`}>
      <ModuleStepIndicator order={doc.order} total={totalSteps} status={isComplete ? 'Completed' : isLocked ? 'Locked' : 'In Progress'} />

      <div className="module-body">
        <div className="module-header">
          <div className="module-title-row">
            <h3 className="module-title">
              {isLocked && <Lock size={16} className="lock-inline" />}
              <FileText size={16} className="lock-inline" />
              {doc.title}
            </h3>
            <span className="module-version">{doc.version}</span>
          </div>
          <p className="module-desc">{doc.description}</p>
        </div>

        {isLocked ? (
          <div className="module-locked-msg">
            <AlertCircle size={16} />
            Complete the previous step to unlock this document.
          </div>
        ) : (
          <div className="policy-action-area">
            <div className="policy-embed-placeholder">
              <FileText size={32} style={{ color: 'var(--ge-blue)', opacity: 0.5 }} />
              <p>Document will be embedded from SharePoint</p>
              <p className="task-meta">{doc.pdfSharePointPath}</p>
            </div>
            <label className="policy-acknowledge">
              <input type="checkbox" defaultChecked={doc.acknowledged} />
              <span>I acknowledge that I have read and understand this document and agree to follow the requirements described in it.</span>
            </label>
            <button className="btn btn-blue" disabled={doc.acknowledged}>
              {doc.acknowledged ? 'Acknowledged' : 'Submit Acknowledgement'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function DirectDepositPlaceholder({ order, totalSteps }: { order: number; totalSteps: number }) {
  return (
    <div className="module-card module-locked">
      <ModuleStepIndicator order={order} total={totalSteps} status="Locked" />
      <div className="module-body">
        <div className="module-header">
          <div className="module-title-row">
            <h3 className="module-title">
              <Lock size={16} className="lock-inline" />
              <CreditCard size={16} className="lock-inline" />
              Direct Deposit Setup
            </h3>
            <span className="status locked"><Lock size={14} /> Locked</span>
          </div>
          <p className="module-desc">Set up direct deposit for contractor payments. This step will be available once all training and policy acknowledgements are complete.</p>
        </div>
        <div className="module-locked-msg">
          <AlertCircle size={16} />
          Complete all training modules and company policy acknowledgements to unlock.
        </div>
      </div>
    </div>
  );
}

export default async function TrainingPage() {
  const modules = await sharePoint.getTrainingModules();
  const policies = await sharePoint.getPolicyDocuments();
  const totalSteps = modules.length + policies.length + 1; /* +1 for direct deposit */

  const completedModules = modules.filter(m => m.status === 'Completed').length;
  const completedPolicies = policies.filter(p => p.acknowledged).length;
  const totalComplete = completedModules + completedPolicies;
  const totalItems = modules.length + policies.length + 1;
  const overallPercent = Math.round((totalComplete / totalItems) * 100);

  return (
    <AppLayout>
      <div className="page-title">
        <div>
          <h2>Training & Onboarding</h2>
          <p>Complete each training module and pass the quiz with ≥ 70% to proceed. After all modules, review and acknowledge each company policy document.</p>
        </div>
        <div className="training-progress-summary">
          <span className="training-progress-count">{totalComplete} / {totalItems}</span>
          <span className="task-meta">steps complete</span>
        </div>
      </div>

      {/* Overall progress */}
      <div className="card" style={{ marginBottom: 22 }}>
        <div className="module-progress-label">
          <span><strong>Overall Progress</strong></span>
          <strong>{overallPercent}%</strong>
        </div>
        <div className="progress-wrap"><div className="progress-bar" style={{ width: `${overallPercent}%` }} /></div>
      </div>

      {/* ── Training Modules Section ── */}
      <div className="training-section-label">
        <Play size={18} />
        <span>Training Modules</span>
        <span className="task-meta">{completedModules} of {modules.length} complete</span>
      </div>

      <div className="module-list">
        {modules.map(mod => (
          <TrainingModuleCard key={mod.id} mod={mod} totalSteps={totalSteps} />
        ))}
      </div>

      {/* ── Company Policies Section ── */}
      <div className="training-section-label" style={{ marginTop: 32 }}>
        <FileText size={18} />
        <span>Company Policies</span>
        <span className="task-meta">{completedPolicies} of {policies.length} acknowledged</span>
      </div>

      <div className="module-list">
        {policies.map(doc => (
          <PolicyDocCard key={doc.id} doc={doc} totalSteps={totalSteps} />
        ))}
      </div>

      {/* ── Direct Deposit ── */}
      <div className="training-section-label" style={{ marginTop: 32 }}>
        <CreditCard size={18} />
        <span>Final Steps</span>
      </div>

      <div className="module-list">
        <DirectDepositPlaceholder order={totalSteps} totalSteps={totalSteps} />
      </div>

      <div className="notice" style={{ marginTop: 22 }}>
        Production note: Quiz scores are retrieved from Microsoft Forms via Power Automate and written to the SharePoint Training Progress list. Policy acknowledgements write a timestamped record with CandidateID, document version, and IP address.
      </div>
    </AppLayout>
  );
}
