/**
 * Login Form Component
 * Reusable login form with validation and error handling
 */

"use client";

import { useCallback } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Button, Input, ErrorMessage } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { useLogin } from "../../hooks/use-auth";
import { loginRequestSchema } from "@customer-portal/domain/auth";
import { useZodForm } from "@/shared/hooks";
import { z } from "zod";
import { getSafeRedirect } from "@/features/auth/utils/route-protection";

interface LoginFormProps {
  onSuccess?: (() => void) | undefined;
  onError?: ((error: string) => void) | undefined;
  showSignupLink?: boolean | undefined;
  showForgotPasswordLink?: boolean | undefined;
  className?: string | undefined;
  redirectTo?: string | undefined;
  initialEmail?: string | undefined;
}

/**
 * Frontend form schema - extends domain loginRequestSchema with UI-specific fields
 *
 * Single source of truth: Domain layer (loginRequestSchema) defines validation rules
 * Frontend only adds: rememberMe field for UI state
 */
const loginFormSchema = loginRequestSchema.extend({
  rememberMe: z.boolean().optional(),
});

type LoginFormValues = z.infer<typeof loginFormSchema>;

export function LoginForm({
  onSuccess,
  onError,
  showSignupLink = true,
  showForgotPasswordLink = true,
  className = "",
  redirectTo,
  initialEmail,
}: LoginFormProps) {
  const searchParams = useSearchParams();
  const { login, loading, error, clearError } = useLogin(redirectTo ? { redirectTo } : undefined);
  const redirectCandidate =
    redirectTo || searchParams?.get("next") || searchParams?.get("redirect");
  const redirect = getSafeRedirect(redirectCandidate, "");
  const redirectQuery = redirect ? `?redirect=${encodeURIComponent(redirect)}` : "";

  const handleLogin = useCallback(
    async ({ rememberMe: _rememberMe, ...formData }: LoginFormValues) => {
      void _rememberMe;
      clearError();
      try {
        // formData already matches LoginRequest schema (email, password)
        await login(formData);
        onSuccess?.();
      } catch (err) {
        const message = err instanceof Error ? err.message : "Login failed";
        onError?.(message);
        throw err;
      }
    },
    [login, onSuccess, onError, clearError]
  );

  const { values, errors, touched, isSubmitting, setValue, setTouchedField, handleSubmit } =
    useZodForm<LoginFormValues>({
      schema: loginFormSchema,
      initialValues: {
        email: initialEmail ?? "",
        password: "",
        rememberMe: false,
      },
      onSubmit: handleLogin,
    });

  return (
    <div className={`w-full ${className}`}>
      <form onSubmit={event => void handleSubmit(event)} className="space-y-6">
        <FormField
          label="Email Address"
          error={touched["email"] ? errors["email"] : undefined}
          required
        >
          <Input
            type="email"
            value={values.email}
            onChange={e => setValue("email", e.target.value)}
            onBlur={() => setTouchedField("email")}
            placeholder="Enter your email"
            disabled={isSubmitting || loading}
            className="w-full"
          />
        </FormField>

        <FormField
          label="Password"
          error={touched["password"] ? errors["password"] : undefined}
          required
        >
          <Input
            type="password"
            value={values.password}
            onChange={e => setValue("password", e.target.value)}
            onBlur={() => setTouchedField("password")}
            placeholder="Enter your password"
            disabled={isSubmitting || loading}
            className="w-full"
          />
        </FormField>

        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <input
              id="remember-me"
              name="remember-me"
              type="checkbox"
              checked={values.rememberMe}
              onChange={e => setValue("rememberMe", e.target.checked)}
              disabled={isSubmitting || loading}
              className="h-4 w-4 text-primary focus:ring-primary border-border rounded transition-colors accent-primary"
            />
            <label htmlFor="remember-me" className="ml-2 block text-sm text-muted-foreground">
              Remember me
            </label>
          </div>

          {showForgotPasswordLink && (
            <div className="text-sm">
              <Link
                href="/auth/forgot-password"
                className="font-medium text-primary hover:text-primary-hover transition-colors duration-200"
              >
                Forgot your password?
              </Link>
            </div>
          )}
        </div>

        {error && <ErrorMessage className="text-center">{error}</ErrorMessage>}

        <Button
          type="submit"
          disabled={isSubmitting || loading}
          loading={isSubmitting || loading}
          loadingText="Signing in..."
          className="w-full"
        >
          Sign in
        </Button>

        {showSignupLink && (
          <div className="text-center">
            <p className="text-sm text-muted-foreground">
              Don&apos;t have an account?{" "}
              <Link
                href={`/auth/signup${redirectQuery}`}
                className="font-medium text-primary hover:text-primary-hover transition-colors duration-200"
              >
                Sign up
              </Link>
            </p>
            <p className="text-sm text-muted-foreground mt-1">
              Existing customer?{" "}
              <Link
                href={`/auth/migrate${redirectQuery}`}
                className="font-medium text-primary hover:text-primary-hover transition-colors duration-200"
              >
                Migrate your account
              </Link>
            </p>
          </div>
        )}
      </form>
    </div>
  );
}
