"use client";

import { useActionState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

interface UserAuthFormProps {
  mode: "login" | "register";
  action: (formData: FormData) => Promise<{ error?: string } | void>;
  next?: string;
}

export function UserAuthForm({ mode, action, next = "/account" }: UserAuthFormProps) {
  const [state, formAction, pending] = useActionState(
    async (_prev: { error?: string } | null, formData: FormData) => {
      return (await action(formData)) ?? null;
    },
    null
  );

  return (
    <form action={formAction} className="space-y-4">
      <input type="hidden" name="next" value={next} />

      {mode === "register" && (
        <div>
          <Label htmlFor="name">暱稱（選填）</Label>
          <Input id="name" name="name" className="mt-1" />
        </div>
      )}

      <div>
        <Label htmlFor="email">電子郵件 *</Label>
        <Input
          id="email"
          name="email"
          type="email"
          required
          autoComplete="email"
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="password">密碼 *</Label>
        <Input
          id="password"
          name="password"
          type="password"
          required
          minLength={6}
          autoComplete={mode === "login" ? "current-password" : "new-password"}
          className="mt-1"
        />
      </div>

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

      <Button
        type="submit"
        disabled={pending}
        className="w-full bg-primary text-primary-foreground"
      >
        {pending
          ? "處理中..."
          : mode === "login"
            ? "登入"
            : "註冊帳號"}
      </Button>
    </form>
  );
}