import * as api from "@client/api";
import { useSettings } from "@client/hooks/useSettings";
import { queryKeys } from "@client/lib/queryKeys";
import type { SearchProfile } from "@shared/types";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import type React from "react";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

/**
 * Search profile strip on the Jobs page: quick link to Settings, or inline
 * switch when you have more than one profile for this login.
 */
export const ProfileQuickSwitch: React.FC = () => {
  const queryClient = useQueryClient();
  const { settings, refreshSettings } = useSettings();

  const { data: profiles = [], isLoading } = useQuery<SearchProfile[]>({
    queryKey: queryKeys.searchProfiles.list(),
    queryFn: api.listProfiles,
    select: (rows) => {
      const seen = new Set<string>();
      return rows.filter((profile) => {
        if (seen.has(profile.id)) return false;
        seen.add(profile.id);
        return true;
      });
    },
  });

  const [selectedId, setSelectedId] = useState<string | null>(null);

  const activeId = useMemo(() => {
    if (selectedId && profiles.some((profile) => profile.id === selectedId)) {
      return selectedId;
    }
    const sid = settings?.activeProfileId?.trim() ?? "";
    if (sid && profiles.some((profile) => profile.id === sid)) return sid;
    return profiles[0]?.id ?? "";
  }, [selectedId, settings?.activeProfileId, profiles]);

  useEffect(() => {
    const sid = settings?.activeProfileId?.trim() ?? "";
    if (sid && profiles.some((profile) => profile.id === sid)) {
      setSelectedId(sid);
    }
  }, [settings?.activeProfileId, profiles]);

  const activateMutation = useMutation({
    mutationFn: (id: string) => api.activateProfile(id),
    onSuccess: async (_data, profileId) => {
      setSelectedId(profileId);
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: queryKeys.jobs.all }),
        queryClient.invalidateQueries({ queryKey: queryKeys.profile.all }),
        queryClient.invalidateQueries({
          queryKey: queryKeys.searchProfiles.all,
        }),
      ]);
      await refreshSettings();
      const profileName =
        profiles.find((profile) => profile.id === profileId)?.name ??
        "Search profile";
      toast.success(`${profileName} active`);
    },
    onError: (err: unknown) => {
      const message =
        err instanceof Error ? err.message : "Failed to activate profile";
      toast.error(message);
    },
  });

  if (isLoading && profiles.length === 0) {
    return (
      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
        Profiles…
      </div>
    );
  }

  if (profiles.length === 0) return null;

  if (profiles.length === 1) {
    const p = profiles[0] as SearchProfile;
    return (
      <div className="flex flex-wrap items-center gap-2 rounded-lg border border-border/60 bg-muted/15 px-3 py-2 text-xs">
        <span className="text-muted-foreground">Search profile</span>
        <span className="font-medium text-foreground">{p.name}</span>
        <Button variant="link" className="h-auto p-0 text-xs" asChild>
          <a href="/settings">Edit in Settings</a>
        </Button>
      </div>
    );
  }

  return (
    <div className="flex flex-wrap items-center gap-2 rounded-lg border border-border/60 bg-muted/15 px-3 py-2">
      <span className="text-xs font-medium text-foreground">
        Search profile
      </span>
      <Select
        value={activeId}
        onValueChange={(id) => {
          if (!id || id === activeId) return;
          activateMutation.mutate(id);
        }}
        disabled={activateMutation.isPending}
      >
        <SelectTrigger className="h-8 w-[min(100%,16rem)] text-xs">
          <SelectValue placeholder="Choose profile" />
        </SelectTrigger>
        <SelectContent>
          {profiles.map((p) => (
            <SelectItem key={p.id} value={p.id} className="text-xs">
              {p.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Button variant="link" className="h-auto p-0 text-xs" asChild>
        <a href="/settings">Open Settings</a>
      </Button>
    </div>
  );
};
