import React, { useEffect, useRef } from 'react';

import StatusTag from './StatusTag';

import { PICKUP_STATUS } from '../data/constants';

function drawQRCode(canvas, text) {
  const ctx = canvas.getContext('2d');
  const size = 160;
  canvas.width = size;
  canvas.height = size;
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, size, size);

  const hash = text.split('').reduce((a, c) => a + c.charCodeAt(0), 0);
  const cell = 8;
  const cells = size / cell;

  for (let y = 0; y < cells; y++) {
    for (let x = 0; x < cells; x++) {
      const inCorner =
        (x < 9 && y < 9) || (x > cells - 10 && y < 9) || (x < 9 && y > cells - 10);
      const val = (hash * (x + 1) * (y + 1) + x * y) % 7;
      if (inCorner) {
        if (
          (x === 1 || x === 7 || x === cells - 8 || x === cells - 2) &&
          (y === 1 || y === 7)
        ) {
          ctx.fillStyle = '#1D2129';
          ctx.fillRect(x * cell, y * cell, cell, cell);
        } else if (x >= 2 && x <= 6 && y >= 2 && y <= 6) {
          ctx.fillStyle = '#1D2129';
          ctx.fillRect(x * cell, y * cell, cell, cell);
        }
      } else if (val < 3) {
        ctx.fillStyle = '#1D2129';
        ctx.fillRect(x * cell, y * cell, cell, cell);
      }
    }
  }
}

const STATUS_HINTS = {
  [PICKUP_STATUS.PENDING]: '请向运维人员出示二维码',
  [PICKUP_STATUS.LOCKED]: '运维已核验，正在办理交车',
  [PICKUP_STATUS.PROCESSING]: '等待双方完成电子签署',
  [PICKUP_STATUS.COMPLETED]: '交车已完成，提车码已失效',
  [PICKUP_STATUS.REVOKED]: '交车任务已取消，提车码不可使用',
  [PICKUP_STATUS.EXPIRED]: '提车码已失效',
};

export default function PickupCodeCard({ step7 }) {
  const canvasRef = useRef(null);
  const isDisabled =
    step7.status === PICKUP_STATUS.COMPLETED ||
    step7.status === PICKUP_STATUS.REVOKED ||
    step7.status === PICKUP_STATUS.EXPIRED;

  useEffect(() => {
    if (canvasRef.current && step7.pickupCode) {
      drawQRCode(canvasRef.current, step7.pickupCode);
    }
  }, [step7.pickupCode]);

  const hint = STATUS_HINTS[step7.status];

  return (
    <div className="dt-pickup-page">
      <div className="dt-pickup-success dt-animate-fade-in">
        <div className="dt-pickup-icon">✓</div>
        <h2 className="dt-pickup-title">安全培训已完成</h2>
        <p className="dt-pickup-subtitle">请向运维人员出示下方提车码</p>
      </div>

      <div className="dt-card dt-qr-card dt-animate-scale-in">
        <div className="dt-qr-card-header">
          <StatusTag status={step7.status} />
          {hint ? <p className="dt-qr-status-hint">{hint}</p> : null}
        </div>
        <div className="dt-qr-frame">
          <canvas ref={canvasRef} className={`dt-qr-code ${isDisabled ? 'disabled' : ''}`} />
          {isDisabled && <div className="dt-qr-overlay">已失效</div>}
        </div>

        <div className="dt-warning-tip">提车码仅限本次交车使用，请勿转发给他人。</div>
      </div>
    </div>
  );
}
