/**
 * Address Step - Japanese address input for WHMCS
 *
 * Field mapping to WHMCS:
 * - postcode → postcode
 * - state → state (prefecture)
 * - city → city
 * - address1 → address1 (building/room)
 * - address2 → address2 (street/block)
 * - country → "JP"
 */

"use client";

import { useCallback, useEffect } from "react";
import { ChevronDown } from "lucide-react";
import { Input } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { JAPAN_PREFECTURES, formatJapanesePostalCode } from "@/shared/constants";

interface AddressData {
  address1: string;
  address2: string;
  city: string;
  state: string;
  postcode: string;
  country: string;
  countryCode?: string | undefined;
}

interface AddressStepProps {
  form: {
    values: { address: AddressData };
    errors: Record<string, string | undefined>;
    touched: Record<string, boolean | undefined>;
    setValue: (field: string, value: unknown) => void;
    setTouchedField: (field: string) => void;
  };
}

export function AddressStep({ form }: AddressStepProps) {
  const { values, errors, touched, setValue, setTouchedField } = form;
  const address = values.address;

  const getError = (field: string) => {
    const key = `address.${field}`;
    return touched[key] || touched["address"] ? (errors[key] ?? errors[field]) : undefined;
  };

  const updateAddress = useCallback(
    (field: keyof AddressData, value: string) => {
      setValue("address", { ...address, [field]: value });
    },
    [address, setValue]
  );

  const handlePostcodeChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const formatted = formatJapanesePostalCode(e.target.value);
      updateAddress("postcode", formatted);
    },
    [updateAddress]
  );

  const markTouched = () => setTouchedField("address");

  // Set Japan as default country on mount if empty
  useEffect(() => {
    if (!address.country) {
      setValue("address", { ...address, country: "JP", countryCode: "JP" });
    }
  }, [address, setValue]);

  return (
    <div className="space-y-5">
      {/* Postal Code - First field for Japanese addresses */}
      <FormField
        label="Postal Code"
        error={getError("postcode")}
        required
        helperText="Format: XXX-XXXX"
      >
        <Input
          name="postal-code"
          type="text"
          inputMode="numeric"
          value={address.postcode}
          onChange={handlePostcodeChange}
          onBlur={markTouched}
          placeholder="100-0001"
          autoComplete="section-signup postal-code"
          maxLength={8}
          autoFocus
          data-field="address.postcode"
        />
      </FormField>

      {/* Prefecture Selection */}
      <FormField label="Prefecture" error={getError("state")} required>
        <div className="relative">
          <select
            name="address-level1"
            value={address.state}
            onChange={e => updateAddress("state", e.target.value)}
            onBlur={markTouched}
            className="block w-full h-11 pl-4 pr-10 py-2.5 border border-border rounded-lg appearance-none bg-card text-foreground text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary transition-colors cursor-pointer"
            autoComplete="section-signup address-level1"
            data-field="address.state"
          >
            <option value="">Select prefecture</option>
            {JAPAN_PREFECTURES.map(p => (
              <option key={p.value} value={p.value}>
                {p.label}
              </option>
            ))}
          </select>
          <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
            <ChevronDown className="h-4 w-4 text-muted-foreground" />
          </div>
        </div>
      </FormField>

      {/* City/Ward */}
      <FormField
        label="City / Ward"
        error={getError("city")}
        required
        helperText="e.g., Shibuya-ku, Chiyoda-ku"
      >
        <Input
          name="address-level2"
          value={address.city}
          onChange={e => updateAddress("city", e.target.value)}
          onBlur={markTouched}
          placeholder="Shibuya-ku"
          autoComplete="section-signup address-level2"
          data-field="address.city"
        />
      </FormField>

      {/* Street / Block (Address 2) */}
      <FormField
        label="Street / Block (Address 2)"
        error={getError("address2")}
        required
        helperText="e.g., 2-20-9 Wakabayashi"
      >
        <Input
          name="address-line1"
          type="text"
          value={address.address2}
          onChange={e => updateAddress("address2", e.target.value)}
          onBlur={markTouched}
          placeholder="2-20-9 Wakabayashi"
          autoComplete="section-signup address-line1"
          required
          data-field="address.address2"
        />
      </FormField>

      {/* Building / Room (Address 1) */}
      <FormField
        label="Building / Room (Address 1)"
        error={getError("address1")}
        required
        helperText="e.g., Gramercy 201"
      >
        <Input
          name="address-line2"
          type="text"
          value={address.address1}
          onChange={e => updateAddress("address1", e.target.value)}
          onBlur={markTouched}
          placeholder="Gramercy 201"
          autoComplete="section-signup address-line2"
          required
          data-field="address.address1"
        />
      </FormField>
    </div>
  );
}
