import{j as n}from"./vendor-mui-69397583.js";import{r as x,L as _}from"./vendor-react-ece1c85f.js";import{P as O}from"./papaparse.min-f30b4da6.js";import{E as D}from"./vendor-excel-ee8fc4e5.js";import"./Alert-7dfbd254.js";import{B as N,cr as J,O as R,Q as U}from"./index-c62ac197.js";import"./index-6b6d0f06.js";import"./index-c2088808.js";import"./Drawer-949c18c6.js";import"./FormContainer-91c2b0e4.js";import"./Switcher-c8648037.js";import"./index-36228db5.js";import{U as Q}from"./Upload-fb34ce03.js";import{S as Y}from"./StickyFooter-5b934274.js";const L=1,Z=["text/csv","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],q=m=>{var f;const g=m.split(".");return g.length>1?(f=g.pop())==null?void 0:f.toLowerCase():""},me=({requiredHeaders:m,apiUrl:g,allowedHeaders:f,onDiscard:w,importType:T,templateFile:P,fetchData:$})=>{const[b,E]=x.useState([]),[G,j]=x.useState([]),[v,a]=x.useState([]),[A,i]=x.useState(!1),[k,S]=x.useState(!1),I=()=>{j([]),a([]),i(!1)},V=e=>{e.success?(R.push(n.jsx(U,{title:"Success",type:"success",duration:2500,children:(e==null?void 0:e.message)||"Success"}),{placement:"top-center"}),i(!1),j([]),E([]),w(),$()):R.push(n.jsx(U,{title:"Error",type:"danger",duration:2500,children:e.message||"Import Failed"}),{placement:"top-center"})},C=(e,t)=>{const s=[],o=e.map(l=>l.trim()),r=f&&f.length>0?f:m,d=m.filter(l=>!o.includes(l)),h=o.filter(l=>!r.includes(l));d.length>0&&(d.length===m.length?s.push("The uploaded file does not match the expected template. None of the required columns were found."):s.push(`Missing required columns: ${d.join(", ")}`)),h.length>0&&s.push(`These columns are not allowed and will be ignored: ${h.join(", ")}`),(d.length>0||h.length>0)&&(s.push(`Required columns: ${m.join(", ")}`),s.push(`Allowed columns: ${r.join(", ")}`));const u=o.filter(l=>r.includes(l));u.length===0&&s.push("No valid columns found. The file does not match the expected template.");const y=t.map(l=>{const p={};return u.forEach(c=>{p[c]=l[c]}),p});if(y.forEach((l,p)=>{m.forEach(c=>{(!l[c]||String(l[c]).trim()==="")&&s.push(`Row ${p+2}: "${c}" cannot be empty`)})}),s.length>0){a(s),i(!1);return}j(y),i(!0),a([])},W=e=>{O.parse(e,{header:!0,skipEmptyLines:!0,transformHeader:t=>t.trim(),complete:t=>{const s=t.data,o=t.meta.fields||[];if(!o||o.length===0){a(["No header row found in the CSV file."]),i(!1);return}C(o,s)},error:t=>{a([t.message]),i(!1)}})},z=async e=>{try{const t=await e.arrayBuffer(),s=new D.Workbook;await s.xlsx.load(t);const o=s.worksheets[0];if(!o){a(["No sheets found in the Excel file."]),i(!1);return}const r=[];if(o.eachRow({includeEmpty:!1},l=>{const p=l.values.slice(1).map(c=>c==null?"":String(c));r.push(p)}),r.length===0){a(["The Excel sheet is empty."]),i(!1);return}const[d,...h]=r;if(!d||d.length===0){a(["No header row found in the Excel file."]),i(!1);return}const u=d.map(l=>String(l).trim()),y=h.map(l=>{const p={};return u.forEach((c,X)=>{p[c]=l[X]??""}),p});C(u,y)}catch(t){a([(t==null?void 0:t.message)||"Failed to parse Excel file. Please check the format."]),i(!1)}},F=e=>{if(E(e),I(),!e||e.length===0)return;const t=e[0];if(!t)return;const s=t.name.toLowerCase(),o=s.endsWith(".csv"),r=s.endsWith(".xlsx"),d=s.endsWith(".xls");if(!o&&!r&&!d){a(["Unsupported file type. Please upload a CSV or Excel file (.csv, .xlsx, .xls)."]),i(!1);return}o?W(t):z(t)},B=async()=>{var e,t,s;try{S(!0),a([]);const o=await g(b,T,q((e=b[0])==null?void 0:e.name));V(o)}catch(o){a([((s=(t=o==null?void 0:o.response)==null?void 0:t.data)==null?void 0:s.message)||"Upload failed"])}finally{S(!1)}},M=(e,t)=>{let s=!0;const o=1e7;if(t.length>=L)return`You can only upload ${L} file(s)`;if(e)for(const r of e)Z.includes(r.type)?r.size>=o&&(s="Upload file cannot be more than 10MB!"):s="Only csv, xlsx, xls files are allowed!";return s};return n.jsxs("div",{children:[n.jsx(Q,{draggable:!0,accept:".csv,.xlsx,.xls",cropNeeded:!1,fileList:b,beforeUpload:M,onChange:e=>F(e),onFileRemove:e=>F(e)}),n.jsx(_,{download:!0,className:"block lg:inline-block md:mx-2 md:mb-0 mb-4 text-blue-600",to:P,rel:"noopener noreferrer",target:"_blank",children:"Download Template"}),v.length>0&&n.jsxs("div",{style:{color:"red",marginTop:10},children:[n.jsx("b",{children:"Validation Errors:"}),n.jsx("ul",{children:v.map((e,t)=>n.jsx("li",{children:e},t))})]}),A&&n.jsx(Y,{className:"px-8 flex items-center justify-between py-4 w30",stickyClass:"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700",children:n.jsxs("div",{className:"flex items-center justify-between w-full",children:[n.jsx(N,{size:"sm",className:"ltr:mr-3 rtl:ml-3",type:"button",disabled:k,onClick:()=>w==null?void 0:w(),children:"Discard"}),n.jsx(N,{type:"button",size:"sm",variant:"solid",loading:k,icon:n.jsx(J,{}),onClick:B,children:"Upload"})]})})]})};export{me as C};
