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

"use client";

import { useCallback } from "react";
import Link from "next/link";
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 "@customer-portal/validation";
import { z } from "zod";

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

/**
 * 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 = "",
}: LoginFormProps) {
  const { login, loading, error, clearError } = useLogin();

  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: "",
        password: "",
        rememberMe: false,
      },
      onSubmit: handleLogin,
    });

  return (
    <div className={`w-full max-w-md mx-auto ${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-blue-600 focus:ring-blue-500 border-gray-300 rounded transition-colors"
            />
            <label htmlFor="remember-me" className="ml-2 block text-sm text-gray-700">
              Remember me
            </label>
          </div>

          {showForgotPasswordLink && (
            <div className="text-sm">
              <Link
                href="/auth/forgot-password"
                className="font-medium text-blue-600 hover:text-blue-500 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-gray-600">
              Don&apos;t have an account?{" "}
              <Link
                href="/auth/signup"
                className="font-medium text-blue-600 hover:text-blue-500 transition-colors duration-200"
              >
                Sign up
              </Link>
            </p>
          </div>
        )}
      </form>
    </div>
  );
}
