/**
 * Link WHMCS Form - Account migration form using domain schema
 */

"use client";

import { Button, Input, ErrorMessage } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { useWhmcsLink } from "@/features/auth/hooks";
import { linkWhmcsRequestSchema, type LinkWhmcsResponse } from "@customer-portal/domain/auth";
import { useZodForm } from "@/shared/hooks";

interface LinkWhmcsFormProps {
  onTransferred?: ((result: LinkWhmcsResponse) => void) | undefined;
  className?: string | undefined;
  initialEmail?: string | undefined;
}

export function LinkWhmcsForm({ onTransferred, className = "", initialEmail }: LinkWhmcsFormProps) {
  const { linkWhmcs, loading, error, clearError } = useWhmcsLink();

  const form = useZodForm({
    schema: linkWhmcsRequestSchema,
    initialValues: { email: initialEmail ?? "", password: "" },
    onSubmit: async data => {
      clearError();
      const result = await linkWhmcs(data);
      onTransferred?.(result);
    },
  });

  const isLoading = form.isSubmitting || loading;

  return (
    <form onSubmit={e => void form.handleSubmit(e)} className={`space-y-5 ${className}`}>
      <FormField
        label="Email Address"
        error={form.touched["email"] ? form.errors["email"] : undefined}
        required
      >
        <Input
          type="email"
          value={form.values.email}
          onChange={e => form.setValue("email", e.target.value)}
          onBlur={() => form.setTouchedField("email")}
          placeholder="you@example.com"
          disabled={isLoading}
          autoComplete="email"
          autoFocus
        />
      </FormField>

      <FormField
        label="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.setTouchedField("password")}
          placeholder="Enter your legacy portal password"
          disabled={isLoading}
          autoComplete="current-password"
        />
      </FormField>

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

      <Button
        type="submit"
        disabled={isLoading || !form.values.email || !form.values.password}
        loading={isLoading}
        loadingText="Verifying..."
        className="w-full"
      >
        Transfer My Account
      </Button>

      <p className="text-xs text-gray-500 text-center">
        Your credentials are encrypted and used only to verify your identity
      </p>
    </form>
  );
}
