/**
 * MigrateAccountStep - Migrate WHMCS account to portal (passwordless)
 *
 * For whmcs_unmapped users who have verified their email via OTP.
 * Email verification serves as identity proof - no legacy password needed.
 * Shows prefilled WHMCS data and collects password + terms.
 * DOB and gender are not collected here — WHMCS already has them.
 */

"use client";

import { useState } from "react";
import { Button, Input, PasswordInput, Label } from "@/components/atoms";
import { Checkbox } from "@/components/atoms/checkbox";
import { PasswordRequirements, PasswordMatchIndicator } from "@/features/auth/components";
import { usePasswordValidation } from "@/features/auth/hooks/usePasswordValidation";
import { useGetStartedMachine } from "../../../hooks/useGetStartedMachine";

interface FormErrors {
  password?: string | undefined;
  confirmPassword?: string | undefined;
  acceptTerms?: string | undefined;
}

function validateMigrateForm(
  password: string,
  confirmPassword: string,
  acceptTerms: boolean,
  passwordValidationError: string | undefined
): FormErrors {
  const errors: FormErrors = {};
  if (passwordValidationError) errors.password = passwordValidationError;
  if (password !== confirmPassword) errors.confirmPassword = "Passwords do not match";
  if (!acceptTerms) errors.acceptTerms = "You must accept the terms of service";
  return errors;
}

function useMigrateForm(formData: { acceptTerms: boolean; marketingConsent: boolean }) {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [acceptTerms, setAcceptTerms] = useState(formData.acceptTerms);
  const [marketingConsent, setMarketingConsent] = useState(formData.marketingConsent);
  const [localErrors, setLocalErrors] = useState<FormErrors>({});
  const { checks, error: passwordValidationError } = usePasswordValidation(password);
  const showPasswordMatch = confirmPassword.length > 0 && !localErrors.confirmPassword;
  const passwordsMatch = password === confirmPassword;
  const canSubmit = password && confirmPassword && acceptTerms;

  const clearError = (field: keyof FormErrors) =>
    setLocalErrors(prev => ({ ...prev, [field]: undefined }));
  const validate = (): boolean => {
    const errors = validateMigrateForm(
      password,
      confirmPassword,
      acceptTerms,
      passwordValidationError
    );
    setLocalErrors(errors);
    return Object.keys(errors).length === 0;
  };

  return {
    password,
    setPassword,
    confirmPassword,
    setConfirmPassword,
    acceptTerms,
    setAcceptTerms,
    marketingConsent,
    setMarketingConsent,
    localErrors,
    clearError,
    checks,
    showPasswordMatch,
    passwordsMatch,
    canSubmit,
    validate,
  };
}

function formatPrefillAddress(address: {
  postcode?: string;
  state?: string;
  city?: string;
  address1?: string;
  address2?: string;
}): string {
  return [address.postcode, address.state, address.city, address.address1, address.address2]
    .filter(Boolean)
    .join(", ");
}

function DisabledField({ label, value }: { label: string; value: string }) {
  return (
    <div className="space-y-2">
      <Label className="text-muted-foreground">{label}</Label>
      <Input value={value} disabled className="bg-muted text-muted-foreground" />
    </div>
  );
}

function PrefilledFields({
  prefill,
  formData,
}: {
  prefill: {
    firstName?: string;
    lastName?: string;
    phone?: string;
    address?: {
      postcode?: string;
      state?: string;
      city?: string;
      address1?: string;
      address2?: string;
    };
  } | null;
  formData: { firstName: string; lastName: string; email: string; phone: string };
}) {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <DisabledField label="First Name" value={prefill?.firstName || formData.firstName || ""} />
        <DisabledField label="Last Name" value={prefill?.lastName || formData.lastName || ""} />
      </div>
      <DisabledField label="Email" value={formData.email} />
      {(prefill?.phone || formData.phone) && (
        <DisabledField label="Phone" value={prefill?.phone || formData.phone} />
      )}
      {prefill?.address && (
        <DisabledField label="Address" value={formatPrefillAddress(prefill.address)} />
      )}
    </div>
  );
}

