"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import Container from "@/components/elements/Container";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import VerificationBadge from "@/components/main/VerificationBadge";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import RoundedButton from "@/components/elements/RoundedButton";
import IOSSpinner from "@/components/ui/IOSSpinner";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import { usePageTitle } from "@/hooks/usePageTitle";
import { useTranslation } from "react-i18next";
import { formatFullName } from "@/lib/formatFullName";

type NearbyUser = {
  _id: string;
  user_name: string;
  first_name?: string;
  last_name?: string;
  profile_image?: string;
  is_verified?: string;
  verify_badge?: string;
  is_Register?: string | boolean;
  distanceMeters: number;
};

type NearbyGate =
  | "checking"
  | "location_disabled"
  | "permission"
  | "locating"
  | "ready"
  | "error";

const NEARBY_RADIUS_METERS = 5000;
const RADAR_SIZE = 340;
const RING_METERS = [1000, 2000, 3000, 4000, 5000] as const;

function formatDistance(meters: number, t: (key: string, opts?: object) => string) {
  if (meters < 1000) {
    return t("nearbyFriends.distanceMeters", { count: meters });
  }
  const km = Math.round((meters / 1000) * 10) / 10;
  return t("nearbyFriends.distanceKm", { count: km });
}

/** Place users around the radar: closer = inner ring, angle by index. */
function radarPosition(index: number, total: number, distanceMeters: number) {
  const clamped = Math.min(Math.max(distanceMeters, 120), NEARBY_RADIUS_METERS);
  const ring = 0.18 + (clamped / NEARBY_RADIUS_METERS) * 0.72;
  const angle = ((index / Math.max(total, 1)) * 360 - 90) * (Math.PI / 180);
  const x = 50 + Math.cos(angle) * ring * 50;
  const y = 50 + Math.sin(angle) * ring * 50;
  return { left: `${x}%`, top: `${y}%` };
}

