/**
 * Set Password Form - Password creation after WHMCS migration
 */

"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 { useAuth } from "../../hooks/use-auth";
import { useZodForm } from "@/shared/hooks";
import {
  setPasswordRequestSchema,
  checkPasswordStrength,
  getPasswordStrengthDisplay,
} from "@customer-portal/domain/auth";
import { z } from "zod";

// Extend domain schema with confirmPassword
const setPasswordFormSchema = setPasswordRequestSchema
  .extend({ confirmPassword: z.string().min(1, "Please confirm your password") })
  .refine(data => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

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

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

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

  const { requirements, strength, isValid } = checkPasswordStrength(form.values.password);
  const { label, colorClass } = getPasswordStrengthDisplay(strength);
  const passwordsMatch = form.values.password === form.values.confirmPassword;
  const isLoading = loading || form.isSubmitting;
  const isEmailProvided = Boolean(email);

  useEffect(() => {
    if (error) onError?.(error);
  }, [error, onError]);

  // Extract stable setValue to avoid re-running effect on every render.
  // The form object is recreated each render, but setValue is memoized.
  const formSetValue = form.setValue;
  const formEmailValue = form.values.email;

  useEffect(() => {
    if (email && email !== formEmailValue) formSetValue("email", email);
  }, [email, formEmailValue, formSetValue]);

  return (
    <form onSubmit={e => void form.handleSubmit(e)} className={`space-y-5 ${className}`}>
      <FormField label="Email Address" error={form.errors["email"]} required>
        <Input
          type="email"
          value={form.values.email}
          onChange={e => !isEmailProvided && form.setValue("email", e.target.value)}
          disabled={isLoading || isEmailProvided}
          readOnly={isEmailProvided}
          className={isEmailProvided ? "bg-muted text-muted-foreground" : ""}
        />
        {isEmailProvided && (
          <p className="mt-1 text-xs text-muted-foreground">Verified during account transfer</p>
        )}
      </FormField>

      <FormField
        label="New Password"
        error={form.touched["password"] ? form.errors["password"] : undefined}
        required
      >
        <Input
          type="password"
          value={form.values.password}
          onChange={e => form.setValue("password", e.target.value)}
          onBlur={() => form.setTouched("password", true)}
          placeholder="Create a secure password"
          disabled={isLoading}
          autoComplete="new-password"
          autoFocus
        />
      </FormField>

      {form.values.password && (
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
              <div
                className={`h-full transition-all ${colorClass}`}
                style={{ width: `${strength}%` }}
              />
            </div>
            <span
              className={`text-xs font-medium ${isValid ? "text-success" : "text-muted-foreground"}`}
            >
              {label}
            </span>
          </div>
          <div className="grid grid-cols-2 gap-1">
            {requirements.map(r => (
              <div key={r.key} className="flex items-center gap-1.5 text-xs">
                <span className={r.met ? "text-success" : "text-muted-foreground/60"}>
                  {r.met ? "✓" : "○"}
                </span>
                <span className={r.met ? "text-success" : "text-muted-foreground"}>{r.label}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <FormField
        label="Confirm Password"
        error={form.touched["confirmPassword"] ? form.errors["confirmPassword"] : undefined}
        required
      >
        <Input
          type="password"
          value={form.values.confirmPassword}
          onChange={e => form.setValue("confirmPassword", e.target.value)}
          onBlur={() => form.setTouched("confirmPassword", true)}
          placeholder="Re-enter your password"
          disabled={isLoading}
          autoComplete="new-password"
        />
      </FormField>

      {form.values.confirmPassword && (
        <p className={`text-sm ${passwordsMatch ? "text-success" : "text-danger"}`}>
          {passwordsMatch ? "✓ Passwords match" : "✗ Passwords do not match"}
        </p>
      )}

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

      <Button
        type="submit"
        className="w-full"
        disabled={isLoading || !form.isValid}
        loading={isLoading}
      >
        Set Password & Continue
      </Button>

      <div className="text-center">
        <Link href="/auth/login" className="text-sm text-primary hover:underline">
          Back to login
        </Link>
      </div>
    </form>
  );
}
