All files / src/components/features/checkout AddressSelector.tsx

0% Statements 0/495
100% Branches 0/0
0% Functions 0/1
0% Lines 0/495

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
"use client";
import React, { useState, useEffect } from "react";
import { Icon, type IconName } from "@/components/ui/icons";
import { Button, Input } from "@/components/ui";
import { FormRow } from "@/components/ui/FormField";
import type { Address } from "@/types/user";

interface AddressSelectorProps {
  type: "SHIPPING" | "BILLING";
  addresses: Address[];
  selectedAddress: Address | null;
  onAddressSelect: (address: Address | null) => void;
  onAddressChange: (addressData: AddressFormData) => void;
  loading?: boolean;
  sameAsShipping?: boolean;
  onSameAsShippingChange?: (value: boolean) => void;
  shippingAddress?: Address | null;
  defaultUserInfo?: {
    name: string;
    email: string;
    phone: string | null;
  };
  error?: string;
}

export interface AddressFormData {
  name: string;
  email: string;
  phone: string;
  street: string;
  city: string;
  state: string;
  zipCode: string;
  country: string;
}

const emptyFormData: AddressFormData = {
  name: "",
  email: "",
  phone: "",
  street: "",
  city: "",
  state: "",
  zipCode: "",
  country: ""};

export default function AddressSelector({
  type,
  addresses,
  selectedAddress,
  onAddressSelect,
  onAddressChange,
  loading = false,
  sameAsShipping = false,
  onSameAsShippingChange,
  shippingAddress,
  defaultUserInfo,
  error}: AddressSelectorProps) {
  const [isAddingNew, setIsAddingNew] = useState(false);
  const [newAddressData, setNewAddressData] = useState<AddressFormData>(emptyFormData);
  const [savingAddress, setSavingAddress] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  const title = type === "SHIPPING" ? "Shipping Address" : "Billing Address";
  const icon: IconName = type === "SHIPPING" ? "truck" : "credit-card";
  const iconColor = type === "SHIPPING" ? "text-blue" : "text-green";

  // Reset form when switching modes
  useEffect(() => {
    if (isAddingNew && defaultUserInfo) {
      setNewAddressData({
        name: defaultUserInfo.name || "",
        email: defaultUserInfo.email || "",
        phone: defaultUserInfo.phone || "",
        street: "",
        city: "",
        state: "",
        zipCode: "",
        country: ""});
    }
  }, [isAddingNew, defaultUserInfo]);

  // When "same as shipping" is checked, use the shipping address data
  useEffect(() => {
    if (sameAsShipping && shippingAddress) {
      onAddressChange({
        name: shippingAddress.name || "",
        email: shippingAddress.email || "",
        phone: shippingAddress.phone || "",
        street: shippingAddress.street,
        city: shippingAddress.city,
        state: shippingAddress.state,
        zipCode: shippingAddress.zipCode,
        country: shippingAddress.country});
    }
  }, [sameAsShipping, shippingAddress, onAddressChange]);

  const handleSelectAddress = (address: Address) => {
    onAddressSelect(address);
    setIsAddingNew(false);
    onAddressChange({
      name: address.name || "",
      email: address.email || "",
      phone: address.phone || "",
      street: address.street,
      city: address.city,
      state: address.state,
      zipCode: address.zipCode,
      country: address.country});
  };

  const handleAddNew = () => {
    onAddressSelect(null);
    setIsAddingNew(true);
    setNewAddressData({
      name: defaultUserInfo?.name || "",
      email: defaultUserInfo?.email || "",
      phone: defaultUserInfo?.phone || "",
      street: "",
      city: "",
      state: "",
      zipCode: "",
      country: ""});
  };

  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const updated = { ...newAddressData, [name]: value };
    setNewAddressData(updated);
    onAddressChange(updated);
  };

  const handleSaveAddress = async () => {
    setSavingAddress(true);
    setSaveError(null);

    try {
      const response = await fetch("/api/user/addresses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type,
          ...newAddressData,
          email: newAddressData.email || null,
          phone: newAddressData.phone || null,
          isDefault: addresses.length === 0, // Make default if first address
        })});

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error?.message || errorData.error || "Failed to save address");
      }

      const result = await response.json();
      // Extract data from API response wrapper
      const savedAddress = result?.data ?? result;
      handleSelectAddress(savedAddress);
      setIsAddingNew(false);
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : "Failed to save address");
    } finally {
      setSavingAddress(false);
    }
  };

  const handleCancelNew = () => {
    setIsAddingNew(false);
    setNewAddressData(emptyFormData);
    // Re-select the first address if available
    if (addresses.length > 0) {
      handleSelectAddress(addresses[0]);
    }
  };

  const inputClassName = "rounded-md border-gray-3 dark:border-gray-600 bg-gray-1 dark:bg-gray-700 placeholder:text-dark-5 dark:placeholder:text-gray-400 dark:text-gray-200 py-2.5 px-5 focus:shadow-input";

  // Loading state
  if (loading) {
    return (
      <div className="bg-white dark:bg-gray-800 shadow-1 rounded-[10px] p-4 sm:p-8.5">
        <div className="animate-pulse">
          <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-4"></div>
          <div className="h-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
        </div>
      </div>
    );
  }

  // If billing and same as shipping is checked
  if (type === "BILLING" && sameAsShipping) {
    return (
      <div className="bg-white dark:bg-gray-800 shadow-1 rounded-[10px] p-4 sm:p-8.5">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium text-xl text-dark dark:text-white flex items-center gap-2">
            <Icon name={icon} size={24} className={iconColor} />
            {title}
          </h3>
        </div>

        {/* Same as shipping checkbox */}
        {onSameAsShippingChange && (
          <label className="flex items-center gap-2.5 cursor-pointer">
            <input
              type="checkbox"
              checked={sameAsShipping}
              onChange={(e) => onSameAsShippingChange(e.target.checked)}
              className="w-4 h-4 rounded border-gray-3 dark:border-gray-600 text-blue focus:ring-blue focus:ring-2"
            />
            <span className="text-dark dark:text-gray-200 text-custom-sm">
              Same as shipping address
            </span>
          </label>
        )}

        {shippingAddress && (
          <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <p className="text-sm text-gray-600 dark:text-gray-300">
              Using shipping address:
            </p>
            <p className="text-dark dark:text-white font-medium mt-1">
              {shippingAddress.name}
            </p>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {shippingAddress.street}, {shippingAddress.city}, {shippingAddress.state} {shippingAddress.zipCode}
            </p>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 shadow-1 rounded-[10px] p-4 sm:p-8.5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-medium text-xl text-dark dark:text-white flex items-center gap-2">
          <Icon name={icon} size={24} className={iconColor} />
          {title}
        </h3>
        {!isAddingNew && addresses.length > 0 && (
          <Button
            type="button"
            variant="secondary"
            size="sm"
            onClick={handleAddNew}
          >
            <Icon name="plus" size={16} className="mr-1" />
            Add New
          </Button>
        )}
      </div>

      {/* Same as shipping checkbox for billing */}
      {type === "BILLING" && onSameAsShippingChange && (
        <div className="mb-4">
          <label className="flex items-center gap-2.5 cursor-pointer">
            <input
              type="checkbox"
              checked={sameAsShipping}
              onChange={(e) => onSameAsShippingChange(e.target.checked)}
              className="w-4 h-4 rounded border-gray-3 dark:border-gray-600 text-blue focus:ring-blue focus:ring-2"
            />
            <span className="text-dark dark:text-gray-200 text-custom-sm">
              Same as shipping address
            </span>
          </label>
        </div>
      )}

      {error && (
        <div className="mb-4 p-3 rounded-md bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-300 text-sm">
          {error}
        </div>
      )}

      {/* Saved addresses list */}
      {!isAddingNew && addresses.length > 0 && (
        <div className="space-y-3 mb-4">
          {addresses.map((address) => (
            <div
              key={address.id}
              onClick={() => handleSelectAddress(address)}
              className={`
                p-4 rounded-lg border-2 cursor-pointer transition-all
                ${selectedAddress?.id === address.id
                  ? "border-blue bg-blue/5 dark:bg-blue/10"
                  : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"
                }
              `}
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="font-medium text-dark dark:text-white">
                      {address.name || "Unnamed"}
                    </p>
                    {address.isDefault && (
                      <span className="px-2 py-0.5 text-xs font-medium bg-blue text-white rounded-full">
                        Default
                      </span>
                    )}
                  </div>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                    {address.street}
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    {address.city}, {address.state} {address.zipCode}
                  </p>
                  {address.phone && (
                    <p className="text-sm text-gray-500 dark:text-gray-500 mt-1">
                      {address.phone}
                    </p>
                  )}
                </div>
                <div className="flex items-center justify-center w-5 h-5 rounded-full border-2 border-gray-300 dark:border-gray-600">
                  {selectedAddress?.id === address.id && (
                    <div className="w-3 h-3 rounded-full bg-blue" />
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* No addresses - show form */}
      {addresses.length === 0 && !isAddingNew && (
        <div className="text-center py-6 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
          <Icon name="map-pin" size={32} className="mx-auto mb-3 text-gray-400 dark:text-gray-500" />
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            No saved {type.toLowerCase()} address
          </p>
          <Button type="button" variant="primary" size="sm" onClick={handleAddNew}>
            <Icon name="plus" size={16} className="mr-1" />
            Add {title}
          </Button>
        </div>
      )}

      {/* Add new address form */}
      {(isAddingNew || addresses.length === 0) && (
        <div className="space-y-4">
          {addresses.length > 0 && (
            <div className="flex items-center justify-between border-b border-gray-200 dark:border-gray-700 pb-3 mb-4">
              <h4 className="font-medium text-dark dark:text-gray-200">
                New {title}
              </h4>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={handleCancelNew}
              >
                Cancel
              </Button>
            </div>
          )}

          {saveError && (
            <div className="p-3 rounded-md bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-300 text-sm">
              {saveError}
            </div>
          )}

          {/* Contact Information */}
          <div>
            <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
              Contact Information
            </h5>
            <div className="space-y-4">
              <Input
                label="Full Name"
                type="text"
                name="name"
                value={newAddressData.name}
                onChange={handleFormChange}
                required
                placeholder="John Doe"
                fullWidth
                className={inputClassName}
              />
              <FormRow gap={6} className="gap-4">
                <Input
                  label="Email (Optional)"
                  type="email"
                  name="email"
                  value={newAddressData.email}
                  onChange={handleFormChange}
                  placeholder="john@example.com"
                  fullWidth
                  className={inputClassName}
                />
                <Input
                  label="Phone (Optional)"
                  type="tel"
                  name="phone"
                  value={newAddressData.phone}
                  onChange={handleFormChange}
                  placeholder="(555) 123-4567"
                  fullWidth
                  className={inputClassName}
                />
              </FormRow>
            </div>
          </div>

          {/* Address Fields */}
          <div>
            <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
              Address Details
            </h5>
            <div className="space-y-4">
              <Input
                label="Street Address"
                type="text"
                name="street"
                value={newAddressData.street}
                onChange={handleFormChange}
                required
                placeholder="123 Main Street"
                fullWidth
                className={inputClassName}
              />
              <FormRow gap={6} className="gap-4">
                <Input
                  label="City"
                  type="text"
                  name="city"
                  value={newAddressData.city}
                  onChange={handleFormChange}
                  required
                  placeholder="New York"
                  fullWidth
                  className={inputClassName}
                />
                <Input
                  label="State/Province"
                  type="text"
                  name="state"
                  value={newAddressData.state}
                  onChange={handleFormChange}
                  required
                  placeholder="NY"
                  fullWidth
                  className={inputClassName}
                />
              </FormRow>
              <FormRow gap={6} className="gap-4">
                <Input
                  label="ZIP/Postal Code"
                  type="text"
                  name="zipCode"
                  value={newAddressData.zipCode}
                  onChange={handleFormChange}
                  required
                  placeholder="10001"
                  fullWidth
                  className={inputClassName}
                />
                <Input
                  label="Country"
                  type="text"
                  name="country"
                  value={newAddressData.country}
                  onChange={handleFormChange}
                  required
                  placeholder="United States"
                  fullWidth
                  className={inputClassName}
                />
              </FormRow>
            </div>
          </div>

          {/* Save button */}
          <div className="flex gap-3 pt-2">
            <Button
              type="button"
              variant="secondary"
              size="sm"
              onClick={handleSaveAddress}
              loading={savingAddress}
              disabled={!newAddressData.name || !newAddressData.street || !newAddressData.city || !newAddressData.state || !newAddressData.zipCode || !newAddressData.country}
            >
              <Icon name="check" size={16} className="mr-1" />
              Save Address
            </Button>
            <span className="text-sm text-gray-500 dark:text-gray-400 self-center">
              or continue without saving
            </span>
          </div>
        </div>
      )}
    </div>
  );
}