import { type FormEvent, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { H3, Muted } from "@/components/ui/typography";
import { useAuthStore } from "@/stores/auth-store";

interface EmailStepProps {
  onCodeSent: (email: string) => void;
}

export function EmailStep({ onCodeSent }: EmailStepProps) {
  const [email, setEmail] = useState("");
  const isRequestingCode = useAuthStore((s) => s.isRequestingCode);
  const error = useAuthStore((s) => s.error);
  const requestCode = useAuthStore((s) => s.requestCode);
  const clearError = useAuthStore((s) => s.clearError);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    try {
      await requestCode(email);
      onCodeSent(email);
    } catch {
      // Error is set in the store
    }
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div className="flex flex-col gap-2">
        <H3>Sign in</H3>
        <Muted>Enter your email to receive a sign-in code.</Muted>
      </div>

      <div className="flex flex-col gap-1.5">
        <Label htmlFor="email">Email</Label>
        <Input
          id="email"
          type="email"
          placeholder="you@example.com"
          value={email}
          onChange={(e) => {
            setEmail(e.target.value);
            if (error) clearError();
          }}
          required
          autoFocus
        />
      </div>

      {error && (
        <p className="text-sm text-destructive">{error}</p>
      )}

      <Button type="submit" disabled={isRequestingCode || !email}>
        {isRequestingCode ? "Sending..." : "Continue"}
      </Button>
    </form>
  );
}
