/**
 * VerificationStep - Enter 6-digit OTP code
 */

"use client";

import { useState } from "react";
import { Button } from "@/components/atoms";
import { OtpInput } from "@/components/molecules";
import { useGetStartedMachine } from "../../../hooks/useGetStartedMachine";

export function VerificationStep() {
  const { state, send } = useGetStartedMachine();

  const loading = state.matches({ verification: "loading" });
  const error = state.context.error;
  const attemptsRemaining = state.context.attemptsRemaining;
  const email = state.context.formData.email;

  const [code, setCode] = useState("");
  const [resending, setResending] = useState(false);

  const handleCodeChange = (value: string) => {
    setCode(value);
  };

  const handleVerify = () => {
    if (code.length === 6) {
      send({ type: "VERIFY_CODE", code });
    }
  };

  const handleResend = () => {
    setResending(true);
    setCode("");
    send({ type: "SEND_CODE", email });
    // Reset resending state after a short delay (the machine handles the actual async)
    setTimeout(() => setResending(false), 2000);
  };

  const handleGoBack = () => {
    send({ type: "RESET" });
    send({ type: "START" });
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <p className="text-sm text-muted-foreground">Enter the 6-digit code sent to</p>
        <p className="font-medium text-foreground">{email}</p>
      </div>

      <OtpInput
        value={code}
        onChange={handleCodeChange}
        disabled={loading}
        error={error ?? undefined}
        autoFocus
      />

      {typeof attemptsRemaining === "number" && attemptsRemaining < 3 && (
        <p className="text-sm text-warning text-center">
          {attemptsRemaining} {attemptsRemaining === 1 ? "attempt" : "attempts"} remaining
        </p>
      )}

      <div className="space-y-3">
        <Button
          type="button"
          onClick={handleVerify}
          disabled={loading || code.length !== 6}
          loading={loading}
          className="w-full h-11"
        >
          {loading ? "Verifying..." : "Verify Code"}
        </Button>

        <div className="flex items-center justify-between">
          <Button
            type="button"
            variant="ghost"
            onClick={handleGoBack}
            disabled={loading}
            className="text-sm"
          >
            Change email
          </Button>

          <Button
            type="button"
            variant="ghost"
            onClick={handleResend}
            disabled={loading || resending}
            className="text-sm"
          >
            {resending ? "Sending..." : "Resend code"}
          </Button>
        </div>
      </div>

      <p className="text-xs text-muted-foreground text-center">
        The code expires in 10 minutes. Check your spam folder if you don&apos;t see it.
      </p>
    </div>
  );
}
