"use client";
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useCallback, useMemo } from 'react';
import { Button } from '../../button.mjs';
import { Input } from '../../input.mjs';
import { Label } from '../../label.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../select.mjs';
import { Card, CardHeader, CardTitle, CardContent } from '../../card.mjs';
import { Plus, Check, X, Edit2, Trash2 } from 'lucide-react';
import { useLayerStore } from '../../../lib/ui-builder/store/layer-store.mjs';
import { cn } from '../../../lib/utils.mjs';
import { useEditorStore } from '../../../lib/ui-builder/store/editor-store.mjs';

const EMPTY_OBJECT = {};
const VariablesPanel = ({
  className
}) => {
  const { variables, addVariable, updateVariable, removeVariable } = useLayerStore();
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const incrementRevision = useEditorStore((state) => state.incrementRevision);
  const allowVariableEditing = useEditorStore((state) => state.allowVariableEditing);
  const functionRegistry = useEditorStore((state) => state.functionRegistry);
  const handleAddVariable = useCallback(
    (name, type, defaultValue) => {
      addVariable(name, type, defaultValue);
      incrementRevision();
    },
    [addVariable, incrementRevision]
  );
  const handleSetIsAdding = useCallback(() => {
    setIsAdding(true);
  }, []);
  const handleSetIsNotAdding = useCallback(() => {
    setIsAdding(false);
  }, []);
  const handleOnSave = useCallback(
    (id, updates) => {
      updateVariable(id, updates);
      setEditingId(null);
    },
    [updateVariable]
  );
  const handleOnCancel = useCallback(() => {
    setEditingId(null);
  }, []);
  const handleOnDelete = useCallback(
    (id) => {
      removeVariable(id);
      incrementRevision();
    },
    [removeVariable, incrementRevision]
  );
  return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-4 p-4", className), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold", children: "Variables" }),
      allowVariableEditing && /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: handleSetIsAdding, disabled: isAdding, children: [
        /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-2" }),
        "Add Variable"
      ] })
    ] }),
    isAdding && allowVariableEditing && /* @__PURE__ */ jsx(
      AddVariableForm,
      {
        onSave: handleAddVariable,
        onCancel: handleSetIsNotAdding,
        functionRegistry
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "space-y-2", children: variables.map((variable) => /* @__PURE__ */ jsx(
      VariableCard,
      {
        variable,
        isEditing: editingId === variable.id,
        onEdit: setEditingId,
        onSave: handleOnSave,
        onCancel: handleOnCancel,
        onDelete: handleOnDelete,
        editVariables: allowVariableEditing,
        functionRegistry
      },
      variable.id
    )) }),
    variables.length === 0 && !isAdding && /* @__PURE__ */ jsx("div", { className: "text-center text-muted-foreground py-8", children: allowVariableEditing ? 'No variables defined. Click "Add Variable" to create one.' : "No variables defined." })
  ] });
};
const AddVariableForm = ({
  onSave,
  onCancel,
  functionRegistry
}) => {
  const [name, setName] = useState("");
  const [type, setType] = useState("string");
  const [defaultValue, setDefaultValue] = useState("");
  const [errors, setErrors] = useState(EMPTY_OBJECT);
  const functionOptions = useMemo(() => {
    if (!functionRegistry) return [];
    return Object.entries(functionRegistry).map(([id, def]) => ({
      id,
      name: def.name,
      description: def.description
    }));
  }, [functionRegistry]);
  const hasFunctions = functionOptions.length > 0;
  const validateForm = useCallback(() => {
    const newErrors = {};
    if (!name.trim()) {
      newErrors.name = "Name is required";
    }
    if (type === "function") {
      if (!defaultValue) {
        newErrors.defaultValue = "Please select a function";
      }
    } else if (!defaultValue.trim()) {
      newErrors.defaultValue = "Preview value is required";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [name, defaultValue, type]);
  const handleSave = useCallback(() => {
    if (!validateForm()) return;
    let parsedValue = defaultValue;
    try {
      if (type === "number") {
        parsedValue = parseFloat(defaultValue) || 0;
      } else if (type === "boolean") {
        parsedValue = defaultValue.toLowerCase() === "true";
      }
    } catch (e) {
      console.warn("Error parsing variable value, keeping as string", e);
    }
    onSave(name, type, parsedValue);
  }, [name, type, defaultValue, onSave, validateForm]);
  const handleNameChange = useCallback(
    (e) => {
      setName(e.target.value);
      if (errors.name) setErrors((prev) => ({ ...prev, name: void 0 }));
    },
    [errors.name]
  );
  const handleTypeChange = useCallback(
    (value) => {
      setType(value);
      setDefaultValue("");
    },
    []
  );
  const handleDefaultValueChange = useCallback(
    (e) => {
      setDefaultValue(e.target.value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleFunctionSelect = useCallback(
    (value) => {
      setDefaultValue(value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  return /* @__PURE__ */ jsxs(Card, { children: [
    /* @__PURE__ */ jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "Add New Variable" }) }),
    /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: "var-name", children: [
          "Name ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "var-name",
            value: name,
            onChange: handleNameChange,
            placeholder: "variableName",
            className: errors.name ? "border-red-500" : ""
          }
        ),
        errors.name && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.name })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "var-type", children: "Type" }),
        /* @__PURE__ */ jsxs(Select, { value: type, onValueChange: handleTypeChange, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
          /* @__PURE__ */ jsxs(SelectContent, { children: [
            /* @__PURE__ */ jsx(SelectItem, { value: "string", children: "String" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "number", children: "Number" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "boolean", children: "Boolean" }),
            hasFunctions && /* @__PURE__ */ jsx(SelectItem, { value: "function", children: "Function" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { children: type === "function" ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: "var-function", children: [
          "Function ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxs(Select, { value: defaultValue, onValueChange: handleFunctionSelect, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { className: errors.defaultValue ? "border-red-500" : "", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select a function..." }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: functionOptions.map((fn) => /* @__PURE__ */ jsx(SelectItem, { value: fn.id, children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsx("span", { children: fn.name }),
            fn.description && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: fn.description })
          ] }) }, fn.id)) })
        ] }),
        errors.defaultValue && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: "var-default", children: [
          "Preview Value ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "var-default",
            value: defaultValue,
            onChange: handleDefaultValueChange,
            placeholder: getPlaceholderForType(type),
            className: errors.defaultValue ? "border-red-500" : ""
          }
        ),
        errors.defaultValue && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: handleSave, children: [
          /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 mr-2" }),
          "Save"
        ] }),
        /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: onCancel, children: [
          /* @__PURE__ */ jsx(X, { className: "h-4 w-4 mr-2" }),
          "Cancel"
        ] })
      ] })
    ] })
  ] });
};
const VariableCard = ({
  variable,
  isEditing,
  onEdit,
  onSave,
  onCancel,
  onDelete,
  editVariables,
  functionRegistry
}) => {
  const [name, setName] = useState(variable.name);
  const [type, setType] = useState(variable.type);
  const [defaultValue, setDefaultValue] = useState(
    String(variable.defaultValue)
  );
  const [errors, setErrors] = useState(EMPTY_OBJECT);
  const functionOptions = useMemo(() => {
    if (!functionRegistry) return [];
    return Object.entries(functionRegistry).map(([id, def]) => ({
      id,
      name: def.name,
      description: def.description
    }));
  }, [functionRegistry]);
  const hasFunctions = functionOptions.length > 0;
  const getFunctionDisplayName = useCallback((funcId) => {
    if (!functionRegistry) return funcId;
    const fn = functionRegistry[funcId];
    return fn ? fn.name : funcId;
  }, [functionRegistry]);
  const validateForm = useCallback(() => {
    const newErrors = {};
    if (!name.trim()) {
      newErrors.name = "Name is required";
    }
    if (type === "function") {
      if (!defaultValue) {
        newErrors.defaultValue = "Please select a function";
      }
    } else if (!defaultValue.trim()) {
      newErrors.defaultValue = "Preview value is required";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [name, defaultValue, type]);
  const handleSave = useCallback(() => {
    if (!validateForm()) return;
    let parsedValue = defaultValue;
    try {
      if (type === "number") {
        parsedValue = parseFloat(defaultValue) || 0;
      } else if (type === "boolean") {
        parsedValue = defaultValue.toLowerCase() === "true";
      }
    } catch (e) {
      console.warn("Error parsing variable value, keeping as string", e);
    }
    onSave(variable.id, { name, type, defaultValue: parsedValue });
  }, [name, type, defaultValue, onSave, validateForm, variable.id]);
  const handleNameChange = useCallback(
    (e) => {
      setName(e.target.value);
      if (errors.name) setErrors((prev) => ({ ...prev, name: void 0 }));
    },
    [errors.name]
  );
  const handleTypeChange = useCallback(
    (value) => {
      setType(value);
      setDefaultValue("");
    },
    []
  );
  const handleDefaultValueChange = useCallback(
    (e) => {
      setDefaultValue(e.target.value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleFunctionSelect = useCallback(
    (value) => {
      setDefaultValue(value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleOnEdit = useCallback(() => {
    onEdit(variable.id);
  }, [onEdit, variable.id]);
  const handleOnDelete = useCallback(() => {
    onDelete(variable.id);
  }, [onDelete, variable.id]);
  if (isEditing) {
    return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "pt-4 space-y-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: `edit-name-${variable.id}`, children: [
          "Name ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: `edit-name-${variable.id}`,
            value: name,
            onChange: handleNameChange,
            className: errors.name ? "border-red-500" : ""
          }
        ),
        errors.name && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.name })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: `edit-type-${variable.id}`, children: "Type" }),
        /* @__PURE__ */ jsxs(Select, { value: type, onValueChange: handleTypeChange, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
          /* @__PURE__ */ jsxs(SelectContent, { children: [
            /* @__PURE__ */ jsx(SelectItem, { value: "string", children: "String" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "number", children: "Number" }),
            /* @__PURE__ */ jsx(SelectItem, { value: "boolean", children: "Boolean" }),
            hasFunctions && /* @__PURE__ */ jsx(SelectItem, { value: "function", children: "Function" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { children: type === "function" ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: `edit-function-${variable.id}`, children: [
          "Function ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxs(Select, { value: defaultValue, onValueChange: handleFunctionSelect, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { className: errors.defaultValue ? "border-red-500" : "", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select a function..." }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: functionOptions.map((fn) => /* @__PURE__ */ jsx(SelectItem, { value: fn.id, children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsx("span", { children: fn.name }),
            fn.description && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: fn.description })
          ] }) }, fn.id)) })
        ] }),
        errors.defaultValue && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: `edit-default-${variable.id}`, children: [
          "Preview Value ",
          /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: `edit-default-${variable.id}`,
            value: defaultValue,
            onChange: handleDefaultValueChange,
            placeholder: getPlaceholderForType(type),
            className: errors.defaultValue ? "border-red-500" : ""
          }
        ),
        errors.defaultValue && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: handleSave, children: [
          /* @__PURE__ */ jsx(Check, { className: "h-4 w-4 mr-2" }),
          "Save"
        ] }),
        /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: onCancel, children: [
          /* @__PURE__ */ jsx(X, { className: "h-4 w-4 mr-2" }),
          "Cancel"
        ] })
      ] })
    ] }) });
  }
  return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(CardContent, { className: "pt-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: variable.name }),
        /* @__PURE__ */ jsx("span", { className: "text-xs bg-muted px-2 py-1 rounded", children: variable.type })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground mt-1", children: variable.type === "function" ? getFunctionDisplayName(String(variable.defaultValue)) : String(variable.defaultValue) })
    ] }),
    editVariables && /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
      /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: handleOnEdit, children: /* @__PURE__ */ jsx(Edit2, { className: "h-4 w-4" }) }),
      /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: handleOnDelete, children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }) })
    ] })
  ] }) }) });
};
function getPlaceholderForType(type) {
  switch (type) {
    case "string":
      return "Enter text...";
    case "number":
      return "0";
    case "boolean":
      return "true";
    case "function":
      return "Select a function...";
    default:
      return "";
  }
}

export { VariablesPanel };
