import React, { useCallback, useEffect } from 'react';
import { TrainingProvider, useTraining } from './context/TrainingContext';
import { TOTAL_STEPS } from './data/constants';
import { DriverTrainingLayout } from './components/DriverTrainingLayout';
import PrototypeDebugPanel from './components/PrototypeDebugPanel';
import Toast, { useToast } from './components/Toast';
import Step1Document from './steps/Step1Document';
import Step2Phone from './steps/Step2Phone';
import Step3Certificates from './steps/Step3Certificates';
import Step4Video from './steps/Step4Video';
import Step5Portrait from './steps/Step5Portrait';
import Step6Signature from './steps/Step6Signature';
import Step7Signature from './steps/Step7Signature';
import Step7PickupCode from './steps/Step7PickupCode';
import './styles/driver-training.css';

const STEPS = [
  Step1Document,
  Step2Phone,
  Step3Certificates,
  Step4Video,
  Step5Portrait,
  Step6Signature,
  Step7Signature,
  Step7PickupCode,
];

const SIGNATURE_STEP = 7;

function StepFooterBar({ currentStep, goToStep, children }) {
  if (currentStep >= TOTAL_STEPS) return null;

  if (currentStep <= 1) {
    return <div className="dt-footer-stack">{children}</div>;
  }

  return (
    <div className="dt-footer-stack">
      <div className="dt-footer-row">
        <button type="button" className="dt-btn-prev" onClick={() => goToStep(currentStep - 1)}>
          上一步
        </button>
        <div className="dt-footer-main">{children}</div>
      </div>
    </div>
  );
}

function getStepDetailHint(state) {
  const { currentStep, step1, step4 } = state;
  if (currentStep === 1 && step1.readProgress > 0 && step1.readProgress < 100) {
    return `阅读 ${step1.readProgress}%`;
  }
  if (currentStep === 4 && !step4.completed && step4.watchedSeconds > 0) {
    return `已观看 ${step4.watchedSeconds}s`;
  }
  if (currentStep === SIGNATURE_STEP) {
    return '请横屏签字';
  }
  return '';
}

function DriverTrainingContent({ onRegisterBack }) {
  const { state, updateState, goToStep, completeStep, stepNames, updateCertificate, submitTraining } = useTraining();
  const { message, show, clear } = useToast();
  const { currentStep, maxCompletedStep } = state;
  const stepDetailHint = getStepDetailHint(state);
  const isSignatureStep = currentStep === SIGNATURE_STEP;

  useEffect(() => {
    if (!onRegisterBack) return undefined;
    onRegisterBack(() => {
      if (currentStep > 1) {
        goToStep(currentStep - 1);
        return true;
      }
      return false;
    });
    return () => onRegisterBack(null);
  }, [onRegisterBack, currentStep, goToStep]);

  const StepComponent = STEPS[currentStep - 1] || STEPS[0];
  const stepProps = {
    state,
    updateState,
    completeStep,
    goToStep,
    showToast: show,
    updateCertificate,
    submitTraining,
  };

  return (
    <>
      <DriverTrainingLayout
        currentStep={currentStep}
        totalSteps={TOTAL_STEPS}
        stepNames={stepNames}
        maxCompletedStep={maxCompletedStep}
        stepDetailHint={stepDetailHint}
        embedded
        immersive={isSignatureStep}
        footer={
          currentStep < TOTAL_STEPS && currentStep !== SIGNATURE_STEP ? (
            <StepFooterBar currentStep={currentStep} goToStep={goToStep}>
              <StepComponent {...stepProps} renderPart="footer" />
            </StepFooterBar>
          ) : null
        }
      >
        <StepComponent {...stepProps} renderPart="content" />
      </DriverTrainingLayout>
      <PrototypeDebugPanel />
      <Toast message={message} onClose={clear} />
    </>
  );
}

export default function DriverTrainingModule({ onRegisterBack }) {
  const registerBack = useCallback(
    (handler) => {
      if (typeof onRegisterBack === 'function') {
        onRegisterBack(handler);
      }
    },
    [onRegisterBack],
  );

  return (
    <TrainingProvider>
      <div className="dt-module-root" data-annotation-id="page-driver-training">
        <DriverTrainingContent onRegisterBack={registerBack} />
      </div>
    </TrainingProvider>
  );
}
