/**
 * Account Step - Contact info
 */

"use client";

import { Input } from "@/components/atoms";
import { FormField } from "@/components/molecules/FormField/FormField";
import { genderEnum } from "@customer-portal/domain/common";

interface AccountStepProps {
  form: {
    values: {
      firstName: string;
      lastName: string;
      email: string;
      phone: string;
      phoneCountryCode: string;
      company?: string | undefined;
      dateOfBirth?: string | undefined;
      gender?: "male" | "female" | "other" | undefined;
    };
    errors: Record<string, string | undefined>;
    touched: Record<string, boolean | undefined>;
    setValue: (field: string, value: unknown) => void;
    setTouchedField: (field: string) => void;
  };
}

export function AccountStep({ form }: AccountStepProps) {
  const { values, errors, touched, setValue, setTouchedField } = form;
  const getError = (field: string) => (touched[field] ? errors[field] : undefined);
  const genderOptions = genderEnum.options;
  const formatGender = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);

  return (
    <div className="space-y-5">
      {/* Name Fields */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField label="First Name" error={getError("firstName")} required>
          <Input
            name="given-name"
            value={values.firstName}
            onChange={e => setValue("firstName", e.target.value)}
            onBlur={() => setTouchedField("firstName")}
            placeholder="Taro"
            autoComplete="section-signup given-name"
            autoFocus
            data-field="firstName"
          />
        </FormField>
        <FormField label="Last Name" error={getError("lastName")} required>
          <Input
            name="family-name"
            value={values.lastName}
            onChange={e => setValue("lastName", e.target.value)}
            onBlur={() => setTouchedField("lastName")}
            placeholder="Yamada"
            autoComplete="section-signup family-name"
            data-field="lastName"
          />
        </FormField>
      </div>

      {/* Email */}
      <FormField label="Email Address" error={getError("email")} required>
        <Input
          name="email"
          type="email"
          value={values.email}
          onChange={e => setValue("email", e.target.value)}
          onBlur={() => setTouchedField("email")}
          placeholder="taro.yamada@example.com"
          autoComplete="section-signup email"
          data-field="email"
        />
      </FormField>

      {/* Phone - Country code + number */}
      <FormField
        label="Phone Number"
        error={getError("phone") || getError("phoneCountryCode")}
        required
      >
        <div className="flex gap-2">
          <Input
            name="tel-country-code"
            type="tel"
            value={values.phoneCountryCode}
            onChange={e => {
              // Allow + and digits only, max 5 chars
              let val = e.target.value.replace(/[^\d+]/g, "");
              if (!val.startsWith("+")) val = "+" + val.replace(/\+/g, "");
              if (val.length > 5) val = val.slice(0, 5);
              setValue("phoneCountryCode", val);
            }}
            onBlur={() => setTouchedField("phoneCountryCode")}
            placeholder="+81"
            autoComplete="section-signup tel-country-code"
            className="w-20 text-center"
            data-field="phoneCountryCode"
          />
          <Input
            name="tel-national"
            type="tel"
            value={values.phone}
            onChange={e => {
              // Only allow digits
              const cleaned = e.target.value.replace(/\D/g, "");
              setValue("phone", cleaned);
            }}
            onBlur={() => setTouchedField("phone")}
            placeholder="9012345678"
            autoComplete="section-signup tel-national"
            className="flex-1"
            data-field="phone"
          />
        </div>
      </FormField>

      {/* DOB + Gender (Required) */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <FormField label="Date of Birth" error={getError("dateOfBirth")} required>
          <Input
            name="bday"
            type="date"
            value={values.dateOfBirth ?? ""}
            onChange={e => setValue("dateOfBirth", e.target.value || undefined)}
            onBlur={() => setTouchedField("dateOfBirth")}
            autoComplete="section-signup bday"
            data-field="dateOfBirth"
          />
        </FormField>

        <FormField label="Gender" error={getError("gender")} required>
          <select
            name="sex"
            value={values.gender ?? ""}
            onChange={e => setValue("gender", e.target.value || undefined)}
            onBlur={() => setTouchedField("gender")}
            autoComplete="section-signup sex"
            data-field="gender"
            className={[
              "flex h-10 w-full rounded-md border border-input bg-background text-foreground px-3 py-2 text-sm",
              "ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none",
              "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
              "disabled:cursor-not-allowed disabled:opacity-50",
              getError("gender")
                ? "border-danger focus-visible:ring-danger focus-visible:ring-offset-2"
                : "",
            ].join(" ")}
            aria-invalid={Boolean(getError("gender")) || undefined}
          >
            <option value="">Select…</option>
            {genderOptions.map(option => (
              <option key={option} value={option}>
                {formatGender(option)}
              </option>
            ))}
          </select>
        </FormField>
      </div>

      {/* Company (Optional) */}
      <FormField label="Company" error={getError("company")} helperText="Optional">
        <Input
          name="organization"
          value={values.company ?? ""}
          onChange={e => setValue("company", e.target.value)}
          onBlur={() => setTouchedField("company")}
          placeholder="Company name"
          autoComplete="section-signup organization"
          data-field="company"
        />
      </FormField>
    </div>
  );
}
