import { jsxs as r, jsx as e, Fragment as ln } from "react/jsx-runtime";
import { useTranslateProvider as sn } from "@/common/languageTranslator/TranslationContext";
import { execute as xe, executeAll as dn } from "@/common/services/QueryBuilder";
import { showToast as F } from "@/common/toaster/toaster";
import cn from "@monaco-editor/react";
import { Dialog as Ae, DialogTitle as Re, Typography as C, Divider as te, DialogContent as Ne, TableContainer as ke, Table as Oe, TableHead as $e, TableRow as K, TableCell as y, TableBody as Me, Chip as A, Box as x, Accordion as pn, AccordionSummary as mn, AccordionDetails as hn, DialogActions as ze, Button as M, Alert as Ce, Paper as be, Tooltip as U, TextField as Se, InputAdornment as un, Checkbox as ve, List as fn, ListItem as gn, ListItemButton as yn, ListItemText as xn, IconButton as Te, Autocomplete as Cn } from "@mui/material";
import b from "prop-types";
import bn, { useState as g, useRef as Sn, useEffect as Ie, Suspense as vn, lazy as Tn } from "react";
import I from "@/common/fontAwesomeIcons/FontAwesomeIcons";
import we from "@mui/material/Grid2";
import { useForm as In } from "react-hook-form";
import { useSelector as wn } from "react-redux";
const Ee = {
  NEW_TABLE: { label: "New Table", color: "success" },
  MODIFIED: { label: "Modified", color: "warning" },
  SYNC_REQUIRED: { label: "Sync Required", color: "info" },
  NO_CHANGES: { label: "No Changes", color: "default" }
};
function De({ changes: d, status: z }) {
  var m, w, v, R, O;
  const f = [];
  return z === "NEW_TABLE" ? f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: `${((m = d.addedColumns) == null ? void 0 : m.length) || 0} columns`,
        color: "success",
        variant: "outlined"
      },
      "new"
    )
  ) : ((w = d.addedColumns) != null && w.length && f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: `+${d.addedColumns.length} cols`,
        color: "success",
        variant: "outlined"
      },
      "add"
    )
  ), (v = d.removedColumns) != null && v.length && f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: `-${d.removedColumns.length} cols`,
        color: "error",
        variant: "outlined"
      },
      "rem"
    )
  ), (R = d.typeChangedColumns) != null && R.length && f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: `${d.typeChangedColumns.length} types`,
        color: "warning",
        variant: "outlined"
      },
      "type"
    )
  ), d.primaryKeyChange && f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: "PK changed",
        color: "warning",
        variant: "outlined"
      },
      "pk"
    )
  ), (O = d.settingsChanges) != null && O.length && f.push(
    /* @__PURE__ */ e(
      A,
      {
        size: "small",
        label: `${d.settingsChanges.length} settings`,
        color: "info",
        variant: "outlined"
      },
      "set"
    )
  ), f.length || f.push(
    /* @__PURE__ */ e(C, { variant: "caption", color: "text.secondary", children: "—" }, "none")
  )), /* @__PURE__ */ e(x, { sx: { display: "flex", gap: 0.5, flexWrap: "wrap" }, children: f });
}
function We({ item: d }) {
  var w, v, R, O, D, W, T;
  const { tableName: z, status: f, changes: m } = d;
  return /* @__PURE__ */ r(x, { sx: { p: 1.5 }, children: [
    f === "NEW_TABLE" && /* @__PURE__ */ r(Ce, { severity: "success", sx: { mb: 1.5, py: 0.5 }, children: [
      "This table does not exist in the database. A",
      " ",
      /* @__PURE__ */ e("strong", { children: "CREATE TABLE" }),
      " migration script will be generated."
    ] }),
    (((w = m.addedColumns) == null ? void 0 : w.length) > 0 || ((v = m.removedColumns) == null ? void 0 : v.length) > 0 || ((R = m.typeChangedColumns) == null ? void 0 : R.length) > 0 || m.primaryKeyChange) && f !== "NEW_TABLE" && /* @__PURE__ */ r(Ce, { severity: "warning", sx: { mb: 1.5, py: 0.5 }, children: [
      "SQLite does not support all ALTER TABLE operations. A",
      " ",
      /* @__PURE__ */ e("strong", { children: "rebuild migration" }),
      " (dummy table copy) will be generated."
    ] }),
    (((O = m.addedColumns) == null ? void 0 : O.length) > 0 || ((D = m.removedColumns) == null ? void 0 : D.length) > 0 || ((W = m.typeChangedColumns) == null ? void 0 : W.length) > 0) && /* @__PURE__ */ e(
      ke,
      {
        sx: {
          mb: 1.5,
          border: "1px solid",
          borderColor: "divider",
          borderRadius: 1
        },
        children: /* @__PURE__ */ r(Oe, { size: "small", children: [
          /* @__PURE__ */ e($e, { children: /* @__PURE__ */ r(K, { sx: { backgroundColor: "action.hover" }, children: [
            /* @__PURE__ */ e(y, { sx: { fontWeight: 700, fontSize: "0.75rem" }, children: "Column" }),
            /* @__PURE__ */ e(y, { sx: { fontWeight: 700, fontSize: "0.75rem" }, children: "Type" }),
            /* @__PURE__ */ e(y, { sx: { fontWeight: 700, fontSize: "0.75rem" }, children: "Change" })
          ] }) }),
          /* @__PURE__ */ r(Me, { children: [
            (m.addedColumns || []).map((l) => /* @__PURE__ */ r(
              K,
              {
                sx: { backgroundColor: "rgba(76,175,80,0.08)" },
                children: [
                  /* @__PURE__ */ e(
                    y,
                    {
                      sx: { fontSize: "0.75rem", fontFamily: "monospace" },
                      children: l.name
                    }
                  ),
                  /* @__PURE__ */ e(y, { sx: { fontSize: "0.75rem" }, children: l.type }),
                  /* @__PURE__ */ e(y, { children: /* @__PURE__ */ e(A, { size: "small", label: "Added", color: "success" }) })
                ]
              },
              `add-${l.name}`
            )),
            (m.removedColumns || []).map((l) => /* @__PURE__ */ r(
              K,
              {
                sx: { backgroundColor: "rgba(244,67,54,0.08)" },
                children: [
                  /* @__PURE__ */ e(
                    y,
                    {
                      sx: {
                        fontSize: "0.75rem",
                        fontFamily: "monospace",
                        textDecoration: "line-through",
                        color: "error.main"
                      },
                      children: l.name
                    }
                  ),
                  /* @__PURE__ */ e(
                    y,
                    {
                      sx: {
                        fontSize: "0.75rem",
                        textDecoration: "line-through",
                        color: "error.main"
                      },
                      children: l.type
                    }
                  ),
                  /* @__PURE__ */ e(y, { children: /* @__PURE__ */ e(A, { size: "small", label: "Removed", color: "error" }) })
                ]
              },
              `rem-${l.name}`
            )),
            (m.typeChangedColumns || []).map((l) => /* @__PURE__ */ r(
              K,
              {
                sx: { backgroundColor: "rgba(255,152,0,0.08)" },
                children: [
                  /* @__PURE__ */ e(
                    y,
                    {
                      sx: { fontSize: "0.75rem", fontFamily: "monospace" },
                      children: l.name
                    }
                  ),
                  /* @__PURE__ */ r(y, { sx: { fontSize: "0.75rem" }, children: [
                    /* @__PURE__ */ e(
                      "span",
                      {
                        style: {
                          textDecoration: "line-through",
                          color: "var(--mui-palette-error-main)",
                          marginRight: "8px"
                        },
                        children: l.oldType
                      }
                    ),
                    /* @__PURE__ */ e("span", { children: l.newType })
                  ] }),
                  /* @__PURE__ */ e(y, { children: /* @__PURE__ */ e(A, { size: "small", label: "Type Changed", color: "warning" }) })
                ]
              },
              `type-${l.name}`
            ))
          ] })
        ] })
      }
    ),
    m.primaryKeyChange && /* @__PURE__ */ r(
      x,
      {
        sx: {
          mb: 1.5,
          p: 1,
          backgroundColor: "warning.50",
          borderRadius: 1,
          border: "1px solid",
          borderColor: "warning.200"
        },
        children: [
          /* @__PURE__ */ e(
            C,
            {
              variant: "caption",
              sx: { fontWeight: 700, color: "warning.dark" },
              children: "Primary Key Change:"
            }
          ),
          /* @__PURE__ */ r(C, { variant: "caption", sx: { ml: 1 }, children: [
            /* @__PURE__ */ e("code", { children: m.primaryKeyChange.from }),
            " → ",
            /* @__PURE__ */ e("code", { children: m.primaryKeyChange.to })
          ] })
        ]
      }
    ),
    ((T = m.settingsChanges) == null ? void 0 : T.length) > 0 && /* @__PURE__ */ r(x, { sx: { mb: 1.5 }, children: [
      /* @__PURE__ */ e(
        C,
        {
          variant: "caption",
          sx: { fontWeight: 700, display: "block", mb: 0.5 },
          children: "Settings Changes:"
        }
      ),
      m.settingsChanges.map((l, _) => /* @__PURE__ */ r(
        x,
        {
          sx: { display: "flex", alignItems: "center", gap: 1, mb: 0.25 },
          children: [
            /* @__PURE__ */ r(
              C,
              {
                variant: "caption",
                sx: { color: "text.secondary", minWidth: 120 },
                children: [
                  l.field,
                  ":"
                ]
              }
            ),
            /* @__PURE__ */ r(C, { variant: "caption", children: [
              /* @__PURE__ */ e("code", { children: String(l.from) }),
              " → ",
              /* @__PURE__ */ e("code", { children: String(l.to) })
            ] })
          ]
        },
        _
      ))
    ] })
  ] });
}
function _e({
  open: d,
  onClose: z,
  summaryData: f,
  onApply: m,
  applying: w,
  migrationVersions: v,
  unifiedMigrationScript: R,
  onUnifiedScriptChange: O
}) {
  const [D, W] = g(!0), T = f.filter(
    (l) => l.status !== "NO_CHANGES"
  ).length;
  return /* @__PURE__ */ r(
    Ae,
    {
      open: d,
      onClose: z,
      maxWidth: "md",
      fullWidth: !0,
      PaperProps: { sx: { borderRadius: 3 } },
      children: [
        /* @__PURE__ */ r(Re, { sx: { pb: 1, fontWeight: 700 }, children: [
          "Import Summary",
          /* @__PURE__ */ r(C, { variant: "body2", color: "text.secondary", children: [
            T,
            " table(s) will be affected · ",
            f.length,
            " total in file"
          ] })
        ] }),
        /* @__PURE__ */ e(te, {}),
        /* @__PURE__ */ r(Ne, { sx: { p: 0 }, children: [
          /* @__PURE__ */ e(ke, { children: /* @__PURE__ */ r(Oe, { children: [
            /* @__PURE__ */ e($e, { children: /* @__PURE__ */ r(K, { sx: { backgroundColor: "action.hover" }, children: [
              /* @__PURE__ */ e(y, { sx: { fontWeight: 700, pl: 3 }, children: "Table Name" }),
              /* @__PURE__ */ e(y, { sx: { fontWeight: 700 }, children: "Status" }),
              /* @__PURE__ */ e(y, { sx: { fontWeight: 700 }, children: "Changes" })
            ] }) }),
            /* @__PURE__ */ e(Me, { children: f.map((l) => {
              const _ = Ee[l.status] || Ee.NO_CHANGES;
              return /* @__PURE__ */ r(bn.Fragment, { children: [
                /* @__PURE__ */ r(
                  K,
                  {
                    sx: {
                      "& > *": {
                        borderBottom: l.status !== "NO_CHANGES" ? "none" : void 0
                      }
                    },
                    children: [
                      /* @__PURE__ */ e(
                        y,
                        {
                          sx: {
                            fontFamily: "monospace",
                            fontSize: "0.82rem",
                            pl: 3
                          },
                          children: l.tableName
                        }
                      ),
                      /* @__PURE__ */ e(y, { children: /* @__PURE__ */ e(
                        A,
                        {
                          label: _.label,
                          color: _.color,
                          size: "small",
                          sx: { fontWeight: 600 }
                        }
                      ) }),
                      /* @__PURE__ */ e(y, { children: /* @__PURE__ */ e(
                        De,
                        {
                          changes: l.changes,
                          status: l.status
                        }
                      ) })
                    ]
                  }
                ),
                l.status !== "NO_CHANGES" && /* @__PURE__ */ e(K, { children: /* @__PURE__ */ e(
                  y,
                  {
                    colSpan: 3,
                    sx: {
                      pt: 0,
                      pb: 0.5,
                      px: 2,
                      backgroundColor: "action.hover"
                    },
                    children: /* @__PURE__ */ e(
                      We,
                      {
                        item: l
                      }
                    )
                  }
                ) })
              ] }, l.tableName);
            }) })
          ] }) }),
          R && /* @__PURE__ */ e(x, { sx: { p: 3, borderTop: "1px solid", borderColor: "divider" }, children: /* @__PURE__ */ r(
            pn,
            {
              expanded: D,
              onChange: () => W((l) => !l),
              sx: {
                boxShadow: "none",
                border: "1px solid",
                borderColor: "divider",
                borderRadius: "4px !important"
              },
              children: [
                /* @__PURE__ */ e(
                  mn,
                  {
                    expandIcon: /* @__PURE__ */ e(
                      I,
                      {
                        iconName: "faChevronDown",
                        className: "text-[0.75rem]"
                      }
                    ),
                    children: /* @__PURE__ */ r(
                      x,
                      {
                        sx: {
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "center",
                          width: "100%",
                          pr: 2
                        },
                        children: [
                          /* @__PURE__ */ r(C, { variant: "caption", sx: { fontWeight: 700 }, children: [
                            /* @__PURE__ */ e(
                              I,
                              {
                                iconName: "faCode",
                                className: "mr-2 text-[0.7rem]"
                              }
                            ),
                            "Preview Unified Migration Script"
                          ] }),
                          v && v.from_version !== void 0 && /* @__PURE__ */ r(
                            C,
                            {
                              variant: "caption",
                              sx: { color: "text.secondary", fontWeight: 600 },
                              children: [
                                "From : ",
                                /* @__PURE__ */ r("strong", { children: [
                                  "v",
                                  v.from_version + 1
                                ] }),
                                /* @__PURE__ */ e(
                                  I,
                                  {
                                    iconName: "faArrowRight",
                                    className: "mx-2 text-[0.6rem]"
                                  }
                                ),
                                "To : ",
                                /* @__PURE__ */ r("strong", { children: [
                                  "v",
                                  v.to_version + 1
                                ] })
                              ]
                            }
                          )
                        ]
                      }
                    )
                  }
                ),
                /* @__PURE__ */ e(hn, { sx: { p: 0 }, children: /* @__PURE__ */ e(
                  cn,
                  {
                    height: "300px",
                    defaultLanguage: "sql",
                    theme: "vs-dark",
                    options: {
                      fontSize: 12,
                      minimap: { enabled: !1 },
                      readOnly: !1,
                      scrollBeyondLastLine: !1,
                      wordWrap: "on"
                    },
                    value: R,
                    onChange: O
                  }
                ) })
              ]
            }
          ) })
        ] }),
        /* @__PURE__ */ e(te, {}),
        /* @__PURE__ */ r(ze, { sx: { px: 3, py: 2, gap: 1 }, children: [
          /* @__PURE__ */ e(
            M,
            {
              onClick: z,
              variant: "outlined",
              size: "small",
              sx: { borderRadius: 2, textTransform: "none" },
              disabled: w,
              children: "Cancel"
            }
          ),
          /* @__PURE__ */ e(
            M,
            {
              variant: "contained",
              size: "small",
              disabled: T === 0 || w,
              onClick: m,
              sx: { borderRadius: 2, textTransform: "none", boxShadow: "none" },
              startIcon: w ? null : /* @__PURE__ */ e(I, { iconName: "faCheck" }),
              children: w ? "Applying…" : `Apply Import (${T})`
            }
          )
        ] })
      ]
    }
  );
}
_e.propTypes = {
  open: b.bool.isRequired,
  onClose: b.func.isRequired,
  summaryData: b.array.isRequired,
  onApply: b.func.isRequired,
  applying: b.bool,
  migrationVersions: b.object,
  unifiedMigrationScript: b.string,
  onUnifiedScriptChange: b.func.isRequired
};
We.propTypes = {
  item: b.object
};
De.propTypes = {
  changes: b.object,
  status: b.string
};
const En = Tn(() => import("./TableDetails-DztbjsIA.js"));
function An({
  tableList: d,
  tablesInfo: z,
  allTableList: f,
  allTablesInfo: m,
  formSubmitted: w,
  reloadComponents: v
}) {
  const [R, O] = g(""), [D, W] = g(""), [T, l] = g({}), [_, Y] = g({}), [P, Be] = g({}), [Fe, V] = g({}), N = d ? d.filter(
    (n) => n.toLowerCase().includes(R.toLowerCase())
  ) : [], [Ke, L] = g(!1), [je, X] = g(!1), [j, Z] = g(), [ae, Q] = g(!1), [Pe, ie] = g(!1), [Le, le] = g(!1), { translate: se } = sn(), de = wn((n) => n.Authenticate.user.id), [h, ce] = g(!1), [E, G] = g(/* @__PURE__ */ new Set()), pe = Sn(null), [Qe, ee] = g(!1), [me, Ge] = g([]), [Ue, H] = g(!1), [He, he] = g({}), [ne, ue] = g("");
  In({
    defaultValues: {
      field1: "",
      field2: "",
      field3: ""
    }
  }), Ie(() => {
    let n = {}, t = {};
    W(d[0]), n = fe(z), l((i) => ({ ...i, ...n })), t = fe(m), Be((i) => ({ ...i, ...t }));
  }, [z, m]), Ie(() => {
    Y(() => T[d[0]]), V(() => P[d[0]]);
  }, [T, P]);
  const Je = (n) => {
    const t = n.toLowerCase();
    return t.includes("int") || t.includes("timestamp") || t === "boolean" || t.includes("serial") || t.includes("date") ? "INTEGER" : (t.includes("char") || t.includes("text") || t.includes("varchar"), "TEXT");
  }, fe = (n) => {
    const t = {};
    return n.forEach((i) => {
      const o = JSON.parse(i.columnInfo), p = Object.keys(o).map((s) => ({
        name: s,
        type: Je(o[s])
      })), a = i.mediaConfiguration ? JSON.parse(i.mediaConfiguration) : null;
      t[i.tableName] = {
        columnInfo: p,
        modifiedOnQuery: i.modifiedOnQuery ? i.modifiedOnQuery : null,
        primaryKey: i.primaryKey ? i.primaryKey : null,
        selectQuery: i.selectQuery ? i.selectQuery : null,
        userData: i.userData !== void 0 ? i.userData : null,
        hasMedia: i.hasMedia !== void 0 ? i.hasMedia : null,
        mediaConfiguration: a,
        syncByDefault: i.syncByDefault ? i.syncByDefault : !1
      };
    }), t;
  }, qe = () => {
    Q(!1), X(!0), Z();
  }, Ye = () => {
    L(!1), Q(!0);
  }, ge = () => {
    X(!1);
  }, Ve = () => {
    if (j) {
      const n = { ...P[j] };
      n && (n.columnInfo = []), W(j), Y(() => n), V(() => P[j]), ie(!0), Q(!1), L(!0);
    }
    X(!1), Z(() => "");
  }, oe = (n) => {
    W(n), Y(() => T[n]), V(() => P[n]), L(!1), Q(!1), ie(!1);
  }, Xe = () => {
    if (E.size === 0) return;
    const n = {};
    E.forEach((a) => {
      T[a] && (n[a] = T[a]);
    });
    const t = JSON.stringify(
      { exportedAt: (/* @__PURE__ */ new Date()).toISOString(), tables: n },
      null,
      2
    ), i = new Blob([t], { type: "application/json" }), o = URL.createObjectURL(i), p = document.createElement("a");
    p.href = o, p.download = `db_export_${Date.now()}.json`, p.click(), URL.revokeObjectURL(o), ce(!1), G(/* @__PURE__ */ new Set()), F({
      message: `Exported ${E.size} table(s) successfully.`,
      type: "success"
    });
  }, Ze = (n, t) => {
    const i = t.columnInfo || [];
    let o = `CREATE TABLE ${n} (
`;
    return o += i.map((p) => `  ${p.name} ${p.type}`).join(`,
`), t.primaryKey && (o += `,
  CONSTRAINT ${n}_pkey PRIMARY KEY (${t.primaryKey})`), o += `
);`, o;
  }, ye = (n, t, i) => {
    const o = i.columnInfo || [], p = t.columnInfo || [], a = new Set(o.map((k) => k.name)), c = p.filter((k) => a.has(k.name)).map((k) => k.name).join(", "), S = i.primaryKey, B = o.map((k) => `  ${k.name} ${k.type}`).join(`,
`), $ = S ? `,
  CONSTRAINT ${n}_dummy_pkey PRIMARY KEY (${S})` : "", re = S ? `,
  CONSTRAINT ${n}_pkey PRIMARY KEY (${S})` : "";
    return [
      "-- Step 1: Create dummy table with new schema",
      `CREATE TABLE ${n}_dummy (
${B}${$}
);`,
      "-- Step 2: Copy common columns from original",
      c ? `INSERT INTO ${n}_dummy (${c})
SELECT ${c} FROM ${n};` : "-- (no common columns to copy)",
      "-- Step 3: Drop original table",
      `DROP TABLE ${n};`,
      "-- Step 4: Recreate original table with new schema",
      `CREATE TABLE ${n} (
${B}${re}
);`,
      "-- Step 5: Restore data from dummy",
      c ? `INSERT INTO ${n} (${c})
SELECT ${c} FROM ${n}_dummy;` : "-- (no data to restore)",
      "-- Step 6: Drop dummy table",
      `DROP TABLE ${n}_dummy;`
    ].join(`

`);
  }, J = (n) => (n || "").replace(/\s+/g, " ").trim(), en = (n) => {
    const t = n.tables || {};
    return Object.entries(t).map(([i, o]) => {
      const p = T[i], a = p, s = {
        addedColumns: [],
        removedColumns: [],
        typeChangedColumns: [],
        primaryKeyChange: null,
        settingsChanges: []
      };
      let c = "NO_CHANGES";
      if (!p)
        c = "NEW_TABLE", s.addedColumns = o.columnInfo || [];
      else {
        const B = new Map(
          (o.columnInfo || []).map((u) => [u.name, u.type])
        ), $ = new Map(
          (a.columnInfo || []).map((u) => [u.name, u.type])
        );
        if (s.addedColumns = (o.columnInfo || []).filter(
          (u) => !$.has(u.name)
        ), s.removedColumns = (a.columnInfo || []).filter(
          (u) => !B.has(u.name)
        ), s.typeChangedColumns = (o.columnInfo || []).filter((u) => $.has(u.name) && $.get(u.name) !== u.type).map((u) => ({
          name: u.name,
          oldType: $.get(u.name),
          newType: u.type
        })), s.primaryKeyChange = o.primaryKey !== a.primaryKey ? {
          from: a.primaryKey || "(none)",
          to: o.primaryKey || "(none)"
        } : null, p) {
          const u = [];
          [
            ["syncByDefault", "Sync by Default"],
            ["userData", "User Data"],
            ["hasMedia", "Has Media"]
          ].forEach(([q, an]) => {
            String(o[q]) !== String(p[q]) && u.push({
              field: an,
              from: p[q],
              to: o[q]
            });
          }), J(o.modifiedOnQuery) !== J(p.modifiedOnQuery) && u.push({
            field: "Modified On Query",
            from: "(changed)",
            to: "(changed)"
          }), J(o.selectQuery) !== J(p.selectQuery) && u.push({
            field: "Data Fetch Query",
            from: "(changed)",
            to: "(changed)"
          }), s.settingsChanges = u;
        }
        const re = s.addedColumns.length > 0 || s.removedColumns.length > 0 || s.typeChangedColumns.length > 0 || s.primaryKeyChange, k = s.settingsChanges.length > 0;
        c = re || k ? "MODIFIED" : "NO_CHANGES";
      }
      let S = "";
      return c === "NEW_TABLE" ? S = Ze(i, o) : c !== "NO_CHANGES" && (s.addedColumns.length > 0 || s.removedColumns.length > 0 || s.typeChangedColumns.length > 0 || s.primaryKeyChange) && (S = ye(
        i,
        a,
        o
      )), {
        tableName: i,
        status: c,
        changes: s,
        importedTable: o,
        existingTable: a,
        migrationScript: S
      };
    });
  }, nn = (n) => {
    let t = "";
    return n.filter((o) => o.status !== "NO_CHANGES").forEach((o) => {
      var p, a, s;
      o.migrationScript && (t += `-- ==================================================
`, t += `-- Table: ${o.tableName}
`, o.status === "NEW_TABLE" ? t += `-- Changes: New Table
` : (t += `-- Changes:
`, (p = o.changes.addedColumns) != null && p.length && (t += `--   Added: ${o.changes.addedColumns.map((c) => c.name).join(", ")}
`), (a = o.changes.removedColumns) != null && a.length && (t += `--   Removed: ${o.changes.removedColumns.map((c) => c.name).join(", ")}
`), (s = o.changes.typeChangedColumns) != null && s.length && (t += `--   Modified types: ${o.changes.typeChangedColumns.map((c) => `${c.name} (${c.oldType} -> ${c.newType})`).join(", ")}
`), o.changes.primaryKeyChange && (t += `--   Primary Key Changed
`)), t += `-- ==================================================

`, t += o.migrationScript.trim() + `

`);
    }), t;
  }, on = (n) => {
    var o;
    const t = (o = n.target.files) == null ? void 0 : o[0];
    if (!t) return;
    const i = new FileReader();
    i.onload = (p) => {
      try {
        const a = JSON.parse(p.target.result);
        if (!a.tables)
          throw new Error("Invalid format: missing 'tables' key.");
        const s = en(a);
        Ge(s);
        const c = nn(s);
        ue(c), xe({ code: "MFA_MIGRATION_MASTER_GET_LATEST_VERSIONS" }).then((S) => {
          var B, $;
          he((($ = (B = S == null ? void 0 : S.data) == null ? void 0 : B.result) == null ? void 0 : $[0]) || {});
        }).catch(() => he({})), ee(!0);
      } catch (a) {
        F({ message: `Import failed: ${a.message}`, type: "error" });
      }
    }, i.readAsText(t), n.target.value = "";
  }, rn = (n) => {
    ue(n);
  }, tn = async () => {
    var i;
    const n = me.filter(
      (o) => o.status !== "NO_CHANGES"
    );
    if (!n.length) {
      F({ message: "Nothing to apply.", type: "info" });
      return;
    }
    H(!0);
    const t = n.map((o, p) => {
      const a = o.importedTable, s = {};
      return (a.columnInfo || []).forEach((c) => {
        s[c.name] = c.type;
      }), {
        code: "update_mobile_entity",
        parameters: {
          tableName: o.tableName || "",
          syncByDefault: !!a.syncByDefault,
          columnInfo: JSON.stringify(s) || "",
          primaryKey: a.primaryKey || "",
          modifiedOnQuery: a.modifiedOnQuery || "",
          selectQuery: a.selectQuery || "",
          userData: !!a.userData,
          hasMedia: !!a.hasMedia,
          mediaConfiguration: a.hasMedia ? JSON.stringify(a.mediaConfiguration || {}) : null,
          modifiedBy: de || "",
          isUpdate: !0
        },
        sequence: p
      };
    });
    try {
      const o = (await dn(t)).data;
      if (o == null ? void 0 : o.some((a) => a.status === 0)) {
        const a = o.findIndex((S) => S.status === 0), s = n[a], c = ((i = o[a]) == null ? void 0 : i.message) || "Unknown error";
        F({
          message: `Failed to save ${s.tableName}: ${c}`,
          type: "error"
        }), H(!1);
        return;
      }
      if (ne.trim()) {
        const a = (await xe({
          code: "INSERT_MOBILE_MIGRATION",
          parameters: {
            migrationScript: ne,
            modifiedBy: de || "",
            generateMigration: !0
          }
        })).data;
        (a == null ? void 0 : a.status) === 0 && F({
          message: `Failed to insert migration script: ${a == null ? void 0 : a.message}`,
          type: "error"
        });
      }
      H(!1), ee(!1), v((a) => !a), F({ message: "Import applied successfully!", type: "success" });
    } catch (o) {
      F({
        message: `Failed to apply import: ${o}`,
        type: "error"
      }), H(!1);
    }
  };
  return /* @__PURE__ */ r(ln, { children: [
    /* @__PURE__ */ r(
      be,
      {
        elevation: 0,
        sx: {
          p: { xs: 2.5, md: 3 },
          mt: 2,
          mb: 3,
          border: "1px solid",
          borderColor: "divider",
          borderRadius: 3,
          backgroundColor: "background.paper"
        },
        children: [
          /* @__PURE__ */ r(x, { sx: { display: "flex", flexDirection: "column", gap: 3 }, children: [
            /* @__PURE__ */ r(
              x,
              {
                sx: {
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "flex-start",
                  flexWrap: "wrap",
                  gap: 2
                },
                children: [
                  /* @__PURE__ */ r(x, { sx: { minWidth: { xs: "100%", lg: "40%" } }, children: [
                    /* @__PURE__ */ e(
                      C,
                      {
                        variant: "h5",
                        sx: { fontWeight: 800, color: "text.primary", mb: 0.5 },
                        children: se("Database Management")
                      }
                    ),
                    /* @__PURE__ */ e(C, { variant: "body2", color: "text.secondary", children: "Manage synced tables, create new entities, and configure mobile database schemas." })
                  ] }),
                  /* @__PURE__ */ r(
                    x,
                    {
                      sx: {
                        display: "flex",
                        alignItems: "center",
                        gap: 1.5,
                        flexWrap: "wrap"
                      },
                      children: [
                        /* @__PURE__ */ e(
                          "input",
                          {
                            type: "file",
                            accept: ".json",
                            ref: pe,
                            style: { display: "none" },
                            onChange: on
                          }
                        ),
                        /* @__PURE__ */ e(
                          U,
                          {
                            title: h ? "Cancel export mode" : "Export selected tables as JSON",
                            arrow: !0,
                            children: /* @__PURE__ */ e(
                              M,
                              {
                                variant: h ? "contained" : "outlined",
                                size: "small",
                                color: h ? "warning" : "inherit",
                                sx: {
                                  borderRadius: 2,
                                  fontWeight: 600,
                                  px: 2,
                                  textTransform: "none",
                                  borderColor: "divider",
                                  color: h ? "white" : "text.primary",
                                  "&:hover": {
                                    backgroundColor: h ? "warning.dark" : "action.hover",
                                    borderColor: "text.disabled"
                                  }
                                },
                                startIcon: /* @__PURE__ */ e(
                                  I,
                                  {
                                    iconName: h ? "faXmark" : "faFileExport"
                                  }
                                ),
                                onClick: () => {
                                  ce((n) => !n), G(/* @__PURE__ */ new Set());
                                },
                                children: h ? "Cancel Export" : "Export"
                              }
                            )
                          }
                        ),
                        /* @__PURE__ */ e(U, { title: "Import table configuration from JSON", arrow: !0, children: /* @__PURE__ */ e(
                          M,
                          {
                            variant: "outlined",
                            size: "small",
                            sx: {
                              borderRadius: 2,
                              fontWeight: 600,
                              px: 2,
                              textTransform: "none",
                              borderColor: "divider",
                              color: "text.primary",
                              "&:hover": {
                                backgroundColor: "action.hover",
                                borderColor: "text.disabled"
                              }
                            },
                            startIcon: /* @__PURE__ */ e(I, { iconName: "faFileImport" }),
                            onClick: () => {
                              var n;
                              return (n = pe.current) == null ? void 0 : n.click();
                            },
                            children: "Import"
                          }
                        ) }),
                        /* @__PURE__ */ e(
                          M,
                          {
                            variant: "outlined",
                            size: "small",
                            sx: {
                              borderRadius: 2,
                              fontWeight: 600,
                              px: 2,
                              textTransform: "none",
                              borderColor: "divider",
                              color: "text.primary",
                              "&:hover": {
                                backgroundColor: "action.hover",
                                borderColor: "text.disabled"
                              }
                            },
                            startIcon: /* @__PURE__ */ e(I, { iconName: "faRotate" }),
                            onClick: () => qe(),
                            children: "Sync Table"
                          }
                        ),
                        /* @__PURE__ */ e(
                          M,
                          {
                            size: "small",
                            variant: "contained",
                            sx: {
                              borderRadius: 2,
                              fontWeight: 600,
                              px: 2,
                              boxShadow: "none",
                              textTransform: "none"
                            },
                            startIcon: /* @__PURE__ */ e(I, { iconName: "faPlus" }),
                            onClick: () => Ye(),
                            children: "Create Table"
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ r(
              x,
              {
                sx: {
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  flexWrap: "wrap",
                  gap: 2,
                  backgroundColor: "action.hover",
                  p: 1.5,
                  borderRadius: 2.5,
                  border: "1px solid",
                  borderColor: "divider"
                },
                children: [
                  /* @__PURE__ */ r(x, { sx: { display: "flex", alignItems: "center", gap: 1.5 }, children: [
                    /* @__PURE__ */ e(
                      A,
                      {
                        label: `${(d == null ? void 0 : d.length) || 0} Synced`,
                        size: "small",
                        color: "primary",
                        variant: "filled",
                        sx: { fontWeight: 700, borderRadius: 2, px: 0.5 }
                      }
                    ),
                    /* @__PURE__ */ e(
                      A,
                      {
                        label: `${(f == null ? void 0 : f.length) || 0} Total`,
                        size: "small",
                        variant: "outlined",
                        sx: {
                          fontWeight: 600,
                          borderRadius: 2,
                          px: 0.5,
                          borderColor: "divider"
                        }
                      }
                    )
                  ] }),
                  /* @__PURE__ */ e(
                    Se,
                    {
                      value: R,
                      size: "small",
                      placeholder: "Search synced tables...",
                      onChange: (n) => O(n.target.value),
                      InputProps: {
                        startAdornment: /* @__PURE__ */ e(un, { position: "start", children: /* @__PURE__ */ e(I, { iconName: "faMagnifyingGlass" }) }),
                        sx: {
                          backgroundColor: "background.paper",
                          borderRadius: 2,
                          minWidth: 260
                        }
                      }
                    }
                  )
                ]
              }
            )
          ] }),
          /* @__PURE__ */ e(te, { sx: { my: 3 } }),
          /* @__PURE__ */ r(we, { container: !0, spacing: 2.5, children: [
            /* @__PURE__ */ e(we, { size: 3, children: /* @__PURE__ */ r(
              be,
              {
                variant: "outlined",
                sx: {
                  borderRadius: 2.5,
                  overflow: "hidden",
                  maxHeight: "72vh",
                  display: "flex",
                  flexDirection: "column"
                },
                children: [
                  /* @__PURE__ */ r(
                    x,
                    {
                      sx: {
                        px: 2,
                        py: 1.5,
                        backgroundColor: h ? "warning.50" : "action.hover",
                        borderBottom: "1px solid",
                        borderColor: h ? "warning.300" : "divider",
                        transition: "background-color 0.2s"
                      },
                      children: [
                        /* @__PURE__ */ r(
                          x,
                          {
                            sx: {
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "space-between"
                            },
                            children: [
                              /* @__PURE__ */ e(
                                C,
                                {
                                  variant: "subtitle2",
                                  sx: {
                                    fontWeight: 700,
                                    color: h ? "warning.dark" : "text.primary"
                                  },
                                  children: h ? "Select Tables to Export" : se("Synced Tables")
                                }
                              ),
                              h && /* @__PURE__ */ e(
                                U,
                                {
                                  title: E.size === N.length ? "Deselect all" : "Select all",
                                  arrow: !0,
                                  children: /* @__PURE__ */ e(
                                    ve,
                                    {
                                      size: "small",
                                      checked: N.length > 0 && E.size === N.length,
                                      indeterminate: E.size > 0 && E.size < N.length,
                                      onChange: (n) => {
                                        n.target.checked ? G(new Set(N)) : G(/* @__PURE__ */ new Set());
                                      },
                                      sx: { p: 0.25 }
                                    }
                                  )
                                }
                              )
                            ]
                          }
                        ),
                        /* @__PURE__ */ e(
                          C,
                          {
                            variant: "caption",
                            color: h ? "warning.dark" : "text.secondary",
                            children: h ? `${E.size} of ${N.length} selected` : `${N.length} of ${(d == null ? void 0 : d.length) || 0} tables`
                          }
                        )
                      ]
                    }
                  ),
                  /* @__PURE__ */ e(x, { sx: { overflowY: "auto", flex: 1 }, children: N.length ? /* @__PURE__ */ e(fn, { disablePadding: !0, children: N.map((n, t) => {
                    const i = D === n;
                    return /* @__PURE__ */ e(
                      gn,
                      {
                        disablePadding: !0,
                        secondaryAction: !h && /* @__PURE__ */ r(
                          x,
                          {
                            sx: {
                              display: "flex",
                              gap: 0.25,
                              opacity: i ? 1 : 0,
                              transition: "opacity 0.2s"
                            },
                            children: [
                              /* @__PURE__ */ e(
                                U,
                                {
                                  title: "Edit table",
                                  arrow: !0,
                                  placement: "top",
                                  children: /* @__PURE__ */ e(
                                    Te,
                                    {
                                      size: "small",
                                      onClick: (o) => {
                                        o.stopPropagation(), oe(n), L(!0);
                                      },
                                      sx: {
                                        color: "primary.main",
                                        "&:hover": {
                                          backgroundColor: "primary.50"
                                        }
                                      },
                                      children: /* @__PURE__ */ e(
                                        I,
                                        {
                                          iconName: "faPen",
                                          className: "text-[0.75rem]"
                                        }
                                      )
                                    }
                                  )
                                }
                              ),
                              /* @__PURE__ */ e(
                                U,
                                {
                                  title: "Delete table",
                                  arrow: !0,
                                  placement: "top",
                                  children: /* @__PURE__ */ e(
                                    Te,
                                    {
                                      size: "small",
                                      onClick: (o) => {
                                        o.stopPropagation(), oe(n), le(!0);
                                      },
                                      sx: {
                                        color: "error.main",
                                        "&:hover": {
                                          backgroundColor: "error.50"
                                        }
                                      },
                                      children: /* @__PURE__ */ e(
                                        I,
                                        {
                                          iconName: "faTrash",
                                          className: "text-[0.75rem]"
                                        }
                                      )
                                    }
                                  )
                                }
                              )
                            ]
                          }
                        ),
                        sx: {
                          borderBottom: t === N.length - 1 ? "none" : "1px solid",
                          borderColor: "divider",
                          "&:hover .MuiBox-root": { opacity: "1 !important" }
                        },
                        children: /* @__PURE__ */ r(
                          yn,
                          {
                            selected: i && !h,
                            onClick: () => {
                              if (h) {
                                const o = new Set(E);
                                o.has(n) ? o.delete(n) : o.add(n), G(o);
                              } else
                                oe(n);
                            },
                            sx: {
                              py: 1,
                              px: 2,
                              transition: "all 0.15s ease",
                              ...h ? {} : {
                                "&.Mui-selected": {
                                  backgroundColor: "primary.50",
                                  borderLeft: "3px solid",
                                  borderLeftColor: "primary.main",
                                  "&:hover": {
                                    backgroundColor: "primary.100"
                                  }
                                },
                                "&:hover": {
                                  backgroundColor: "action.hover"
                                }
                              }
                            },
                            children: [
                              h && /* @__PURE__ */ e(
                                ve,
                                {
                                  size: "small",
                                  checked: E.has(n),
                                  disableRipple: !0,
                                  sx: { p: 0, mr: 1.5 }
                                }
                              ),
                              /* @__PURE__ */ e(
                                xn,
                                {
                                  primary: /* @__PURE__ */ e(
                                    C,
                                    {
                                      variant: "body2",
                                      sx: {
                                        fontWeight: i && !h ? 600 : 400,
                                        color: i && !h ? "primary.dark" : "text.primary",
                                        fontSize: "0.82rem",
                                        overflow: "hidden",
                                        textOverflow: "ellipsis",
                                        whiteSpace: "nowrap",
                                        maxWidth: "160px"
                                      },
                                      children: n
                                    }
                                  )
                                }
                              )
                            ]
                          }
                        )
                      },
                      t + 1
                    );
                  }) }) : /* @__PURE__ */ r(x, { sx: { p: 3, textAlign: "center" }, children: [
                    /* @__PURE__ */ e(
                      I,
                      {
                        iconName: "faInbox",
                        className: "text-[2rem] text-gray-300"
                      }
                    ),
                    /* @__PURE__ */ e(
                      C,
                      {
                        variant: "body2",
                        color: "text.secondary",
                        sx: { mt: 1 },
                        children: d.length < 1 ? "No tables synced" : "No tables match your search."
                      }
                    )
                  ] }) }),
                  h && /* @__PURE__ */ r(
                    x,
                    {
                      sx: {
                        p: 2,
                        borderTop: "1px solid",
                        borderColor: "divider",
                        backgroundColor: "background.paper",
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center"
                      },
                      children: [
                        /* @__PURE__ */ r(C, { variant: "body2", sx: { fontWeight: 600 }, children: [
                          E.size,
                          " selected"
                        ] }),
                        /* @__PURE__ */ e(
                          M,
                          {
                            variant: "contained",
                            size: "small",
                            color: "primary",
                            disabled: E.size === 0,
                            onClick: Xe,
                            startIcon: /* @__PURE__ */ e(I, { iconName: "faDownload" }),
                            sx: {
                              textTransform: "none",
                              borderRadius: 2,
                              boxShadow: "none"
                            },
                            children: "Download JSON"
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ e(vn, { children: (!!D && !!_ || ae) && /* @__PURE__ */ e(
              En,
              {
                tableInfo: _,
                table: D,
                isEditMode: Ke,
                updateEditMode: L,
                tableCompleteInfo: Fe,
                formSubmitted: w,
                reloadComponents: v,
                isCreateTableMode: ae,
                isSyncTableMode: Pe,
                updateCreateTableMode: Q,
                openDeleteModal: Le,
                setOpenDeleteModal: le,
                generateRebuildScript: ye
              }
            ) })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ r(
      Ae,
      {
        open: je,
        onClose: ge,
        maxWidth: "sm",
        fullWidth: !0,
        PaperProps: {
          sx: { borderRadius: 3, p: 1 }
        },
        children: [
          /* @__PURE__ */ r(Re, { sx: { fontWeight: 700, pb: 1 }, children: [
            "Sync a Table",
            /* @__PURE__ */ e(C, { variant: "body2", color: "text.secondary", children: "Select an existing database table to sync with the mobile app." })
          ] }),
          /* @__PURE__ */ e(Ne, { children: /* @__PURE__ */ e(
            Cn,
            {
              options: f.filter((n) => !d.includes(n)),
              getOptionLabel: (n) => n,
              value: j,
              onChange: (n, t) => Z(t),
              renderInput: (n) => /* @__PURE__ */ e(
                Se,
                {
                  ...n,
                  label: "Table",
                  placeholder: "Search and select a table...",
                  size: "small",
                  sx: { mt: 1 }
                }
              )
            }
          ) }),
          /* @__PURE__ */ r(ze, { sx: { px: 3, pb: 2 }, children: [
            /* @__PURE__ */ e(
              M,
              {
                onClick: ge,
                variant: "outlined",
                size: "small",
                sx: { borderRadius: 2, textTransform: "none" },
                children: "Cancel"
              }
            ),
            /* @__PURE__ */ e(
              M,
              {
                variant: "contained",
                size: "small",
                onClick: () => Ve(),
                disabled: !j,
                sx: { borderRadius: 2, textTransform: "none", boxShadow: "none" },
                children: "Sync Table"
              }
            )
          ] })
        ]
      }
    ),
    /* @__PURE__ */ e(
      _e,
      {
        open: Qe,
        onClose: () => ee(!1),
        summaryData: me,
        onApply: tn,
        applying: Ue,
        migrationVersions: He,
        unifiedMigrationScript: ne,
        onUnifiedScriptChange: rn
      }
    )
  ] });
}
An.propTypes = {
  tableList: b.any,
  tablesInfo: b.any,
  allTableList: b.any,
  allTablesInfo: b.any,
  formSubmitted: b.bool,
  reloadComponents: b.any
};
export {
  An as default
};
//# sourceMappingURL=TableList-DYwotUDO.js.map
