import{r as a,j as b}from"./index-BrKLwClo.js";import{K as R}from"./knowledgeApi.contracts-k-GJjwsS.js";import{B as S}from"./button-CEehFzQd.js";import{a as $}from"./assert-NcfOxGOJ.js";import{c as z}from"./cn-DZ6KI8WZ.js";function q({name:p,preview:u,onUpload:l,onFetch:f,onRemove:n,disabled:m,uploadText:g="Browse files to upload",labelText:k="Upload files",className:w,onChange:x,fileList:j,...e}){const i=a.useRef(null),[s,t]=a.useState([]),o=a.useCallback(async()=>{$(f);try{const r=await f();t(r)}catch(r){console.error(r)}},[f]),c=a.useCallback(async r=>{if(x)return x(r);const{files:d}=r.target;d&&[...d].forEach(async h=>{const C=Math.random();t(F=>[{id:C,file_name:h.name,file_size:h.size,file_type:h.type,status:"uploading"},...F]),l==null||l(h).then(F=>{t(E=>E.map(y=>y.id===C?{...F,status:"done"}:y))}).catch(F=>{t(E=>E.map(y=>y.id===C?{...y,status:"error",error:F}:y))})})},[l,x]),_=a.useCallback(async r=>{try{n&&(typeof r=="string"||r%1===0)&&await n(r),t(d=>d.filter(h=>h.id!==r))}catch(d){console.error(d)}},[n]),L=a.useCallback(()=>{var r;(r=i.current)==null||r.click()},[]);return a.useEffect(()=>{f&&o()},[o]),b.jsxs("div",{className:z("flex flex-col gap-2",w),children:[b.jsxs("label",{htmlFor:e.id,children:[b.jsx("span",{className:"text-foreground text-xs font-medium",children:k}),b.jsx("input",{name:p,type:"file",ref:i,...e,disabled:m,onChange:c,hidden:!0}),b.jsx(S,{onClick:L,size:"xs",variant:"outline",className:"!text-xs",disabled:m,isFluid:!0,children:g})]}),u==null?void 0:u({fileList:j??s,remove:n?_:void 0})]})}function K({organizationId:p,pipelineId:u,runId:l}){const[f,n]=a.useState([]),m=a.useRef(null),g=a.useCallback(async(e,i)=>{var _;if(!i)throw new Error("Missing file block name");const s=new FormData;s.append("file",e),s.append("block_name",i),s.append("input_name","input");const t=await fetch(`/super-api/organizations/${p}/pipelines/${u}/runs/${l}/input_file`,{body:s,method:"POST"}),o=await t.json();if(!t.ok)throw new Error(((_=o==null?void 0:o.errors)==null?void 0:_.detail)??"Something went wrong!");return{...R.parse(o),status:"done"}},[p,u,l]),k=a.useCallback(async(e,i)=>fetch(`/super-api/organizations/${p}/pipelines/${u}/runs/${l}/input_file`,{method:"DELETE",body:JSON.stringify({file_id:e,block_name:i,input_name:"input"}),headers:{"Content-Type":"application/json"}}),[p,u,l]),w=async(e,i)=>{const s=Math.random();n(t=>[{id:s,file_name:e.name,file_size:e.size,file_type:e.type,status:"uploading"},...t]);try{const t=await g(e,i);n(o=>o.map(c=>c.id===s?{...t,status:"done"}:c))}catch(t){n(o=>o.map(c=>c.id===s?{...c,status:"error",error:t}:c))}finally{if(!m.current)return;m.current.value=""}},x=a.useCallback(async(e,i)=>{try{(typeof e=="string"||e%1===0)&&await k(e,i),n(s=>s.filter(t=>t.id!==e))}catch(s){console.error(s)}},[k,n]),j=a.useCallback(()=>{n([])},[n]);return{fileList:f,uploadFile:w,removeFile:x,inputRef:m,clearFiles:j,isUploading:f.some(e=>e.status==="uploading")}}export{q as F,K as u};
