"use client";

import * as React from "react";

export type AuthFormActions = {
  login: (email: string, password: string) => Promise<{ error?: string }>;
  signup?: (email: string, password: string) => Promise<{ error?: string }>;
};

export type AuthFormComponents = {
  Button?: React.ComponentType<
    React.ButtonHTMLAttributes<HTMLButtonElement> & {
      children?: React.ReactNode;
    }
  >;
  Input?: React.ComponentType<React.InputHTMLAttributes<HTMLInputElement>>;
  Error?: React.ComponentType<{ children?: React.ReactNode }>;
  Separator?: React.ComponentType<{ children?: React.ReactNode }>;
};

type LoginFormProps = {
  actions: AuthFormActions;
  components?: AuthFormComponents;
  onSuccess?: () => void;
  signUpUrl?: string;
};

export function LoginForm({
  actions,
  components = {},
  onSuccess,
  signUpUrl,
}: LoginFormProps) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState<string | null>(null);
  const [loading, setLoading] = React.useState(false);

  const Button = components.Button ?? "button";
  const Input = components.Input ?? "input";
  const ErrorComponent = components.Error ?? "div";
  const SeparatorComponent = components.Separator ?? "div";

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const result = await actions.login(email, password);
      if (result.error) {
        setError(result.error);
        return;
      }
      onSuccess?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Login failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div>
        <label className="block text-sm font-medium mb-1">Email</label>
        <Input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          autoComplete="email"
          className="w-full rounded border border-input bg-background px-3 py-2 text-sm"
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Password</label>
        <Input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
          autoComplete="current-password"
          className="w-full rounded border border-input bg-background px-3 py-2 text-sm"
        />
      </div>
      {error && (
        <ErrorComponent className="text-sm text-destructive">
          {error}
        </ErrorComponent>
      )}
      <Button
        type="submit"
        disabled={loading}
        className="rounded bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
      >
        {loading ? "Signing in…" : "Sign in"}
      </Button>
      {signUpUrl && (
        <>
          <SeparatorComponent />
          <a
            href={signUpUrl}
            className="text-sm text-muted-foreground hover:underline"
          >
            Create an account
          </a>
        </>
      )}
    </form>
  );
}

type LoginPageProps = {
  actions: AuthFormActions;
  components?: AuthFormComponents;
  onSuccess?: () => void;
  signUpUrl?: string;
  title?: string;
};

export function LoginPage({
  actions,
  components,
  onSuccess,
  signUpUrl,
  title = "Sign in",
}: LoginPageProps) {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center p-4">
      <div className="w-full max-w-sm space-y-6 rounded-lg border border-border bg-card p-6">
        <h1 className="text-xl font-semibold text-center">{title}</h1>
        <LoginForm
          actions={actions}
          components={components}
          onSuccess={onSuccess}
          signUpUrl={signUpUrl}
        />
      </div>
    </div>
  );
}
