"use client";

import dynamic from "next/dynamic";

import { FormField } from "@/components/ui/form-field";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Typography } from "@/components/ui/typography";
import { useTranslation } from "@/hooks/useTranslation";
import type { RegistrationForm } from "./types";
import type { LatLng } from "./StationMapPicker";

/**
 * Leaflet reads `window` at import time, so the picker loads browser-only.
 * Keep this the sole dynamic boundary for the map on this screen.
 */
const StationMapPicker = dynamic(
  () => import("./StationMapPicker").then((mod) => mod.StationMapPicker),
  {
    ssr: false,
    loading: () => (
      <Skeleton className="h-[300px] w-full rounded-[12px] sm:h-[360px]" />
    ),
  },
);

export function StationSection({ form }: { form: RegistrationForm }) {
  const { t } = useTranslation();
  const { control } = form;

  const lat = form.watch("stationLatitude");
  const lng = form.watch("stationLongitude");
  const radiusKm = form.watch("serviceRadiusKm") ?? 10;
  const pin: LatLng | null =
    typeof lat === "number" && typeof lng === "number" ? { lat, lng } : null;

  function handlePick(coords: LatLng) {
    form.setValue("stationLatitude", coords.lat, { shouldTouch: true });
    form.setValue("stationLongitude", coords.lng, { shouldTouch: true });
    // Validate BOTH together: the superRefine "location required" error is keyed
    // on stationLatitude, so validating the fields one-at-a-time would leave a
    // stale error on stationLatitude after the pin is actually placed.
    void form.trigger(["stationLatitude", "stationLongitude"]);
  }

  const locationError = form.formState.errors.stationLatitude;
  const showLocationError =
    !!locationError &&
    (form.formState.touchedFields.stationLatitude ||
      form.formState.submitCount > 0);

  return (
    <div className="flex flex-col gap-5">
      <FormField
        control={control}
        name="stationAddress"
        label={t("auth.registerProvider.location.address")}
        render={({ field, hasError, id }) => (
          <Input
            id={id}
            placeholder={t("auth.registerProvider.location.addressPlaceholder")}
            aria-invalid={hasError}
            {...field}
          />
        )}
      />

      <div className="grid gap-5 sm:grid-cols-2">
        <FormField
          control={control}
          name="stationCity"
          label={t("auth.registerProvider.location.city")}
          render={({ field, hasError, id }) => (
            <Input
              id={id}
              placeholder={t("auth.registerProvider.location.cityPlaceholder")}
              aria-invalid={hasError}
              {...field}
            />
          )}
        />
        <FormField
          control={control}
          name="stationState"
          label={t("auth.registerProvider.location.state")}
          render={({ field, hasError, id }) => (
            <Input
              id={id}
              placeholder={t("auth.registerProvider.location.statePlaceholder")}
              aria-invalid={hasError}
              {...field}
              value={field.value ?? ""}
            />
          )}
        />
      </div>

      <FormField
        control={control}
        name="stationZipCode"
        label={t("auth.registerProvider.location.zip")}
        render={({ field, hasError, id }) => (
          <Input
            id={id}
            placeholder={t("auth.registerProvider.location.zipPlaceholder")}
            aria-invalid={hasError}
            {...field}
            value={field.value ?? ""}
          />
        )}
      />

      {/* Map pin */}
      <div className="flex flex-col gap-1.5">
        <Label>{t("auth.registerProvider.location.coordinates")}</Label>
        <StationMapPicker
          value={pin}
          onChange={handlePick}
          radiusKm={radiusKm}
          getAddressQuery={() =>
            [
              form.getValues("stationAddress"),
              form.getValues("stationCity"),
              form.getValues("stationState"),
              form.getValues("stationZipCode"),
            ]
              .map((part) => part?.trim())
              .filter(Boolean)
              .join(", ")
          }
        />
        <Typography
          as="p"
          variant="caption"
          color="secondary"
          className="mt-0.5"
        >
          {t("auth.registerProvider.location.pinHint")}
        </Typography>
        {showLocationError && (
          <Typography
            as="p"
            variant="caption"
            className="text-destructive mt-0.5"
          >
            {t(locationError?.message ?? "")}
          </Typography>
        )}
      </div>

      {/* Service radius */}
      <FormField
        control={control}
        name="serviceRadiusKm"
        label={t("auth.registerProvider.location.radius")}
        description={t("auth.registerProvider.location.radiusHint")}
        render={({ field, hasError, id }) => (
          <InputGroup dir="ltr">
            <InputGroupInput
              id={id}
              type="number"
              inputMode="numeric"
              min={1}
              max={200}
              className="font-numeric"
              aria-invalid={hasError}
              value={field.value ?? ""}
              onBlur={field.onBlur}
              onChange={(event) =>
                field.onChange(
                  event.target.value === ""
                    ? undefined
                    : Number(event.target.value),
                )
              }
            />
            <InputGroupAddon align="inline-end">
              <InputGroupText>
                {t("auth.registerProvider.location.kmUnit")}
              </InputGroupText>
            </InputGroupAddon>
          </InputGroup>
        )}
      />
    </div>
  );
}
