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 CodeStepProps {
  email: string;
  onBack: () => void;
}

export function CodeStep({ email, onBack }: CodeStepProps) {
  const [code, setCode] = useState("");
  const isSigningIn = useAuthStore((s) => s.isSigningIn);
  const error = useAuthStore((s) => s.error);
  const signIn = useAuthStore((s) => s.signIn);
  const clearError = useAuthStore((s) => s.clearError);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    try {
      await signIn(email, code);
    } 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>Check your email</H3>
        <Muted>
          We sent a code to <strong className="text-foreground">{email}</strong>.
        </Muted>
      </div>

      <div className="flex flex-col gap-1.5">
        <Label htmlFor="code">Code</Label>
        <Input
          id="code"
          type="text"
          inputMode="numeric"
          placeholder="Enter code"
          value={code}
          onChange={(e) => {
            setCode(e.target.value);
            if (error) clearError();
          }}
          required
          autoFocus
        />
      </div>

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

      <div className="flex flex-col gap-2">
        <Button type="submit" disabled={isSigningIn || !code}>
          {isSigningIn ? "Signing in..." : "Sign in"}
        </Button>
        <Button type="button" variant="ghost" onClick={onBack}>
          Back
        </Button>
      </div>
    </form>
  );
}
