/**
 * Password Reset Form Component
 * Form for requesting and resetting passwords - migrated to use Zod validation
 */

"use client";

import { useEffect } from "react";
import Link from "next/link";
import { Button, Input, ErrorMessage } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { usePasswordReset } from "../../hooks/use-auth";
import { useZodForm } from "@customer-portal/validation";
import { passwordResetRequestSchema, passwordResetSchema } from "@customer-portal/domain/auth";
import { z } from "zod";

interface PasswordResetFormProps {
  mode: "request" | "reset";
  token?: string;
  onSuccess?: () => void;
  onError?: (error: string) => void;
  showLoginLink?: boolean;
  className?: string;
}

export function PasswordResetForm({
  mode,
  token,
  onSuccess,
  onError,
  showLoginLink = true,
  className = "",
}: PasswordResetFormProps) {
  const { requestPasswordReset, resetPassword, loading, error, clearError } = usePasswordReset();

  // Zod form for password reset request - uses domain schema
  type PasswordResetRequestData = z.infer<typeof passwordResetRequestSchema>;

  const requestForm = useZodForm<PasswordResetRequestData>({
    schema: passwordResetRequestSchema,
    initialValues: { email: "" },
    onSubmit: async data => {
      try {
        await requestPasswordReset(data.email);
        onSuccess?.();
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Request failed";
        onError?.(errorMessage);
        throw err;
      }
    },
  });

  /**
   * Frontend reset form schema - extends domain passwordResetSchema with confirmPassword
   *
   * Single source of truth: Domain layer defines validation rules
   * Frontend only adds: confirmPassword field and password matching logic
   */
  const resetFormSchema = passwordResetSchema
    .extend({
      confirmPassword: z.string().min(1, "Please confirm your new password"),
    })
    .superRefine((data, ctx) => {
      if (data.password !== data.confirmPassword) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["confirmPassword"],
          message: "Passwords do not match",
        });
      }
    });

  type ResetFormValues = z.infer<typeof resetFormSchema>;

  const resetForm = useZodForm<ResetFormValues>({
    schema: resetFormSchema,
    initialValues: { token: token || "", password: "", confirmPassword: "" },
    onSubmit: async ({ confirmPassword: _ignore, ...data }) => {
      void _ignore;
      try {
        await resetPassword(data.token, data.password);
        onSuccess?.();
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Reset failed";
        onError?.(errorMessage);
        throw err;
      }
    },
  });

  // Get the current form based on mode
  // Handle errors from auth hooks
  useEffect(() => {
    if (error) {
      onError?.(error);
    }
  }, [error, onError]);

  // Clear errors when switching modes
  useEffect(() => {
    clearError();
    requestForm.reset();
    resetForm.reset();
  }, [mode, clearError, requestForm, resetForm]);

  if (mode === "request") {
    return (
      <div className={`space-y-6 ${className}`}>
        <form onSubmit={event => void requestForm.handleSubmit(event)} className="space-y-4">
          <FormField label="Email address" error={requestForm.errors.email} required>
            <Input
              type="email"
              placeholder="Enter your email"
              value={requestForm.values.email}
              onChange={e => requestForm.setValue("email", e.target.value)}
              onBlur={() => requestForm.validate()}
              disabled={loading || requestForm.isSubmitting}
              className={requestForm.errors.email ? "border-red-300" : ""}
            />
          </FormField>

          {error && <ErrorMessage>{error}</ErrorMessage>}

          <Button
            type="submit"
            className="w-full"
            disabled={loading || requestForm.isSubmitting}
            loading={loading || requestForm.isSubmitting}
          >
            Send reset link
          </Button>
        </form>

        {showLoginLink && (
          <div className="text-center">
            <Link
              href="/auth/login"
              className="text-sm text-blue-600 hover:text-blue-500 font-medium transition-colors duration-200"
            >
              Back to login
            </Link>
          </div>
        )}
      </div>
    );
  }

  // Reset mode
  return (
    <div className={`space-y-6 ${className}`}>
      <form onSubmit={event => void resetForm.handleSubmit(event)} className="space-y-4">
        <FormField label="New password" error={resetForm.errors.password} required>
          <Input
            type="password"
            placeholder="Enter new password"
            value={resetForm.values.password}
            onChange={e => resetForm.setValue("password", e.target.value)}
            onBlur={() => resetForm.validate()}
            disabled={loading || resetForm.isSubmitting}
            className={resetForm.errors.password ? "border-red-300" : ""}
          />
        </FormField>

        <FormField label="Confirm password" error={resetForm.errors.confirmPassword} required>
          <Input
            type="password"
            placeholder="Confirm new password"
            value={resetForm.values.confirmPassword}
            onChange={e => resetForm.setValue("confirmPassword", e.target.value)}
            onBlur={() => resetForm.validate()}
            disabled={loading || resetForm.isSubmitting}
            className={resetForm.errors.confirmPassword ? "border-red-300" : ""}
          />
        </FormField>

        {error && <ErrorMessage>{error}</ErrorMessage>}

        <Button
          type="submit"
          className="w-full"
          disabled={loading || resetForm.isSubmitting}
          loading={loading || resetForm.isSubmitting}
        >
          Update password
        </Button>
      </form>

      {showLoginLink && (
        <div className="text-center">
          <Link
            href="/auth/login"
            className="text-sm text-blue-600 hover:text-blue-500 font-medium transition-colors duration-200"
          >
            Back to login
          </Link>
        </div>
      )}
    </div>
  );
}
