/**
 * Address Step Component
 * Address information fields for signup using Zod validation
 */

"use client";

import { useCallback } from "react";
import { Input } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import type { FormErrors, FormTouched, UseZodFormReturn } from "@customer-portal/validation";
import type { SignupFormValues } from "./SignupForm";
import type { Address } from "@customer-portal/domain/customer";
import { COUNTRY_OPTIONS } from "@/lib/constants/countries";

interface AddressStepProps {
  address: SignupFormValues["address"];
  errors: FormErrors<SignupFormValues>;
  touched: FormTouched<SignupFormValues>;
  onAddressChange: (address: SignupFormValues["address"]) => void;
  setTouchedField: UseZodFormReturn<SignupFormValues>["setTouchedField"];
}

export function AddressStep({
  address,
  errors,
  touched,
  onAddressChange,
  setTouchedField,
}: AddressStepProps) {
  // Use domain Address type directly - no type helpers needed
  const updateAddressField = useCallback(
    (field: keyof Address, value: string) => {
      onAddressChange({ ...(address ?? {}), [field]: value });
    },
    [address, onAddressChange]
  );

  const handleCountryChange = useCallback(
    (code: string) => {
      const normalized = code || "";
      onAddressChange({
        ...(address ?? {}),
        country: normalized,
        countryCode: normalized,
      });
    },
    [address, onAddressChange]
  );

  const getFieldError = useCallback(
    (field: keyof Address) => {
      const fieldKey = `address.${field}`;
      const isTouched = touched[fieldKey] ?? touched.address;

      if (!isTouched) {
        return undefined;
      }

      return errors[fieldKey] ?? errors[field] ?? errors.address;
    },
    [errors, touched]
  );

  const markTouched = useCallback(() => {
    setTouchedField("address");
  }, [setTouchedField]);

  return (
    <div className="space-y-6">
      <FormField label="Street Address" error={getFieldError("address1")} required>
        <Input
          type="text"
          value={address?.address1 || ""}
          onChange={e => updateAddressField("address1", e.target.value)}
          onBlur={markTouched}
          placeholder="Enter your street address"
          className="w-full"
        />
      </FormField>

      <FormField label="Address Line 2 (Optional)" error={getFieldError("address2")}>
        <Input
          type="text"
          value={address?.address2 || ""}
          onChange={e => updateAddressField("address2", e.target.value)}
          onBlur={markTouched}
          placeholder="Apartment, suite, etc."
          className="w-full"
        />
      </FormField>

      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
        <FormField label="City" error={getFieldError("city")} required>
          <Input
            type="text"
            value={address?.city || ""}
            onChange={e => updateAddressField("city", e.target.value)}
            onBlur={markTouched}
            placeholder="Enter your city"
            className="w-full"
          />
        </FormField>

        <FormField label="State/Province" error={getFieldError("state")} required>
          <Input
            type="text"
            value={address?.state || ""}
            onChange={e => updateAddressField("state", e.target.value)}
            onBlur={markTouched}
            placeholder="Enter your state/province"
            className="w-full"
          />
        </FormField>
      </div>

      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
        <FormField label="Postal Code" error={getFieldError("postcode")} required>
          <Input
            type="text"
            value={address?.postcode || ""}
            onChange={e => updateAddressField("postcode", e.target.value)}
            onBlur={markTouched}
            placeholder="Enter your postal code"
            className="w-full"
          />
        </FormField>

        <FormField label="Country" error={getFieldError("country")} required>
          <select
            value={address?.country || ""}
            onChange={e => handleCountryChange(e.target.value)}
            onBlur={markTouched}
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="">Select a country</option>
            {COUNTRY_OPTIONS.map(country => (
              <option key={country.code} value={country.code}>
                {country.name}
              </option>
            ))}
          </select>
        </FormField>
      </div>
    </div>
  );
}
