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

"use client";

import { useState } from "react";
import { Button } from "@/components/atoms";
import { OtpInput } from "@/components/molecules";
import { useGetStartedStore } from "../../../stores/get-started.store";

export function VerificationStep() {
  const {
    formData,
    verifyCode,
    sendVerificationCode,
    loading,
    error,
    clearError,
    attemptsRemaining,
    goBack,
  } = useGetStartedStore();

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

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

  const handleCodeComplete = async (value: string) => {
    clearError();
    await verifyCode(value);
  };

  const handleVerify = async () => {
    if (code.length === 6) {
      await verifyCode(code);
    }
  };

  const handleResend = async () => {
    setResending(true);
    setCode("");
    clearError();
    await sendVerificationCode(formData.email);
    setResending(false);
  };

  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">{formData.email}</p>
      </div>

      <OtpInput
        value={code}
        onChange={handleCodeChange}
        onComplete={handleCodeComplete}
        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={goBack}
            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>
  );
}
