/**
 * EmailStep - First step to enter email address
 */

"use client";

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

export function EmailStep() {
  const { formData, sendVerificationCode, loading, error, clearError } = useGetStartedStore();
  const [email, setEmail] = useState(formData.email);
  const [localError, setLocalError] = useState<string | null>(null);

  const validateEmail = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(value);
  };

  const handleSubmit = async () => {
    clearError();
    setLocalError(null);

    const trimmedEmail = email.trim().toLowerCase();

    if (!trimmedEmail) {
      setLocalError("Email address is required");
      return;
    }

    if (!validateEmail(trimmedEmail)) {
      setLocalError("Please enter a valid email address");
      return;
    }

    await sendVerificationCode(trimmedEmail);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleSubmit();
    }
  };

  const displayError = localError || error;

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <Label htmlFor="email">Email Address</Label>
        <Input
          id="email"
          type="email"
          placeholder="you@example.com"
          value={email}
          onChange={e => {
            setEmail(e.target.value);
            setLocalError(null);
            clearError();
          }}
          onKeyDown={handleKeyDown}
          disabled={loading}
          error={displayError}
          autoComplete="email"
          autoFocus
        />
        {displayError && (
          <p className="text-sm text-danger" role="alert">
            {displayError}
          </p>
        )}
      </div>

      <div className="text-sm text-muted-foreground">
        <p>
          We&apos;ll send a verification code to confirm your email address. This helps us keep your
          account secure.
        </p>
      </div>

      <Button
        type="button"
        onClick={handleSubmit}
        disabled={loading || !email.trim()}
        loading={loading}
        className="w-full h-11"
      >
        {loading ? "Sending Code..." : "Send Verification Code"}
      </Button>
    </div>
  );
}
