"use client";

import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth/client";
import { mergeGuestCart } from "@/lib/actions/cart";

export default function RegisterForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError("");

      // Client-side validation
      if (!name.trim()) {
        setError("Full name is required");
        return;
      }
      if (!email.trim()) {
        setError("Email is required");
        return;
      }
      if (password.length < 8) {
        setError("Password must be at least 8 characters");
        return;
      }
      if (password !== confirmPassword) {
        setError("Passwords do not match");
        return;
      }

      setLoading(true);
      try {
        const { error: authError } = await authClient.signUp.email({
          name: name.trim(),
          email: email.trim(),
          password,
        });

        if (authError) {
          setError(authError.message ?? "Registration failed");
          return;
        }

        // Fold any items added while logged-out into the new account's cart.
        await mergeGuestCart();

        router.push("/");
        router.refresh();
      } catch {
        setError("An unexpected error occurred");
      } finally {
        setLoading(false);
      }
    },
    [name, email, password, confirmPassword, router],
  );

  return (
    <form onSubmit={handleSubmit} className="space-y-4 px-2 md:px-6">
      {error && (
        <div role="alert" className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
          {error}
        </div>
      )}

      <div className="space-y-1.5">
        <Label htmlFor="name" className="text-sm">
          Full Name
        </Label>
        <Input
          id="name"
          type="text"
          placeholder="Enter your full name"
          className="h-10"
          value={name}
          onChange={(e) => setName(e.target.value)}
          disabled={loading}
          autoComplete="name"
        />
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="email" className="text-sm">
          Email
        </Label>
        <Input
          id="email"
          type="email"
          placeholder="Enter your email"
          className="h-10"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          disabled={loading}
          autoComplete="email"
        />
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="password" className="text-sm">
          Password
        </Label>
        <Input
          id="password"
          type="password"
          placeholder="Create a password"
          className="h-10"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          disabled={loading}
          autoComplete="new-password"
        />
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="confirm-password" className="text-sm">
          Confirm Password
        </Label>
        <Input
          id="confirm-password"
          type="password"
          placeholder="Confirm your password"
          className="h-10"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
          disabled={loading}
          autoComplete="new-password"
        />
      </div>

      <div className="flex items-start gap-2 text-sm">
        <Checkbox id="terms" required />
        <Label
          htmlFor="terms"
          className="text-sm leading-5 text-muted-foreground"
        >
          I agree to the Terms of Service and Privacy Policy
        </Label>
      </div>

      <Button type="submit" className="h-10 w-full rounded-full" disabled={loading}>
        {loading ? "Creating account..." : "Create account"}
      </Button>
    </form>
  );
}
