"use client";

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { getAgentTree } from "@/api/admin-agents";
import { flattenAgentTree, type FlatAgentOption } from "@/lib/admin-agent-tree";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useAdminProfile } from "@/stores/admin-session";

const ALL = "__all__";

type Props = {
  id?: string;
  value: number | undefined;
  onChange: (agentNodeId: number | undefined) => void;
  className?: string;
};

export function AdminAgentFilter({ id = "admin-agent-filter", value, onChange, className }: Props) {
  const { t } = useTranslation("common");
  const profile = useAdminProfile();
  const [options, setOptions] = useState<FlatAgentOption[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    getAgentTree(profile?.agent?.admin_site_id)
      .then((data) => {
        if (!cancelled) {
          setOptions(flattenAgentTree(data.tree));
        }
      })
      .catch(() => {
        if (!cancelled) {
          setOptions([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [profile?.agent?.admin_site_id]);

  const selectValue = value ? String(value) : ALL;
  const selectedLabel = options.find((opt) => String(opt.id) === selectValue)?.label;

  return (
    <div className={className}>
      <Label htmlFor={id} className="text-xs text-muted-foreground">
        {t("agentColumns.filter")}
      </Label>
      <Select
        value={selectValue}
        onValueChange={(v) => onChange(v === ALL ? undefined : Number(v))}
        disabled={loading || options.length === 0}
      >
        <SelectTrigger id={id} className="mt-1 h-9 w-full min-w-[10rem]">
          <SelectValue>
            {(raw) => {
              const current = String(raw ?? ALL);
              if (current === ALL) {
                return t("agentColumns.filterAll");
              }
              return selectedLabel ?? t("agentColumns.filterAll");
            }}
          </SelectValue>
        </SelectTrigger>
        <SelectContent>
          <SelectItem value={ALL}>{t("agentColumns.filterAll")}</SelectItem>
          {options.map((opt) => (
            <SelectItem key={opt.id} value={String(opt.id)}>
              {opt.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
}
