/**
 * CompleteAccountStep - Complete account creation after OTP verification
 *
 * Collects: Password, Phone, DOB, Gender, Terms
 * Shows pre-filled info from form step
 */

"use client";

import { useState, useCallback } from "react";
import { ArrowLeft } from "lucide-react";
import { Button, ErrorMessage } from "@/components/atoms";
import { TermsCheckbox, MarketingCheckbox } from "@/features/auth/components";
import {
  validatePasswordRules,
  usePasswordValidation,
} from "@/features/auth/hooks/usePasswordValidation";
import { useEligibilityCheckStore } from "../../../stores/eligibility-check.store";
import { AccountInfoDisplay, PersonalInfoFields, PasswordSection } from "./complete-account";

interface AccountFormErrors {
  password?: string | undefined;
  confirmPassword?: string | undefined;
  phone?: string | undefined;
  dateOfBirth?: string | undefined;
  gender?: string | undefined;
  acceptTerms?: string | undefined;
}

export function CompleteAccountStep() {
  const {
    formData,
    accountData,
    updateAccountData,
    completeAccount,
    goBack,
    loading,
    error,
    clearError,
  } = useEligibilityCheckStore();

  const [accountErrors, setAccountErrors] = useState<AccountFormErrors>({});

  const clearLocalError = useCallback((field: keyof AccountFormErrors) => {
    setAccountErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });
  }, []);

  const { isValid: isPasswordValid } = usePasswordValidation(accountData.password);
  const doPasswordsMatch = accountData.password === accountData.confirmPassword;

  const validateAccountForm = useCallback((): boolean => {
    const errors: AccountFormErrors = {};

    const passwordError = validatePasswordRules(accountData.password);
    if (passwordError) errors.password = passwordError;
    if (accountData.password !== accountData.confirmPassword)
      errors.confirmPassword = "Passwords do not match";
    if (!accountData.phone.trim()) errors.phone = "Phone number is required";
    if (!accountData.dateOfBirth) errors.dateOfBirth = "Date of birth is required";
    if (!accountData.gender) errors.gender = "Please select a gender";
    if (!accountData.acceptTerms) errors.acceptTerms = "You must accept the terms of service";

    setAccountErrors(errors);
    return Object.keys(errors).length === 0;
  }, [accountData]);

  const handleSubmit = async () => {
    if (!validateAccountForm()) return;
    clearError();
    await completeAccount();
  };

  const canSubmit =
    accountData.password &&
    accountData.confirmPassword &&
    accountData.phone &&
    accountData.dateOfBirth &&
    accountData.gender &&
    accountData.acceptTerms &&
    isPasswordValid &&
    doPasswordsMatch &&
    Object.keys(accountErrors).length === 0;

  return (
    <div className="space-y-6">
      <AccountInfoDisplay
        firstName={formData.firstName}
        lastName={formData.lastName}
        email={formData.email}
        address={formData.address}
      />

      <PersonalInfoFields
        phone={accountData.phone}
        dateOfBirth={accountData.dateOfBirth}
        gender={accountData.gender}
        onPhoneChange={phone => updateAccountData({ phone })}
        onDateOfBirthChange={dateOfBirth => updateAccountData({ dateOfBirth })}
        onGenderChange={gender => updateAccountData({ gender })}
        errors={accountErrors}
        clearError={clearLocalError}
        loading={loading}
      />

      <PasswordSection
        password={accountData.password}
        confirmPassword={accountData.confirmPassword}
        onPasswordChange={password => updateAccountData({ password })}
        onConfirmPasswordChange={confirmPassword => updateAccountData({ confirmPassword })}
        errors={accountErrors}
        clearError={clearLocalError}
        loading={loading}
      />

      <div className="space-y-3">
        <TermsCheckbox
          checked={accountData.acceptTerms}
          onChange={acceptTerms => {
            updateAccountData({ acceptTerms });
            clearLocalError("acceptTerms");
          }}
          disabled={loading}
          error={accountErrors.acceptTerms}
        />
        <MarketingCheckbox
          checked={accountData.marketingConsent}
          onChange={marketingConsent => updateAccountData({ marketingConsent })}
          disabled={loading}
        />
      </div>

      {error && (
        <div className="p-4 rounded-lg bg-danger/10 border border-danger/20">
          <ErrorMessage showIcon>{error}</ErrorMessage>
        </div>
      )}

      <div className="space-y-3">
        <Button
          type="button"
          onClick={handleSubmit}
          disabled={loading || !canSubmit}
          loading={loading}
          loadingText="Creating Account..."
          className="w-full"
        >
          Create Account
        </Button>

        <Button
          type="button"
          variant="ghost"
          onClick={goBack}
          disabled={loading}
          leftIcon={<ArrowLeft className="h-4 w-4" />}
          className="w-full"
        >
          Go Back
        </Button>
      </div>
    </div>
  );
}
