import { u as useForm, j as jsxRuntimeExports, P as PowerhouseButton, r as reactExports, a as useDebounceValue, C as Controller, b as ConnectSelect, I as Icon, M as Modal, t as twMerge, R as Root2, L as List, c as React, T as Trigger, d as Content, e as usePHModal, f as useUser, g as useConnectCrypto, h as useDriveEditorModules, i as closePHModal, k as requestPublicDrive, l as addRemoteDrive, m as toast, n as t, s as setSelectedDrive, o as addDrive } from "./index-DEuI3Aoa.js";
import { L as Label, S as SharingTypeFormInput, A as AvailableOfflineToggle, D as Divider, a as LocationInfo } from "./toggle-OA2woAUh.js";
import { F as FormInput } from "./form-input-DucXwitU.js";
import { D as Disclosure } from "./disclosure-DtNIZI7D.js";
function AddLocalDriveForm(props) {
  const { register, handleSubmit, control, formState: { errors } } = useForm({
    defaultValues: {
      name: "",
      sharingType: "LOCAL",
      availableOffline: false,
      appId: props.appOptions[0].id
    }
  });
  return jsxRuntimeExports.jsx("form", { name: "add-local-drive", onSubmit: handleSubmit(props.onSubmit), className: "flex flex-col gap-4", children: jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-4", children: [jsxRuntimeExports.jsxs("div", { children: [jsxRuntimeExports.jsx(Label, { htmlFor: "name", className: "text-sm font-medium text-gray-800", children: "Drive Name" }), jsxRuntimeExports.jsx(FormInput, { ...register("name", {
    required: "Drive name is required"
  }), errorMessage: errors.name?.message, placeholder: "Drive name" })] }), jsxRuntimeExports.jsxs("div", { children: [jsxRuntimeExports.jsx(Label, { htmlFor: "driveApp", className: "text-sm font-medium text-gray-800", children: "Drive App" }), jsxRuntimeExports.jsx(AppFormInput, { control, appOptions: props.appOptions })] }), jsxRuntimeExports.jsxs("div", { children: [jsxRuntimeExports.jsx(Label, { htmlFor: "sharingType", className: "text-sm font-medium text-gray-800", children: "Location" }), jsxRuntimeExports.jsx(SharingTypeFormInput, { control })] }), jsxRuntimeExports.jsx("div", { children: jsxRuntimeExports.jsx(AvailableOfflineToggle, { ...register("availableOffline") }) }), jsxRuntimeExports.jsx(PowerhouseButton, { className: "mt-2 w-full", type: "submit", children: "Create new drive" })] }) });
}
function AddRemoteDriveForm(props) {
  const { sharingType = "PUBLIC", requestPublicDrive: requestPublicDrive2 } = props;
  const [remoteDriveDetails, setPublicDriveDetails] = reactExports.useState();
  const [showLocationSettings, setShowLocationSettings] = reactExports.useState(false);
  const [isUrlValid, setIsUrlValid] = reactExports.useState(true);
  const [hasConfirmedUrl, setHasConfirmedUrl] = reactExports.useState(false);
  const [errorMessage, setErrorMessage] = reactExports.useState("");
  const [url, setUrl] = reactExports.useState("");
  const [debouncedUrl, setDebouncedUrl] = useDebounceValue(url, 500);
  const { register, handleSubmit, setValue } = useForm({
    mode: "onBlur",
    defaultValues: {
      availableOffline: remoteDriveDetails?.availableOffline ?? false
    }
  });
  reactExports.useEffect(() => {
    setDebouncedUrl(url);
  }, [url]);
  reactExports.useEffect(() => {
    setHasConfirmedUrl(false);
    if (debouncedUrl === "")
      return;
    fetchPublicDrive().catch(console.error);
    async function fetchPublicDrive() {
      try {
        const { id, name } = await requestPublicDrive2(debouncedUrl);
        setPublicDriveDetails({
          id,
          name,
          sharingType,
          location: "SWITCHBOARD",
          availableOffline: true
        });
        setValue("availableOffline", true);
        setIsUrlValid(true);
        setErrorMessage("");
      } catch (error) {
        setPublicDriveDetails(void 0);
        setIsUrlValid(false);
        setErrorMessage(error.message);
      }
    }
  }, [debouncedUrl, setValue, sharingType]);
  function onSubmit({ availableOffline }) {
    if (!remoteDriveDetails)
      return;
    props.onSubmit({
      ...remoteDriveDetails,
      availableOffline,
      url: debouncedUrl
    });
  }
  return jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit(onSubmit), children: hasConfirmedUrl ? jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(DriveName, { driveName: remoteDriveDetails?.name ?? "New drive" }), jsxRuntimeExports.jsx(Divider, { className: "my-3" }), jsxRuntimeExports.jsxs(Disclosure, { isOpen: showLocationSettings, onOpenChange: () => setShowLocationSettings(!showLocationSettings), title: "Location", children: [jsxRuntimeExports.jsx(LocationInfo, { location: "SWITCHBOARD" }), jsxRuntimeExports.jsx(AvailableOfflineToggle, { ...register("availableOffline") })] }), jsxRuntimeExports.jsx(PowerhouseButton, { className: "mt-4 w-full", color: "dark", type: "submit", children: "Add new drive" })] }) : jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(FormInput, { errorMessage, onChange: (e) => setUrl(e.target.value), placeholder: "Drive URL", required: true, type: "url", value: url }), jsxRuntimeExports.jsx(PowerhouseButton, { className: "mt-4 w-full py-2 text-base", color: "dark", size: "small", disabled: !isUrlValid || url === "", onClick: (e) => {
    e.preventDefault();
    setHasConfirmedUrl(true);
  }, type: "button", children: "Add drive" })] }) });
}
function appToInputOption(app) {
  return {
    value: app.id,
    displayValue: app.name,
    icon: jsxRuntimeExports.jsx(Icon, { name: "PowerhouseLogoSmall" }),
    description: "Built by Powerhouse"
  };
}
function AppFormInput(props) {
  const { control, appOptions, ...delegatedProps } = props;
  const items = appOptions.map(appToInputOption);
  return jsxRuntimeExports.jsx(Controller, { control, name: "appId", render: ({ field }) => jsxRuntimeExports.jsx(ConnectSelect, { ...delegatedProps, ...field, id: "appId", items }) });
}
function DriveName(props) {
  return jsxRuntimeExports.jsxs("div", { className: "flex gap-2 rounded-xl bg-gray-100 p-3 font-semibold text-gray-500", children: [jsxRuntimeExports.jsx(Icon, { className: "text-gray-600", name: "Drive" }), props.driveName] });
}
function AddDriveModal$1(props) {
  function handleCancel() {
    onOpenChange(false);
  }
  const { open, onOpenChange, onAddRemoteDrive, onAddLocalDrive, requestPublicDrive: requestPublicDrive2, modalProps, containerProps } = props;
  return jsxRuntimeExports.jsx(Modal, { ...modalProps, contentProps: {
    className: "rounded-2xl"
  }, onOpenChange, open, children: jsxRuntimeExports.jsx("div", { ...containerProps, className: twMerge("w-[408px] rounded-2xl p-6", containerProps?.className), children: jsxRuntimeExports.jsxs(Tabs, { defaultValue: "Create Drive", children: [jsxRuntimeExports.jsx(TabContent, { label: "Create Drive", description: "Create a new drive", children: jsxRuntimeExports.jsx(AddLocalDriveForm, { onCancel: handleCancel, onSubmit: onAddLocalDrive, appOptions: props.appOptions }) }), jsxRuntimeExports.jsx(TabContent, { label: "Add Drive", description: "Add a drive", children: jsxRuntimeExports.jsx(AddRemoteDriveForm, { sharingType: "PUBLIC", onSubmit: onAddRemoteDrive, onCancel: handleCancel, requestPublicDrive: requestPublicDrive2 }) })] }) }) });
}
function TabContent(props) {
  const { label, children } = props;
  return jsxRuntimeExports.jsx("div", { children });
}
function Tabs({ children, defaultValue }) {
  return jsxRuntimeExports.jsxs(Root2, { defaultValue, className: "flex flex-col gap-2", children: [jsxRuntimeExports.jsx("div", { className: "flex w-full justify-between", children: jsxRuntimeExports.jsx(List, { className: "flex w-full gap-x-2 rounded-xl bg-slate-50 p-1 text-sm font-semibold text-gray-600 outline-none", children: React.Children.map(children, (child, i) => {
    if (!React.isValidElement(child))
      return;
    const { label, disabled } = child.props;
    return jsxRuntimeExports.jsx(Trigger, { className: "data-[state='active']:tab-shadow ata-disabled:cursor-not-allowed data-disabled:text-gray-400 flex h-7 flex-1 items-center justify-center rounded-lg transition duration-300 data-[state='active']:bg-gray-50 data-[state='active']:text-gray-900", value: label, disabled: disabled ?? false, children: label }, label);
  }) }) }), jsxRuntimeExports.jsx("div", { className: "mt-3 rounded-md bg-white", children: React.Children.map(children, (child, i) => {
    if (!React.isValidElement(child))
      return;
    const { label } = child.props;
    return jsxRuntimeExports.jsx(Content, { value: label, children: child }, i);
  }) })] });
}
function AddDriveModal() {
  const phModal = usePHModal();
  const open = phModal?.type === "addDrive";
  const user = useUser();
  const connectCrypto = useConnectCrypto();
  const driveEditorModules = useDriveEditorModules();
  const onAddLocalDrive = async (data) => {
    try {
      const app = driveEditorModules?.find((a) => a.id === data.appId);
      const newDrive = await addDrive(
        {
          id: "",
          slug: "",
          global: {
            name: data.name,
            icon: null
          },
          local: {
            availableOffline: data.availableOffline,
            sharingType: data.sharingType.toLowerCase(),
            listeners: [],
            triggers: []
          }
        },
        app?.id
      );
      toast(t("notifications.addDriveSuccess"), {
        type: "connect-success"
      });
      if (!newDrive) {
        return;
      }
      setSelectedDrive(newDrive);
    } catch (e) {
      console.error(e);
    }
  };
  const onAddRemoteDrive = async (data) => {
    try {
      const newDrive = await addRemoteDrive(data.url, {
        sharingType: data.sharingType,
        availableOffline: data.availableOffline,
        listeners: [
          {
            block: true,
            callInfo: {
              data: data.url,
              name: "switchboard-push",
              transmitterType: "SwitchboardPush"
            },
            filter: {
              branch: ["main"],
              documentId: ["*"],
              documentType: ["*"],
              scope: ["global"]
            },
            label: "Switchboard Sync",
            listenerId: "1",
            system: true
          }
        ],
        triggers: []
      });
      toast(t("notifications.addDriveSuccess"), {
        type: "connect-success"
      });
      if (!newDrive) {
        return;
      }
      setSelectedDrive(newDrive);
    } catch (e) {
      console.error(e);
    }
  };
  async function onAddLocalDriveSubmit(data) {
    await onAddLocalDrive(data);
    closePHModal();
  }
  async function onAddRemoteDriveSubmit(data) {
    await onAddRemoteDrive(data);
    closePHModal();
  }
  const ready = !!driveEditorModules?.length;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    AddDriveModal$1,
    {
      open: open && ready,
      onAddLocalDrive: onAddLocalDriveSubmit,
      onAddRemoteDrive: onAddRemoteDriveSubmit,
      requestPublicDrive: async (url) => {
        try {
          const authToken = await connectCrypto?.getBearerToken?.(
            url,
            user?.address,
            true,
            { expiresIn: 10 }
          );
          return requestPublicDrive(url, {
            Authorization: `Bearer ${authToken}`
          });
        } catch (error) {
          console.error(error);
          const authToken = await connectCrypto?.getBearerToken?.(
            url,
            user?.address,
            true,
            { expiresIn: 10 }
          );
          return requestPublicDrive(url, {
            Authorization: `Bearer ${authToken}`
          });
        }
      },
      onOpenChange: (status) => {
        if (!status) return closePHModal();
      },
      appOptions: driveEditorModules?.map((pkg) => ({
        id: pkg.id,
        name: pkg.name,
        driveEditor: pkg.id
      })) || []
    }
  );
}
export {
  AddDriveModal
};
//# sourceMappingURL=AddDriveModal-DK9E9lEh.js.map
