/**
 * Set Password Form Component
 * Form for setting password after WHMCS account linking - 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 { useWhmcsLink } from "../../hooks/use-auth";
import { useZodForm } from "@customer-portal/validation";
import { setPasswordRequestSchema } from "@customer-portal/domain/auth";
import { z } from "zod";

interface SetPasswordFormProps {
  email?: string;
  onSuccess?: () => void;
  onError?: (error: string) => void;
  showLoginLink?: boolean;
  className?: string;
}

export function SetPasswordForm({
  email = "",
  onSuccess,
  onError,
  showLoginLink = true,
  className = "",
}: SetPasswordFormProps) {
  const { setPassword, loading, error, clearError } = useWhmcsLink();

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

  type SetPasswordFormValues = z.infer<typeof setPasswordFormSchema>;

  const form = useZodForm<SetPasswordFormValues>({
    schema: setPasswordFormSchema,
    initialValues: {
      email,
      password: "",
      confirmPassword: "",
    },
    onSubmit: async ({ confirmPassword: _ignore, ...data }) => {
      void _ignore;
      clearError();
      try {
        await setPassword(data.email, data.password);
        onSuccess?.();
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Failed to set password";
        onError?.(errorMessage);
        throw err;
      }
    },
  });

  // Handle errors from auth hooks
  useEffect(() => {
    if (error) {
      onError?.(error);
    }
  }, [error, onError]);

  // Update email when prop changes
  useEffect(() => {
    if (email && email !== form.values.email) {
      form.setValue("email", email);
    }
  }, [email, form]);

  return (
    <div className={`space-y-6 ${className}`}>
      <div className="text-center">
        <h2 className="text-2xl font-bold text-gray-900">Set your password</h2>
        <p className="mt-2 text-sm text-gray-600">
          Create a password for your account to complete the setup.
        </p>
      </div>

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

        <FormField label="Password" error={form.errors.password} required>
          <Input
            type="password"
            placeholder="Enter your password"
            value={form.values.password}
            onChange={e => form.setValue("password", e.target.value)}
            onBlur={() => form.setTouched("password", true)}
            disabled={loading || form.isSubmitting}
            className={form.errors.password ? "border-red-300" : ""}
          />
        </FormField>

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

        {(error || form.errors._form) && <ErrorMessage>{form.errors._form || error}</ErrorMessage>}

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

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