'use client';

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

import OtpDigitInput from '@/components/employee-signup/OtpDigitInput';

const RESEND_SECONDS = 30;

interface OtpStepProps {
  email: string;
  submitting: boolean;
  errorMessage?: string | null;
  onVerify: (code: string) => void;
  onChangeEmail: () => void;
  onResend: () => void;
}

export default function OtpStep({ email, submitting, errorMessage, onVerify, onChangeEmail, onResend }: OtpStepProps) {
  const [code, setCode] = useState('');
  const [secondsLeft, setSecondsLeft] = useState(RESEND_SECONDS);
  const autoSubmitted = useRef('');

  useEffect(() => {
    if (secondsLeft <= 0) return;
    const id = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
    return () => clearTimeout(id);
  }, [secondsLeft]);

  // Auto-submit once all 6 digits are entered (paste or fast typing),
  // mirroring the design prototype's own employee-login.js behavior.
  useEffect(() => {
    if (code.length === 6 && !submitting && autoSubmitted.current !== code) {
      autoSubmitted.current = code;
      onVerify(code);
    }
  }, [code, submitting, onVerify]);

  const handleResend = () => {
    if (secondsLeft > 0) return;
    setSecondsLeft(RESEND_SECONDS);
    setCode('');
    autoSubmitted.current = '';
    onResend();
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        if (code.length === 6) onVerify(code);
      }}
      noValidate
    >
      <button
        type="button"
        onClick={onChangeEmail}
        className="mb-3 inline-flex items-center gap-1.5 border-0 bg-transparent p-0 text-[13px] font-semibold text-[var(--fra-muted)] hover:text-[var(--fra-coral)]"
      >
        <svg className="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 12H5M11 18l-6-6 6-6" />
        </svg>
        <span>Change email</span>
      </button>

      <h2 className="mb-1.5 text-[22px] font-extrabold text-[var(--fra-heading)]">Enter the OTP</h2>
      <p className="mb-5 text-sm text-[var(--fra-muted)]">
        We sent a 6-digit code to <strong className="text-[var(--fra-heading)]">{email}</strong>
      </p>

      <OtpDigitInput
        value={code}
        onChange={(v) => {
          setCode(v);
          if (v.length < 6) autoSubmitted.current = '';
        }}
        disabled={submitting}
        invalid={!!errorMessage}
      />
      {errorMessage && <small className="mt-1.5 block text-xs text-[var(--fra-rejected)]">{errorMessage}</small>}

      <button
        type="submit"
        disabled={submitting || code.length !== 6}
        className="group mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-[var(--fra-radius-sm)] bg-[var(--fra-coral)] text-[15px] font-semibold text-white shadow-[0_4px_14px_rgba(244,93,107,0.35)] transition-colors hover:bg-[var(--fra-coral-dark)] disabled:cursor-not-allowed disabled:opacity-60"
      >
        <span>{submitting ? 'Verifying…' : 'Verify & sign in'}</span>
        {!submitting && (
          <svg className="size-4 transition-transform group-hover:translate-x-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 12h14M13 6l6 6-6 6" />
          </svg>
        )}
      </button>

      <p className="mt-3.5 mb-0 text-center text-[13px] text-[var(--fra-muted)]">
        Didn&apos;t get it?{' '}
        <button
          type="button"
          onClick={handleResend}
          disabled={secondsLeft > 0}
          className="border-0 bg-transparent p-0 font-semibold text-[var(--fra-coral)] disabled:text-[var(--fra-muted)]"
        >
          {secondsLeft > 0 ? `Resend OTP in ${secondsLeft}s` : 'Resend OTP'}
        </button>
      </p>
    </form>
  );
}
