"use client";

import { useEffect, useState } from "react";
import { Layers } from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useActiveTenant } from "../context/active-tenant-context";
import { ALL_UNITS_SCOPE } from "../types/tenancy";
import { fetchOrgUnits } from "../api/access-api";

export function UnitScopeSelector() {
  const { organizationKey, unitScope, unitLabel, setUnitScope, loading } = useActiveTenant();
  const [units, setUnits] = useState<Array<{ _id: string; name: string }>>([]);

  useEffect(() => {
    if (!organizationKey) {
      setUnits([]);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const rows = await fetchOrgUnits(organizationKey);
        if (!cancelled) setUnits(rows);
      } catch {
        if (!cancelled) setUnits([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [organizationKey]);

  if (loading || !organizationKey || units.length <= 1) return null;

  return (
    <Select
      value={unitScope || ALL_UNITS_SCOPE}
      onValueChange={(v) => setUnitScope(v)}
    >
      <SelectTrigger className="h-8 w-[160px] gap-1 text-xs">
        <Layers className="size-3.5 shrink-0 opacity-60" />
        <SelectValue placeholder={`All ${unitLabel}s`} />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value={ALL_UNITS_SCOPE}>All {unitLabel}s</SelectItem>
        {units.map((u) => (
          <SelectItem key={u._id} value={u._id}>
            {u.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
