"use client";

import axios from "axios";
import { Building2, Check, ChevronDown, Loader2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";

import { Button } from "@/components/ui/button";
import { useAppToast } from "@/components/hooks/use-app-toast";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { getApiBaseUrl } from "@/lib/api";
import { listResidences } from "@/lib/residences-api";
import { patchUserMeResidence } from "@/lib/user-api";
import { useResidenceStore } from "@/stores/residence-store";
import { useUserStore } from "@/stores/user-store";
import type { Residence } from "@/types/residence";

function apiErrorMessage(err: unknown): string {
  if (axios.isAxiosError(err)) {
    const d = err.response?.data as { message?: string } | undefined;
    if (d?.message) return d.message;
    if (err.message) return err.message;
  }
  if (err instanceof Error) return err.message;
  return "Impossible de charger les résidences.";
}

export function AdminResidenceSwitcher() {
  const notify = useAppToast();
  const [mounted, setMounted] = useState(false);
  const [list, setList] = useState<Residence[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [switching, setSwitching] = useState(false);

  const selectedId = useResidenceStore((s) => s.selectedId);
  const setSelectedId = useResidenceStore((s) => s.setSelectedId);

  const residenceIdFromUser = useUserStore(
    (s) => s.user?.residence_id ?? null
  );
  const setResidenceIdOnUser = useUserStore((s) => s.setResidenceId);

  const baseConfigured = Boolean(getApiBaseUrl());

  const loadList = useCallback(async () => {
    if (!baseConfigured) {
      setList([]);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await listResidences();
      setList(data);
    } catch (e) {
      setError(apiErrorMessage(e));
      setList([]);
    } finally {
      setLoading(false);
    }
  }, [baseConfigured]);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted || !baseConfigured) return;
    loadList();
  }, [mounted, baseConfigured, loadList]);

  useEffect(() => {
    if (!mounted || loading || list.length === 0) return;

    const rid = residenceIdFromUser;
    if (rid !== undefined && rid !== null && rid !== "") {
      const inList = list.some((r) => String(r.id) === String(rid));
      if (inList && String(selectedId) !== String(rid)) {
        setSelectedId(String(rid));
        return;
      }
      if (inList) return;
    }

    const exists = list.some((r) => String(r.id) === String(selectedId));
    if (!selectedId || !exists) {
      setSelectedId(String(list[0].id));
    }
  }, [
    mounted,
    loading,
    list,
    selectedId,
    setSelectedId,
    residenceIdFromUser,
  ]);

  const selected = useMemo(() => {
    if (list.length === 0) return null;
    return (
      list.find((r) => String(r.id) === String(selectedId)) ?? list[0] ?? null
    );
  }, [list, selectedId]);

  const effectiveId = selectedId;

  if (!mounted) {
    return (
      <Button
        variant="ghost"
        disabled
        className="h-9 max-w-[min(100vw-8rem,320px)] justify-between gap-2 rounded-full border border-border/60 bg-muted/60 px-3 font-normal"
      >
        <Building2 className="h-3.5 w-3.5 shrink-0 text-primary/60" aria-hidden />
        <span className="text-muted-foreground text-sm">…</span>
        <ChevronDown className="h-3.5 w-3.5 shrink-0 opacity-40" aria-hidden />
      </Button>
    );
  }

  if (!baseConfigured) {
    return (
      <Button
        variant="ghost"
        disabled
        title="Définir NEXT_PUBLIC_APP_API_URL dans .env.local"
        className="h-9 max-w-[min(100vw-8rem,320px)] cursor-not-allowed gap-2 rounded-full border border-dashed border-amber-500/50 bg-amber-500/5 px-3 text-xs text-amber-950 dark:text-amber-100"
      >
        <Building2 className="h-3.5 w-3.5 shrink-0" aria-hidden />
        <span className="truncate">API non configurée</span>
      </Button>
    );
  }

  if (loading && list.length === 0) {
    return (
      <Button
        variant="ghost"
        disabled
        className="h-9 max-w-[min(100vw-8rem,320px)] justify-between gap-2 rounded-full border border-border/60 bg-muted/60 px-3 font-normal"
      >
        <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-primary/60" aria-hidden />
        <span className="text-sm text-muted-foreground">Chargement…</span>
      </Button>
    );
  }

  if (error && list.length === 0) {
    return (
      <Button
        variant="ghost"
        type="button"
        onClick={() => loadList()}
        className="h-auto max-w-[min(100vw-8rem,320px)] flex-col items-stretch gap-1 rounded-xl border border-destructive/40 bg-destructive/5 px-3 py-2 text-left text-xs text-destructive hover:bg-destructive/10"
        title={error}
      >
        <span className="flex items-center gap-2 font-medium">
          <Building2 className="h-3.5 w-3.5 shrink-0" aria-hidden />
          Erreur API
        </span>
        <span className="line-clamp-2 font-normal opacity-90">{error}</span>
        <span className="text-[10px] font-medium text-primary">Cliquer pour réessayer</span>
      </Button>
    );
  }

  if (list.length === 0) {
    return (
      <Button variant="ghost" disabled className="h-9 gap-2 rounded-full border border-border/60 bg-muted/60 px-3 font-normal">
        <Building2 className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
        <span className="text-sm text-muted-foreground">Aucune résidence</span>
      </Button>
    );
  }

  if (!selected) {
    return null;
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          className="h-9 max-w-[min(100vw-8rem,320px)] justify-between gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 font-normal text-foreground hover:bg-primary/10 hover:border-primary/30 transition-colors"
          aria-label="Changer de résidence"
          disabled={loading || switching}
        >
          {loading || switching ? (
            <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-primary/70" aria-hidden />
          ) : (
            <Building2
              className="h-3.5 w-3.5 shrink-0 text-primary/70"
              aria-hidden
            />
          )}
          <span className="min-w-0 flex-1 truncate text-left text-sm font-semibold text-foreground">
            {selected.nom}
          </span>
          <ChevronDown
            className="h-3.5 w-3.5 shrink-0 text-primary/60"
            aria-hidden
          />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="max-h-[min(70vh,24rem)] w-[min(calc(100vw-2rem),320px)] overflow-y-auto">
        <DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
          Changer de résidence
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        {list.map((r) => (
          <DropdownMenuItem
            key={String(r.id)}
            className="cursor-pointer gap-2 group"
            disabled={switching}
            onSelect={() => {
              const id = String(r.id);
              if (id === String(effectiveId)) return;
              void (async () => {
                setSwitching(true);
                try {
                  await patchUserMeResidence(r.id);
                  setSelectedId(id);
                  setResidenceIdOnUser(r.id);
                  notify.success({
                    title: "Résidence enregistrée",
                    description: r.nom,
                  });
                  if (typeof window !== "undefined") {
                    window.location.reload();
                  }
                } catch (err) {
                  notify.error({
                    title: "Échec du changement de résidence",
                    description: apiErrorMessage(err),
                  });
                  setSwitching(false);
                }
              })();
            }}
          >
            <span className="flex h-4 w-4 shrink-0 items-center justify-center">
              {String(r.id) === String(effectiveId) ? (
                <Check className="h-4 w-4 text-primary group-hover:text-white" aria-hidden />
              ) : null}
            </span>
            <span className="min-w-0 flex-1 truncate group-hover:text-white">{r.nom}</span>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
