"use client";

import { Controller, useFormState, useWatch } from "react-hook-form";
import type { Control, UseFormRegister, UseFormSetValue } from "react-hook-form";
import { TextField } from "@/components/ui/form";
import { PhoneInput } from "@/components/ui/PhoneInput";
import type { TravelerDetailsFormData } from "@/services/flights/traveler-details.schema";

function MailIcon() {
  return (
    <svg
      width={18}
      height={18}
      viewBox="0 0 24 24"
      fill="none"
      strokeWidth={1.8}
      className="stroke-second"
      aria-hidden="true"
    >
      <rect width={20} height={16} x={2} y={4} rx={2} />
      <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
    </svg>
  );
}

export interface ContactCardProps {
  control: Control<TravelerDetailsFormData>;
  register: UseFormRegister<TravelerDetailsFormData>;
  setValue: UseFormSetValue<TravelerDetailsFormData>;
  /** Dial code to fall back to, resolved from the visitor's country. */
  defaultCountry: string;
}

/**
 * Contact details for the whole booking.
 *
 * Deliberately no name here. Agoda's contact block repeats first and last name
 * that the passenger section already collects, and that duplication is the most
 * consistently cited complaint in public critiques of their traveller-details
 * page. The confirmation goes to an address and a number; the name on it is
 * already known from passenger 1.
 */
export default function ContactCard({
  control,
  register,
  setValue,
  defaultCountry,
}: ContactCardProps) {
  const { errors } = useFormState({ control, name: "contact" });
  const countryCode = useWatch({ control, name: "contact.countryCode" });

  return (
    <section
      className="bgColor-white shadow-sm rounded-3 p-3 p-md-4"
      aria-labelledby="contact-heading"
    >
      <p className="text-xs text-muted mb-1 d-flex align-items-center gap-2">
        <MailIcon />
        {/* corp: "this request", not "all bookings" — one request, one
            traveller party, and nothing is booked until an admin approves. */}
        For this request
      </p>
      <h3 id="contact-heading" className="smallHeading mb-1" style={{ textTransform: "none" }}>
        Contact details
      </h3>
      <p className="text-xs text-muted mb-0">
        The approval decision, the e-ticket once it is issued and any airline
        updates go here. One contact covers the whole request.
      </p>
      <p className="lf-required-note mb-3 mt-2">
        <span className="lf-required-star" aria-hidden="true">*</span> Required field
      </p>

      <div className="row g-3">
        <div className="col-md-6">
          <TextField
            id="contact-email"
            type="email"
            label="Email address"
            required
            placeholder="you@example.com"
            autoComplete="email"
            spellCheck={false}
            error={errors.contact?.email?.message}
            {...register("contact.email")}
          />
        </div>

        <div className="col-md-6">
          <Controller
            control={control}
            name="contact.phone"
            render={({ field }) => (
              <PhoneInput
                id="contact-phone"
                label="Mobile number"
                // Required by the schema — `contact.phone` must be 7-15 digits,
                // so an empty field fails Continue. It simply never said so.
                required
                // PhoneInput speaks one digit string; the form stores the dial
                // code and the national number separately because that is the
                // shape Amadeus wants (countryCallingCode + number), so the
                // two halves are recombined here on the way in.
                value={`${(countryCode || "").replace(/\D/g, "")}${(field.value || "").replace(/\D/g, "")}`}
                onChange={() => {}}
                onValuePartsChange={({ dialCode, nationalNumber }) => {
                  setValue("contact.countryCode", dialCode, {
                    shouldDirty: true,
                    shouldValidate: true,
                  });
                  field.onChange(nationalNumber);
                }}
                placeholder="Enter mobile number"
                defaultCountry={defaultCountry}
                preferredCountries={["us", "gb", "in"]}
                error={
                  errors.contact?.phone?.message || errors.contact?.countryCode?.message
                }
              />
            )}
          />
        </div>
      </div>
    </section>
  );
}