export default function NearbyFriendsPage() {
  const { t } = useTranslation("common");
  usePageTitle(t("nearbyFriends.title"));
  const user = useUser();
  const { request } = useAxios();

  const [gate, setGate] = useState<NearbyGate>("checking");
  const [users, setUsers] = useState<NearbyUser[]>([]);
  const [errorMessage, setErrorMessage] = useState("");
  const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
    null
  );

  const radarUsers = useMemo(() => users.slice(0, 12), [users]);
  const radarActive =
    gate === "locating" || gate === "checking" || gate === "ready";

  const loadNearby = useCallback(
    async (lat: number, lng: number) => {
      setGate("locating");
      setErrorMessage("");
      try {
        const res = await request<{ users?: NearbyUser[] }>(
          "GET",
          `/users/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`,
          null,
          { noToast: true }
        );
        setUsers(res?.users ?? []);
        setCoords({ lat, lng });
        setGate("ready");
      } catch (err: unknown) {
        const response = (
          err as {
            response?: {
              status?: number;
              data?: { code?: string; message?: string };
            };
          }
        )?.response;
        const data = response?.data;
        if (data?.code === "LOCATION_DISABLED") {
          setGate("location_disabled");
          return;
        }
        if (response?.status === 404) {
          setErrorMessage(t("nearbyFriends.apiUnavailable"));
        } else {
          setErrorMessage(data?.message || t("nearbyFriends.loadError"));
        }
        setGate("error");
      }
    },
    [request, t]
  );

  const requestBrowserLocation = useCallback(() => {
    if (!navigator.geolocation) {
      setErrorMessage(t("nearbyFriends.geoUnsupported"));
      setGate("error");
      return;
    }

    setGate("locating");
    setErrorMessage("");

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        void loadNearby(pos.coords.latitude, pos.coords.longitude);
      },
      (err) => {
        if (err.code === err.PERMISSION_DENIED) {
          setGate("permission");
          return;
        }
        setErrorMessage(t("nearbyFriends.geoDenied"));
        setGate("error");
      },
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 15000 }
    );
  }, [loadNearby, t]);

  useEffect(() => {
    if (!user) return;

    if (user.show_location !== true) {
      setGate("location_disabled");
      return;
    }

    requestBrowserLocation();
  }, [user, requestBrowserLocation]);

  return (
    <LocalePageShell>
      <Container className="pb-28">
        <div className="mb-4 flex items-center gap-3 pt-2">
          <Link
            href="/settings/chats"
            className="flex h-9 w-9 items-center justify-center rounded-full bg-neutral-100 dark:bg-neutral-800"
            aria-label={t("nearbyFriends.back")}
          >
            <span className="text-lg leading-none">‹</span>
          </Link>
          <h1 className="text-base font-bold md:text-lg">
            {t("nearbyFriends.title")}
          </h1>
        </div>

        <div className="mb-6 flex flex-col items-center">
          <div
            className="relative overflow-hidden rounded-full border border-[#1f6b2a] shadow-[0_0_40px_rgba(57,255,20,0.18)]"
            style={{
              width: RADAR_SIZE,
              height: RADAR_SIZE,
              background:
                "radial-gradient(circle at center, #0a2e12 0%, #031408 62%, #010805 100%)",
            }}
          >
            {/* scanlines / phosphor grain */}
            <div
              className="pointer-events-none absolute inset-0 opacity-[0.12]"
              style={{
                backgroundImage:
                  "repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.35) 3px)",
              }}
            />

            {/* crosshair */}
            <div className="pointer-events-none absolute left-1/2 top-0 h-full w-px -translate-x-1/2 bg-[#39ff14]/25" />
            <div className="pointer-events-none absolute left-0 top-1/2 h-px w-full -translate-y-1/2 bg-[#39ff14]/25" />

            {/* distance rings + labels */}
            {RING_METERS.map((meters) => {
              const pct = (meters / NEARBY_RADIUS_METERS) * 100;
              const inset = `${(100 - pct) / 2}%`;
              return (
                <div key={meters}>
                  <div
                    className="pointer-events-none absolute rounded-full border border-[#39ff14]/30"
                    style={{ inset }}
                  />
                  <span
                    className="pointer-events-none absolute left-1/2 z-[1] -translate-x-1/2 font-mono text-[9px] text-[#39ff14]/70"
                    style={{
                      top: `calc(${inset} - 1px)`,
                    }}
                  >
                    {meters}
                  </span>
                </div>
              );
            })}

            {/* rotating sweep beam */}
            {radarActive ? (
              <div
                className="nearby-radar-sweep pointer-events-none absolute inset-0"
                aria-hidden
              >
                <div
                  className="absolute inset-0"
                  style={{
                    background:
                      "conic-gradient(from 0deg, rgba(57,255,20,0.55) 0deg, rgba(57,255,20,0.18) 28deg, transparent 55deg, transparent 360deg)",
                  }}
                />
              </div>
            ) : null}

            {/* center = you (exact geometric center) */}
            <div className="absolute left-1/2 top-1/2 z-20 h-12 w-12 -translate-x-1/2 -translate-y-1/2">
              <div className="relative flex h-12 w-12 items-center justify-center rounded-full bg-black ring-2 ring-[#39ff14] shadow-[0_0_14px_rgba(57,255,20,0.65)]">
                {user?.profile_image ? (
                  <ProfileAvatar
                    src={user.profile_image}
                    alt={user.user_name || t("nearbyFriends.you")}
                    size="sm"
                    rounded="full"
                    className="!h-10 !w-10"
                  />
                ) : (
                  <span className="h-3 w-3 rounded-full bg-[#39ff14] shadow-[0_0_8px_#39ff14]" />
                )}
              </div>
              <span className="pointer-events-none absolute left-1/2 top-[calc(100%+4px)] -translate-x-1/2 whitespace-nowrap text-[10px] font-semibold text-[#39ff14]">
                {t("nearbyFriends.you")}
              </span>
            </div>

            {gate === "ready"
              ? radarUsers.map((item, index) => {
                  const pos = radarPosition(
                    index,
                    radarUsers.length,
                    item.distanceMeters
                  );
                  return (
                    <Link
                      key={item._id}
                      href={`/offer/${item._id}`}
                      className="absolute z-10 -translate-x-1/2 -translate-y-1/2 transition-transform active:scale-95"
                      style={pos}
                      title={item.user_name}
                    >
                      <div className="flex flex-col items-center">
                        <div className="nearby-blip-glow relative rounded-full ring-1 ring-[#39ff14]/80">
                          <ProfileAvatar
                            src={item.profile_image}
                            alt={item.user_name}
                            size="sm"
                            rounded="full"
                            className="!h-9 !w-9"
                          />
                          <span className="pointer-events-none absolute -inset-1 rounded-full border border-[#39ff14]/40" />
                        </div>
                        <span
                          className="mt-0.5 max-w-[72px] truncate text-[9px] font-medium text-[#9dff8a]"
                          dir="ltr"
                        >
                          {item.user_name}
                        </span>
                      </div>
                    </Link>
                  );
                })
              : null}
          </div>
          <p className="mt-3 text-center text-xs text-neutral-500">
            {t("nearbyFriends.radiusHint")}
          </p>
        </div>

        {gate === "checking" || gate === "locating" ? (
          <div className="flex flex-col items-center gap-3 py-6">
            <IOSSpinner />
            <p className="text-sm text-neutral-500">
              {gate === "checking"
                ? t("nearbyFriends.checking")
                : t("nearbyFriends.locating")}
            </p>
          </div>
        ) : null}

        {gate === "location_disabled" ? (
          <div className="mx-auto max-w-sm rounded-2xl border border-neutral-200 p-5 text-center dark:border-neutral-800">
            <p className="text-sm font-semibold">
              {t("nearbyFriends.locationOffTitle")}
            </p>
            <p className="mt-2 text-xs text-neutral-500">
              {t("nearbyFriends.locationOffDesc")}
            </p>
            <Link href="/settings/profile/user-settings" className="mt-4 block">
              <RoundedButton variant="primary" className="w-full max-w-none">
                {t("nearbyFriends.openSettings")}
              </RoundedButton>
            </Link>
          </div>
        ) : null}

        {gate === "permission" ? (
          <div className="mx-auto max-w-sm rounded-2xl border border-neutral-200 p-5 text-center dark:border-neutral-800">
            <p className="text-sm font-semibold">
              {t("nearbyFriends.permissionTitle")}
            </p>
            <p className="mt-2 text-xs text-neutral-500">
              {t("nearbyFriends.permissionDesc")}
            </p>
            <RoundedButton
              className="!border-transparent mt-4 h-9 w-full max-w-none !bg-sky-100 text-sky-600"
              onClick={requestBrowserLocation}
            >
              {t("nearbyFriends.retryLocation")}
            </RoundedButton>
          </div>
        ) : null}

        {gate === "error" ? (
          <div className="mx-auto max-w-sm rounded-2xl border border-red-200 p-5 text-center dark:border-red-900">
            <p className="text-sm text-red-600 dark:text-red-400">
              {errorMessage || t("nearbyFriends.loadError")}
            </p>
            <RoundedButton
              className="!border-transparent mt-4 h-9 w-full max-w-none !bg-sky-100 text-sky-600"
              onClick={requestBrowserLocation}
            >
              {t("nearbyFriends.retryLocation")}
            </RoundedButton>
          </div>
        ) : null}

        {gate === "ready" ? (
          <div className="flex flex-col gap-1">
            {coords ? (
              <p className="mb-2 text-center text-[11px] text-neutral-400">
                {t("nearbyFriends.found", { count: users.length })}
              </p>
            ) : null}

            {users.length === 0 ? (
              <p className="py-6 text-center text-sm text-neutral-500">
                {t("nearbyFriends.empty")}
              </p>
            ) : (
              users.map((item) => (
                <Link
                  key={`list-${item._id}`}
                  href={`/offer/${item._id}`}
                  className="flex items-center gap-3 py-3"
                >
                  <ProfileAvatar
                    src={item.profile_image}
                    alt={item.user_name}
                    size="sm"
                    rounded="full"
                    className="!h-12 !w-12 shrink-0"
                  />
                  <div className="min-w-0 flex-1">
                    <div className="flex min-w-0 items-center gap-1">
                      <span className="truncate font-semibold" dir="ltr">
                        {item.user_name}
                      </span>
                      <VerificationBadge verifyBadge={item.verify_badge} />
                    </div>
                    {(item.first_name || item.last_name) && (
                      <p className="truncate text-xs text-neutral-500">
                        {formatFullName(item.first_name, item.last_name)}
                      </p>
                    )}
                    <p className="mt-0.5 text-[11px] text-[#0095f6]">
                      {formatDistance(item.distanceMeters, t)}
                    </p>
                  </div>
                </Link>
              ))
            )}

            <RoundedButton
              className="!border-transparent mx-auto mt-4 h-9 w-full max-w-none !bg-neutral-100 text-neutral-600 dark:!bg-neutral-800 dark:text-neutral-300"
              onClick={requestBrowserLocation}
            >
              {t("nearbyFriends.refresh")}
            </RoundedButton>
          </div>
        ) : null}
      </Container>
    </LocalePageShell>
  );
}
