import React from 'react';
import { DOCUMENT_VERSION, TRAINING_DOCUMENT } from '../data/constants';
import TrainingDocumentViewer from '../components/TrainingDocumentViewer';

export default function Step1Document({ state, updateState, completeStep, renderPart = 'all' }) {
  const { step1 } = state;
  const readProgress = step1.readProgress || 0;
  const scrolledToBottom = step1.scrolledToBottom;
  const checked = step1.checked;

  const handleStart = () => {
    if (!step1.startTime) {
      updateState((prev) => ({
        ...prev,
        step1: { ...prev.step1, startTime: new Date().toISOString() },
      }));
    }
  };

  const handleReachBottom = () => {
    updateState((prev) => ({
      ...prev,
      step1: {
        ...prev.step1,
        scrolledToBottom: true,
        readProgress: 100,
        endTime: prev.step1.endTime || new Date().toISOString(),
      },
    }));
  };

  const handleNext = () => {
    const now = new Date().toISOString();
    updateState((prev) => ({
      ...prev,
      step1: {
        ...prev.step1,
        confirmed: true,
        checked: true,
        confirmTime: now,
        documentVersion: DOCUMENT_VERSION,
        readProgress: 100,
        scrolledToBottom: true,
      },
    }));
    completeStep(1);
  };

  const canProceed = scrolledToBottom && checked;

  const content = (
    <div className="dt-card">
      <h2 className="dt-card-title">安全培训须知</h2>
      <TrainingDocumentViewer
        content={TRAINING_DOCUMENT}
        onProgress={(p) => {
          updateState((prev) => ({ ...prev, step1: { ...prev.step1, readProgress: p } }));
        }}
        onReachBottom={handleReachBottom}
        onStart={handleStart}
      />
      <div className="dt-read-progress">
        <div className="dt-read-progress-bar">
          <div className="dt-read-progress-fill" style={{ width: `${readProgress}%` }} />
        </div>
        <span>已阅读 {readProgress}%</span>
      </div>
      <label className="dt-checkbox-row">
        <input
          type="checkbox"
          checked={checked}
          disabled={!scrolledToBottom}
          onChange={(e) =>
            updateState((prev) => ({
              ...prev,
              step1: { ...prev.step1, checked: e.target.checked },
            }))
          }
        />
        <span>本人已完整阅读并知晓以上内容</span>
      </label>
    </div>
  );

  const footer = (
    <>
      <div className="dt-footer-hint">
        {!scrolledToBottom ? '请完整阅读培训文档后继续。' : !checked ? '请勾选确认后继续。' : ''}
      </div>
      <button type="button" className="dt-btn-primary" disabled={!canProceed} onClick={handleNext}>
        我已知晓，进入下一步
      </button>
    </>
  );

  if (renderPart === 'content') return content;
  if (renderPart === 'footer') return footer;
  return (
    <>
      {content}
      {footer}
    </>
  );
}
