/**
 * CompleteAccountStep - Full account creation form
 *
 * Handles two cases:
 * - SF-only users (prefill exists): Show pre-filled info, just add password
 * - New customers (no prefill): Full form with name, address, password
 */

"use client";

import { Button } from "@/components/atoms";
import { TermsCheckbox, MarketingCheckbox } from "@/features/auth/components";
import { useGetStartedMachine } from "../../../hooks/useGetStartedMachine";
import {
  PrefilledUserInfo,
  NewCustomerFields,
  AddressFields,
  PersonalInfoFields,
  PasswordSection,
  useCompleteAccountForm,
} from "./complete-account";
import type { PrefillData } from "./complete-account/types";
import type { GetStartedFormData } from "../../../machines/get-started.types";

function computeAccountFlags(accountStatus: string | null, prefill: PrefillData | null) {
  const isNewCustomer = accountStatus === "new_customer";
  const hasPrefill = !!(prefill?.firstName || prefill?.lastName);
  const addr = prefill?.address;
  const hasCompleteAddress = !!(
    addr?.postcode &&
    addr?.prefectureJa &&
    addr?.cityJa &&
    addr?.streetAddress
  );
  const isSfUnmappedIncomplete = accountStatus === "sf_unmapped" && !hasCompleteAddress;
  return {
    isNewCustomer,
    hasPrefill,
    isSfUnmappedIncomplete,
    needsAddress: isNewCustomer || isSfUnmappedIncomplete,
  };
}

export function CompleteAccountStep() {
  const { state, send } = useGetStartedMachine();
  const { formData, prefill, accountStatus, error } = state.context;
  const loading = state.matches({ completeAccount: "loading" });
  const { isNewCustomer, hasPrefill, isSfUnmappedIncomplete, needsAddress } = computeAccountFlags(
    accountStatus,
    prefill
  );

  const form = useCompleteAccountForm({
    initialValues: {
      firstName: formData.firstName || prefill?.firstName,
      lastName: formData.lastName || prefill?.lastName,
      phone: formData.phone || prefill?.phone,
      dateOfBirth: formData.dateOfBirth,
      gender: formData.gender,
      acceptTerms: formData.acceptTerms,
      marketingConsent: formData.marketingConsent,
    },
    isNewCustomer,
    needsAddress,
    updateFormData: (data: Partial<GetStartedFormData>) => send({ type: "UPDATE_FORM_DATA", data }),
  });

  const handleSubmit = () => {
    if (!form.validate()) return;
    send({
      type: "COMPLETE",
      formData: { ...formData, ...form.getFormData() } as GetStartedFormData,
    });
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <p className="text-sm text-muted-foreground">
          {hasPrefill
            ? `Welcome back, ${prefill?.firstName}! Just a few more details.`
            : "Fill in your details to create your account."}
        </p>
      </div>

      {hasPrefill && <PrefilledUserInfo prefill={prefill!} email={formData.email} />}
      {isNewCustomer && (
        <NewCustomerFields
          firstName={form.firstName}
          lastName={form.lastName}
          onFirstNameChange={form.setFirstName}
          onLastNameChange={form.setLastName}
          onAddressChange={form.handleAddressChange}
          errors={form.errors}
          clearError={form.clearError}
          loading={loading}
        />
      )}
      {isSfUnmappedIncomplete && (
        <AddressFields
          onAddressChange={form.handleAddressChange}
          errors={form.errors}
          loading={loading}
        />
      )}

      <PersonalInfoFields
        phone={form.phone}
        dateOfBirth={form.dateOfBirth}
        gender={form.gender}
        onPhoneChange={form.setPhone}
        onDateOfBirthChange={form.setDateOfBirth}
        onGenderChange={form.setGender}
        errors={form.errors}
        clearError={form.clearError}
        loading={loading}
      />
      <PasswordSection
        password={form.password}
        confirmPassword={form.confirmPassword}
        onPasswordChange={form.setPassword}
        onConfirmPasswordChange={form.setConfirmPassword}
        errors={form.errors}
        clearError={form.clearError}
        loading={loading}
      />

      <div className="space-y-3">
        <TermsCheckbox
          checked={form.acceptTerms}
          onChange={checked => {
            form.setAcceptTerms(checked);
            form.clearError("acceptTerms");
          }}
          disabled={loading}
          error={form.errors.acceptTerms}
        />
        <MarketingCheckbox
          checked={form.marketingConsent}
          onChange={form.setMarketingConsent}
          disabled={loading}
        />
      </div>

      {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 ? "Creating Account..." : "Create Account"}
        </Button>
        <Button
          type="button"
          variant="ghost"
          onClick={() => send({ type: "GO_BACK" })}
          disabled={loading}
          className="w-full"
        >
          Go Back
        </Button>
      </div>
    </div>
  );
}