function MigratePasswordFields({
  form,
  loading,
}: {
  form: ReturnType<typeof useMigrateForm>;
  loading: boolean;
}) {
  return (
    <>
      <div className="space-y-2">
        <Label htmlFor="password">
          Password <span className="text-danger">*</span>
        </Label>
        <PasswordInput
          id="password"
          value={form.password}
          onChange={e => {
            form.setPassword(e.target.value);
            form.clearError("password");
          }}
          placeholder="Create a strong password"
          disabled={loading}
          error={form.localErrors.password}
          autoComplete="new-password"
        />
        {form.localErrors.password && (
          <p className="text-sm text-danger">{form.localErrors.password}</p>
        )}
        <PasswordRequirements checks={form.checks} showHint={form.password.length === 0} />
      </div>
      <div className="space-y-2">
        <Label htmlFor="confirmPassword">
          Confirm Password <span className="text-danger">*</span>
        </Label>
        <PasswordInput
          id="confirmPassword"
          value={form.confirmPassword}
          onChange={e => {
            form.setConfirmPassword(e.target.value);
            form.clearError("confirmPassword");
          }}
          placeholder="Confirm your password"
          disabled={loading}
          error={form.localErrors.confirmPassword}
          autoComplete="new-password"
        />
        {form.localErrors.confirmPassword && (
          <p className="text-sm text-danger">{form.localErrors.confirmPassword}</p>
        )}
        {form.showPasswordMatch && <PasswordMatchIndicator passwordsMatch={form.passwordsMatch} />}
      </div>
    </>
  );
}

function MigrateTermsSection({
  form,
  loading,
}: {
  form: ReturnType<typeof useMigrateForm>;
  loading: boolean;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-start gap-2">
        <Checkbox
          id="acceptTerms"
          checked={form.acceptTerms}
          onChange={e => {
            form.setAcceptTerms(e.target.checked);
            form.clearError("acceptTerms");
          }}
          disabled={loading}
        />
        <Label htmlFor="acceptTerms" className="text-sm font-normal leading-tight cursor-pointer">
          I accept the{" "}
          <a
            href="/terms"
            target="_blank"
            rel="noopener noreferrer"
            className="text-primary hover:underline"
          >
            Terms of Service
          </a>{" "}
          and{" "}
          <a
            href="/privacy"
            target="_blank"
            rel="noopener noreferrer"
            className="text-primary hover:underline"
          >
            Privacy Policy
          </a>{" "}
          <span className="text-danger">*</span>
        </Label>
      </div>
      {form.localErrors.acceptTerms && (
        <p className="text-sm text-danger ml-6">{form.localErrors.acceptTerms}</p>
      )}
      <div className="flex items-start gap-2">
        <Checkbox
          id="marketingConsent"
          checked={form.marketingConsent}
          onChange={e => form.setMarketingConsent(e.target.checked)}
          disabled={loading}
        />
        <Label
          htmlFor="marketingConsent"
          className="text-sm font-normal leading-tight cursor-pointer"
        >
          I would like to receive marketing emails and updates
        </Label>
      </div>
    </div>
  );
}

export function MigrateAccountStep() {
  const { state, send } = useGetStartedMachine();
  const { formData, prefill, error } = state.context;
  const loading = state.matches({ migrateAccount: "loading" });
  const form = useMigrateForm(formData);

  const handleSubmit = () => {
    if (!form.validate()) return;
    send({
      type: "UPDATE_FORM_DATA",
      data: { acceptTerms: form.acceptTerms, marketingConsent: form.marketingConsent },
    });
    send({ type: "MIGRATE", password: form.password });
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <p className="text-sm text-muted-foreground">
          {prefill?.firstName
            ? `Welcome back, ${prefill.firstName}! Set up your new portal password.`
            : "Set up your new portal password to continue."}
        </p>
      </div>
      <PrefilledFields prefill={prefill} formData={formData} />
      <MigratePasswordFields form={form} loading={loading} />
      <MigrateTermsSection form={form} loading={loading} />
      {error && (
        <div className="p-3 rounded-lg bg-danger/10 border border-danger/20">
          <p className="text-sm text-danger">{error}</p>
        </div>
      )}
      <div className="space-y-3">
        <Button
          type="button"
          onClick={handleSubmit}
          disabled={loading || !form.canSubmit}
          loading={loading}
          className="w-full h-11"
        >
          {loading ? "Setting Up Account..." : "Set Up Account"}
        </Button>
        <Button
          type="button"
          variant="ghost"
          onClick={() => send({ type: "GO_BACK" })}
          disabled={loading}
          className="w-full"
        >
          Go Back
        </Button>
      </div>
    </div>
  );
}
