"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "./button";
import { Badge } from "./badge";
import { X } from "lucide-react";
import { parseChildEntity, getEntityApiPath } from "@nextsparkjs/registries/entity-registry.client";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "./popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from "./command";
function SimpleRelationSelect({
  value,
  onChange,
  entityType,
  titleField,
  multiple = false,
  placeholder = "Seleccionar...",
  disabled = false,
  parentId,
  propField,
  usePropertyMode = false,
  propertyOptions = [],
  userFiltered = false,
  teamId
}) {
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const [propertyOptionsState, setPropertyOptionsState] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [selectedOptions, setSelectedOptions] = React.useState([]);
  const [selectedPropertyValues, setSelectedPropertyValues] = React.useState([]);
  const loadedIdsRef = React.useRef([]);
  const lastSelectedPropertyValuesRef = React.useRef("");
  const lastParentIdRef = React.useRef("");
  React.useEffect(() => {
    const childInfo = parseChildEntity(entityType);
    if (childInfo.isChild && lastParentIdRef.current !== "" && lastParentIdRef.current !== parentId) {
      setOptions([]);
      setSelectedOptions([]);
      if (multiple) {
        onChange([]);
      } else {
        onChange("");
      }
    }
    lastParentIdRef.current = parentId || "";
  }, [parentId, entityType, multiple, onChange]);
  const selectedValues = React.useMemo(() => {
    if (!value) return [];
    return Array.isArray(value) ? value : [value];
  }, [value]);
  const loadOptions = React.useCallback(async () => {
    if (loading) return;
    setLoading(true);
    try {
      if (usePropertyMode && propField) {
        if (parentId) {
          const apiPath = getEntityApiPath(entityType);
          const hasSpecificAPI = apiPath !== null;
          let url;
          if (hasSpecificAPI) {
            url = new URL(`/api/v1/${apiPath}`, window.location.origin);
            url.searchParams.set("fields", propField);
            url.searchParams.set("distinct", "true");
            url.searchParams.set("parentId", parentId);
            url.searchParams.set("limit", "50");
          } else {
            console.warn(`No specific API available for entity type: ${entityType}`);
            return [];
          }
          const response = await fetch(url.toString(), {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              ...teamId && { "x-team-id": teamId }
            },
            credentials: "include"
          });
          if (response.ok) {
            const result = await response.json();
            const fetchedOptions = result.success ? result.data : [];
            setPropertyOptionsState(fetchedOptions);
          } else {
            console.error(`[SimpleRelationSelect] API Error:`, response.status, response.statusText);
          }
        } else {
          setPropertyOptionsState([]);
        }
      } else {
        let url;
        const childInfo = parseChildEntity(entityType);
        if (childInfo.isChild && childInfo.parentEntity && childInfo.childType && parentId) {
          const parentApiPath = getEntityApiPath(childInfo.parentEntity);
          if (parentApiPath) {
            url = new URL(`/api/v1/${parentApiPath}/${parentId}/child/${childInfo.childType}`, window.location.origin);
          } else {
            console.warn(`No API path found for parent entity: ${childInfo.parentEntity}`);
            return [];
          }
        } else {
          const apiPath = getEntityApiPath(entityType);
          const hasSpecificAPI = apiPath !== null;
          if (hasSpecificAPI) {
            url = new URL(`/api/v1/${apiPath}`, window.location.origin);
            url.searchParams.set("limit", "20");
            if (parentId) {
              url.searchParams.set("parentId", parentId);
            }
            if (userFiltered) {
              url.searchParams.set("userFiltered", "true");
            }
          } else {
            console.warn(`No specific API available for entity type: ${entityType}`);
            return [];
          }
        }
        const response = await fetch(url.toString(), {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            ...teamId && { "x-team-id": teamId }
          },
          credentials: "include"
        });
        if (response.ok) {
          const result = await response.json();
          if (result.success && Array.isArray(result.data)) {
            const transformedData = result.data.map((item) => ({
              id: String(item.id || ""),
              title: String(item[titleField || "name"] || item.name || item.title || item.id || ""),
              subtitle: String(item.industry || item.description || ""),
              entityType
            }));
            setOptions(transformedData);
          } else {
            setOptions([]);
          }
        }
      }
    } catch (error) {
      console.error(`Error loading options for ${entityType}:`, error);
    } finally {
      setLoading(false);
    }
  }, [entityType, parentId, titleField, propField, usePropertyMode, userFiltered, loading, teamId]);
  React.useEffect(() => {
    const childInfo = parseChildEntity(entityType);
    if (childInfo.isChild && parentId && options.length === 0 && !loading) {
      loadOptions();
    }
  }, [entityType, parentId, options.length, loading, loadOptions]);
  const loadSelectedOptions = React.useCallback(async (ids) => {
    if (!ids.length) {
      setSelectedOptions([]);
      loadedIdsRef.current = [];
      return;
    }
    const idsString = ids.sort().join(",");
    const loadedIdsString = loadedIdsRef.current.sort().join(",");
    if (idsString === loadedIdsString) {
      return;
    }
    try {
      let url;
      const childInfo = parseChildEntity(entityType);
      if (childInfo.isChild && childInfo.parentEntity && childInfo.childType && parentId) {
        const parentApiPath = getEntityApiPath(childInfo.parentEntity);
        if (parentApiPath) {
          url = new URL(`/api/v1/${parentApiPath}/${parentId}/child/${childInfo.childType}`, window.location.origin);
        } else {
          console.warn(`No API path found for parent entity: ${childInfo.parentEntity}`);
          return;
        }
      } else {
        const apiPath = getEntityApiPath(entityType);
        const hasSpecificAPI = apiPath !== null;
        if (hasSpecificAPI) {
          url = new URL(`/api/v1/${apiPath}`, window.location.origin);
          url.searchParams.set("ids", ids.join(","));
          if (parentId) {
            url.searchParams.set("parentId", parentId);
          }
          if (userFiltered) {
            url.searchParams.set("userFiltered", "true");
          }
        } else {
          console.warn(`No specific API available for entity type: ${entityType}`);
          return;
        }
      }
      const response = await fetch(url.toString(), {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          ...teamId && { "x-team-id": teamId }
        },
        credentials: "include"
      });
      if (response.ok) {
        const data = await response.json();
        if (data.success && Array.isArray(data.data)) {
          const transformedData = data.data.map((item) => ({
            id: String(item.id || ""),
            title: String(item[titleField || "name"] || item.name || item.title || item.id || ""),
            subtitle: String(item.industry || item.description || ""),
            entityType
          }));
          setSelectedOptions(transformedData);
        } else {
          setSelectedOptions([]);
        }
        loadedIdsRef.current = [...ids];
      }
    } catch (error) {
      console.error(`Error loading selected options for ${entityType}:`, error);
      setSelectedOptions([]);
      loadedIdsRef.current = [];
    }
  }, [entityType, parentId, titleField, userFiltered, teamId]);
  const memoizedPropertyOptions = React.useMemo(() => {
    if (!propertyOptions || !Array.isArray(propertyOptions)) return [];
    return propertyOptions;
  }, [propertyOptions]);
  const memoizedPropertyOptionsState = React.useMemo(() => {
    if (!propertyOptionsState || !Array.isArray(propertyOptionsState)) return [];
    return propertyOptionsState;
  }, [propertyOptionsState]);
  React.useEffect(() => {
    if (!usePropertyMode) {
      if (selectedValues.length > 0) {
        loadSelectedOptions(selectedValues);
      } else {
        setSelectedOptions([]);
      }
    }
  }, [selectedValues, loadSelectedOptions, usePropertyMode]);
  React.useEffect(() => {
    if (usePropertyMode && propField && parentId) {
      if (lastParentIdRef.current === parentId) {
        return;
      }
      lastParentIdRef.current = parentId;
      setLoading(true);
      const loadOptionsAsync = async () => {
        try {
          const apiPath = getEntityApiPath(entityType);
          const hasSpecificAPI = apiPath !== null;
          let url;
          if (hasSpecificAPI) {
            url = new URL(`/api/v1/${apiPath}`, window.location.origin);
            url.searchParams.set("fields", propField);
            url.searchParams.set("distinct", "true");
            url.searchParams.set("parentId", parentId);
            url.searchParams.set("limit", "50");
            if (userFiltered) {
              url.searchParams.set("userFiltered", "true");
            }
          } else {
            console.warn(`No specific API available for entity type: ${entityType}`);
            return [];
          }
          const response = await fetch(url.toString(), {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              ...teamId && { "x-team-id": teamId }
            },
            credentials: "include"
          });
          if (response.ok) {
            const result = await response.json();
            const fetchedOptions = result.success ? result.data : [];
            setPropertyOptionsState(fetchedOptions);
          } else {
            console.error(`[SimpleRelationSelect] API Error:`, response.status, response.statusText);
          }
        } catch (error) {
          console.error(`Error loading options for ${entityType}:`, error);
        } finally {
          setLoading(false);
        }
      };
      loadOptionsAsync();
    } else if (usePropertyMode && !parentId) {
      lastParentIdRef.current = "";
      setPropertyOptionsState([]);
    }
  }, [usePropertyMode, propField, parentId, entityType, userFiltered, teamId]);
  React.useEffect(() => {
    if (usePropertyMode) {
      if (selectedValues.length > 0) {
        const selectedPropertyItems = selectedValues.map((val) => {
          const staticOption = memoizedPropertyOptions.find((opt) => opt.value === val);
          if (staticOption) {
            return { value: val, label: staticOption.label };
          }
          const dynamicOption = memoizedPropertyOptionsState.find((opt) => opt.value === val);
          if (dynamicOption) {
            return { value: val, label: dynamicOption.label };
          }
          return { value: val, label: val };
        });
        const newValuesString = selectedPropertyItems.map((v) => `${v.value}:${v.label}`).sort().join(",");
        if (lastSelectedPropertyValuesRef.current !== newValuesString) {
          setSelectedPropertyValues(selectedPropertyItems);
          lastSelectedPropertyValuesRef.current = newValuesString;
        }
      } else if (lastSelectedPropertyValuesRef.current !== "") {
        setSelectedPropertyValues([]);
        lastSelectedPropertyValuesRef.current = "";
      }
    }
  }, [selectedValues, usePropertyMode, memoizedPropertyOptions, memoizedPropertyOptionsState]);
  const handleSelect = (optionId) => {
    const selectedOption = options.find((opt) => opt.id === optionId);
    if (multiple) {
      const newValues = selectedValues.includes(optionId) ? selectedValues.filter((id) => id !== optionId) : [...selectedValues, optionId];
      onChange(newValues.length > 0 ? newValues : null);
      if (selectedOption) {
        if (selectedValues.includes(optionId)) {
          setSelectedOptions((prev) => prev.filter((opt) => opt.id !== optionId));
        } else {
          setSelectedOptions((prev) => [...prev.filter((opt) => opt.id !== optionId), selectedOption]);
        }
      }
    } else {
      onChange(selectedValues.includes(optionId) ? null : optionId);
      setOpen(false);
      if (selectedOption && !selectedValues.includes(optionId)) {
        setSelectedOptions([selectedOption]);
      } else if (selectedValues.includes(optionId)) {
        setSelectedOptions([]);
      }
    }
  };
  const handleRemove = (optionId) => {
    if (multiple) {
      const newValues = selectedValues.filter((id) => id !== optionId);
      onChange(newValues.length > 0 ? newValues : null);
      setSelectedOptions((prev) => prev.filter((opt) => opt.id !== optionId));
    } else {
      onChange(null);
      setSelectedOptions([]);
    }
  };
  const handlePropertySelect = (propertyValue) => {
    if (multiple) {
      const newValues = selectedValues.includes(propertyValue) ? selectedValues.filter((val) => val !== propertyValue) : [...selectedValues, propertyValue];
      onChange(newValues.length > 0 ? newValues : null);
    } else {
      onChange(selectedValues.includes(propertyValue) ? null : propertyValue);
      setOpen(false);
    }
  };
  const handlePropertyRemove = (propertyValue) => {
    if (multiple) {
      const newValues = selectedValues.filter((val) => val !== propertyValue);
      onChange(newValues.length > 0 ? newValues : null);
    } else {
      onChange(null);
    }
  };
  const getDisplayText = () => {
    if (selectedValues.length === 0) {
      return placeholder;
    }
    if (usePropertyMode) {
      if (multiple) {
        if (selectedPropertyValues.length > 0) {
          return selectedPropertyValues.map((opt) => opt.label).join(", ");
        }
        return `${selectedValues.length} seleccionado${selectedValues.length !== 1 ? "s" : ""}`;
      }
      const selectedPropertyItem = selectedPropertyValues.find((item) => item.value === selectedValues[0]);
      return selectedPropertyItem ? selectedPropertyItem.label : selectedValues[0];
    } else {
      if (multiple) {
        if (selectedOptions.length > 0) {
          return selectedOptions.map((opt) => opt.title).join(", ");
        }
        return `${selectedValues.length} seleccionado${selectedValues.length !== 1 ? "s" : ""}`;
      }
      const selectedOption = selectedOptions.find((opt) => opt.id === selectedValues[0]);
      return selectedOption ? selectedOption.title : selectedValues[0];
    }
  };
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
      Button,
      {
        variant: "outline",
        role: "combobox",
        "aria-expanded": open,
        className: "w-full justify-between",
        disabled,
        onClick: () => {
          if (!open) {
            if (usePropertyMode && parentId) {
              loadOptions();
            } else if (!usePropertyMode && options.length === 0) {
              loadOptions();
            }
          }
        },
        children: /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1 flex-1", children: multiple && selectedValues.length > 0 ? selectedValues.map((value2) => {
          let displayText = value2;
          if (usePropertyMode) {
            const propertyItem = selectedPropertyValues.find((item) => item.value === value2);
            displayText = propertyItem ? propertyItem.label : value2;
          } else {
            const selectedOption = selectedOptions.find((opt) => opt.id === value2);
            displayText = selectedOption ? selectedOption.title : value2;
          }
          return /* @__PURE__ */ jsxs(
            Badge,
            {
              variant: "secondary",
              className: "text-xs",
              children: [
                displayText,
                /* @__PURE__ */ jsx(
                  X,
                  {
                    className: "ml-1 h-3 w-3 cursor-pointer",
                    onClick: (e) => {
                      e.stopPropagation();
                      if (usePropertyMode) {
                        handlePropertyRemove(value2);
                      } else {
                        handleRemove(value2);
                      }
                    }
                  }
                )
              ]
            },
            value2
          );
        }) : /* @__PURE__ */ jsx("span", { className: selectedValues.length === 0 ? "text-muted-foreground" : "", children: getDisplayText() }) })
      }
    ) }),
    /* @__PURE__ */ jsx(PopoverContent, { className: "w-full p-0", children: /* @__PURE__ */ jsxs(Command, { children: [
      /* @__PURE__ */ jsx(CommandInput, { placeholder: "Buscar..." }),
      /* @__PURE__ */ jsxs(CommandList, { children: [
        /* @__PURE__ */ jsx(CommandEmpty, { children: loading ? "Cargando..." : "No se encontraron opciones." }),
        /* @__PURE__ */ jsx(CommandGroup, { children: usePropertyMode ? (
          // Render property options - combine static and dynamic options
          (() => {
            let allPropertyOptions = [];
            if (memoizedPropertyOptionsState.length > 0 && parentId) {
              allPropertyOptions = memoizedPropertyOptionsState.map((dynOpt) => {
                const staticOption = memoizedPropertyOptions.find((statOpt) => statOpt.value === dynOpt.value);
                return {
                  value: dynOpt.value,
                  label: staticOption ? staticOption.label : dynOpt.label,
                  isStatic: Boolean(staticOption)
                };
              });
            } else {
              allPropertyOptions = memoizedPropertyOptions.map((opt) => ({
                value: opt.value,
                label: opt.label,
                isStatic: true
              }));
            }
            return allPropertyOptions.map((option) => /* @__PURE__ */ jsx(
              CommandItem,
              {
                value: option.value,
                onSelect: () => handlePropertySelect(option.value),
                children: /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2 w-full", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
                    /* @__PURE__ */ jsx("div", { className: "font-medium", children: option.label }),
                    !option.isStatic && /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: "Din\xE1mico" })
                  ] }),
                  selectedValues.includes(option.value) && /* @__PURE__ */ jsx("div", { className: "text-primary", children: "\u2713" })
                ] })
              },
              option.value
            ));
          })()
        ) : (
          // Render regular entity options
          options.map((option) => /* @__PURE__ */ jsx(
            CommandItem,
            {
              value: option.id,
              onSelect: () => handleSelect(option.id),
              children: /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2 w-full", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
                  /* @__PURE__ */ jsx("div", { className: "font-medium", children: option.title }),
                  option.subtitle && /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: option.subtitle })
                ] }),
                selectedValues.includes(option.id) && /* @__PURE__ */ jsx("div", { className: "text-primary", children: "\u2713" })
              ] })
            },
            option.id
          ))
        ) })
      ] })
    ] }) })
  ] });
}
export {
  SimpleRelationSelect
};
