"use client";
import { useAtom } from "jotai";
import { Section } from "../section";
import { formAtom, auctionConfigAtom } from "@/components/state/autionAtoms";
import { Autocomplete, AutocompleteItem } from "@heroui/react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import LocationMapPicker from "@/components/maps/LocationMapPicker";
import { DEFAULT_MAP_LAT, DEFAULT_MAP_LNG } from "@/lib/mapDefaults";
import { API_BASE_URL } from "@/lib/axios";

export function Step6({
  showErrors = false,
  /** Hide map UI (e.g. annual group single-auction flow still sends default lat/lng). */
  hideMap = false,
}: {
  showErrors?: boolean;
  hideMap?: boolean;
}) {
  const t = useTranslations("ADD_LISTING.STEP6");
  const [form, setForm] = useAtom(formAtom);
  const [config] = useAtom(auctionConfigAtom);

  const [states, setStates] = useState<any[]>([]);
  const [loadingStates, setLoadingStates] = useState(false);

  const isSaudiCountry = (countryId?: string | null) => {
    if (!countryId) return false;
    const countries = (config as any)?.countries as any[] | undefined;
    const c = countries?.find((x) => String(x?.id) === String(countryId));
    const name = String(c?.name || "");
    return (
      String(countryId) === "1" ||
      name.includes("السعود") ||
      name.toLowerCase().includes("saudi")
    );
  };

  const findRiyadh = (list: any[]) => {
    return (list || []).find((s) => {
      const n = String(s?.name || "").toLowerCase();
      return n.includes("الرياض") || n.includes("riyadh");
    });
  };

  useEffect(() => {
    if (form.country_id) return;
    const countries = (config as any)?.countries as any[] | undefined;
    if (!countries || countries.length === 0) return;

    const sa = countries.find((c) => {
      const name = String(c?.name || "");
      return name.includes("السعود") || name.toLowerCase().includes("saudi");
    });

    if (!sa?.id) return;
    setForm((p) => ({
      ...p,
      country_id: String(sa.id),
      country_name: sa?.name || "",
      state_id: "",
      state_name: "",
    }));
  }, [config, form.country_id, setForm]);

  useEffect(() => {
    const fetchStates = async () => {
      if (!form.country_id) return;
      setLoadingStates(true);

      try {
        const res = await fetch(
          `${API_BASE_URL}/user/config/reference-data?states=1&country_id=${form.country_id}`,
        );
        const data = await res.json();
        const list = (data?.data?.states as any[]) || data?.data || [];
        const riyadh = findRiyadh(list);
        const nextStates =
          isSaudiCountry(String(form.country_id)) && riyadh
            ? [
                riyadh,
                ...list.filter((s: any) => String(s?.id) !== String(riyadh.id)),
              ]
            : list;

        setStates(nextStates);

        if (
          isSaudiCountry(String(form.country_id)) &&
          !form.state_id &&
          riyadh?.id
        ) {
          setForm((p) => ({
            ...p,
            state_id: String(riyadh.id),
            state_name: riyadh?.name || "",
          }));
        }
      } catch (err) {
        console.error("Error loading states:", err);
        setStates([]);
      } finally {
        setLoadingStates(false);
      }
    };

    fetchStates();
  }, [config, form.country_id, form.state_id, setForm]);

  return (
    <Section title={t("title")}>
      <div className="grid sm:grid-cols-3 gap-4 text-start">
        <div className="flex flex-col gap-1">
          <label className="text-sm font-semibold text-gray-700 mb-1">
            {t("country")}
          </label>
          <Autocomplete
            selectedKey={form.country_id ? String(form.country_id) : undefined}
            onSelectionChange={(key) => {
              if (!key) return;
              const countryId = String(key);
              const country = config?.countries?.find(
                (c: any) => String(c.id) === countryId,
              );
              setForm((p) => ({
                ...p,
                country_id: countryId,
                country_name: country?.name || "",
                state_id: "",
                state_name: "",
              }));
            }}
            placeholder={t("country")}
            variant="flat"
            className="max-w-full"
            isInvalid={showErrors && !form.country_id}
            errorMessage={showErrors && !form.country_id ? t("country_required") : undefined}
            isDisabled={!config?.countries?.length}
            defaultItems={config?.countries || []}
          >
            {(country: any) => (
              <AutocompleteItem key={String(country.id)}>
                {country.name}
              </AutocompleteItem>
            )}
          </Autocomplete>
        </div>

        <div className="flex flex-col gap-1">
          <label className="text-sm font-semibold text-gray-700 mb-1">
            {t("state")}
          </label>
          <Autocomplete
            selectedKey={form.state_id ? String(form.state_id) : undefined}
            onSelectionChange={(key) => {
              if (!key) return;
              const stateId = String(key);
              const state = states.find((s) => String(s.id) === stateId);
              setForm((p) => ({
                ...p,
                state_id: stateId,
                state_name: state?.name || "",
              }));
            }}
            placeholder={
              !form.country_id
                ? t("select_country_first")
                : loadingStates
                  ? t("loading_states")
                  : t("state")
            }
            variant="flat"
            className="max-w-full"
            isInvalid={showErrors && !form.state_id}
            errorMessage={showErrors && !form.state_id ? t("state_required") : undefined}
            isDisabled={!form.country_id || loadingStates}
            isLoading={loadingStates}
            defaultItems={states}
          >
            {(state: any) => (
              <AutocompleteItem key={String(state.id)}>
                {state.name}
              </AutocompleteItem>
            )}
          </Autocomplete>
        </div>
      </div>

      {!hideMap ? (
        <div className="mt-6 space-y-2 text-start">
          <label className="text-sm font-semibold text-gray-700">
            {t("map_title")}
          </label>
          <p className="text-sm text-slate-500">{t("map_hint")}</p>
          <LocationMapPicker
            lat={form.lat ?? DEFAULT_MAP_LAT}
            lng={form.lng ?? DEFAULT_MAP_LNG}
            height={260}
            onChange={({ lat, lng }) =>
              setForm((p) => ({ ...p, lat, lng }))
            }
          />
          <div
            className="text-xs text-slate-600 font-mono"
            dir="ltr"
          >{`${(form.lat ?? DEFAULT_MAP_LAT).toFixed(6)}, ${(form.lng ?? DEFAULT_MAP_LNG).toFixed(6)}`}</div>
        </div>
      ) : null}
    </Section>
  );
}
