import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, useSubmit, useNavigation, useNavigate, useActionData } from "react-router";
import {
  Page,
  Card,
  Text,
  BlockStack,
  FormLayout,
  Select,
  Button,
  Checkbox,
  TextField,
  InlineStack,
  Banner,
} from "@shopify/polaris";
import { useState, useEffect } from "react";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";

const TIMEZONES: { label: string; value: string }[] = [
  // ── UTC ±0 ────────────────────────────────────────────────────────────────
  { label: "UTC ±0 — UTC (Universal)", value: "UTC" },
  { label: "UTC ±0 — London (GMT/BST)", value: "Europe/London" },
  { label: "UTC ±0 — Dublin (GMT/IST)", value: "Europe/Dublin" },
  { label: "UTC ±0 — Lisbon", value: "Europe/Lisbon" },
  { label: "UTC ±0 — Reykjavik", value: "Atlantic/Reykjavik" },
  { label: "UTC ±0 — Accra / Abidjan", value: "Africa/Accra" },
  { label: "UTC ±0 — Dakar (Senegal)", value: "Africa/Dakar" },

  // ── UTC +1 ────────────────────────────────────────────────────────────────
  { label: "UTC +1 — Amsterdam", value: "Europe/Amsterdam" },
  { label: "UTC +1 — Berlin", value: "Europe/Berlin" },
  { label: "UTC +1 — Paris", value: "Europe/Paris" },
  { label: "UTC +1 — Rome", value: "Europe/Rome" },
  { label: "UTC +1 — Madrid", value: "Europe/Madrid" },
  { label: "UTC +1 — Zurich", value: "Europe/Zurich" },
  { label: "UTC +1 — Stockholm", value: "Europe/Stockholm" },
  { label: "UTC +1 — Vienna", value: "Europe/Vienna" },
  { label: "UTC +1 — Warsaw", value: "Europe/Warsaw" },
  { label: "UTC +1 — Brussels", value: "Europe/Brussels" },
  { label: "UTC +1 — Prague", value: "Europe/Prague" },
  { label: "UTC +1 — Copenhagen", value: "Europe/Copenhagen" },
  { label: "UTC +1 — Oslo", value: "Europe/Oslo" },
  { label: "UTC +1 — Budapest", value: "Europe/Budapest" },
  { label: "UTC +1 — Belgrade / Zagreb", value: "Europe/Belgrade" },
  { label: "UTC +1 — Lagos (West Africa)", value: "Africa/Lagos" },
  { label: "UTC +1 — Tunis", value: "Africa/Tunis" },
  { label: "UTC +1 — Algiers", value: "Africa/Algiers" },
  { label: "UTC +1 — Casablanca", value: "Africa/Casablanca" },

  // ── UTC +2 ────────────────────────────────────────────────────────────────
  { label: "UTC +2 — Helsinki", value: "Europe/Helsinki" },
  { label: "UTC +2 — Athens", value: "Europe/Athens" },
  { label: "UTC +2 — Bucharest", value: "Europe/Bucharest" },
  { label: "UTC +2 — Kyiv", value: "Europe/Kyiv" },
  { label: "UTC +2 — Riga / Tallinn / Vilnius", value: "Europe/Riga" },
  { label: "UTC +2 — Sofia", value: "Europe/Sofia" },
  { label: "UTC +2 — Kaliningrad", value: "Europe/Kaliningrad" },
  { label: "UTC +2 — Cairo", value: "Africa/Cairo" },
  { label: "UTC +2 — Johannesburg", value: "Africa/Johannesburg" },
  { label: "UTC +2 — Harare / Lusaka", value: "Africa/Harare" },
  { label: "UTC +2 — Khartoum", value: "Africa/Khartoum" },
  { label: "UTC +2 — Tripoli", value: "Africa/Tripoli" },
  { label: "UTC +2 — Amman (Jordan)", value: "Asia/Amman" },
  { label: "UTC +2 — Beirut", value: "Asia/Beirut" },
  { label: "UTC +2 — Jerusalem / Tel Aviv", value: "Asia/Jerusalem" },
  { label: "UTC +2 — Damascus", value: "Asia/Damascus" },
  { label: "UTC +2 — Nicosia (Cyprus)", value: "Asia/Nicosia" },

  // ── UTC +3 ────────────────────────────────────────────────────────────────
  { label: "UTC +3 — Moscow", value: "Europe/Moscow" },
  { label: "UTC +3 — Istanbul", value: "Europe/Istanbul" },
  { label: "UTC +3 — Minsk", value: "Europe/Minsk" },
  { label: "UTC +3 — Riyadh (Saudi Arabia)", value: "Asia/Riyadh" },
  { label: "UTC +3 — Baghdad", value: "Asia/Baghdad" },
  { label: "UTC +3 — Kuwait City", value: "Asia/Kuwait" },
  { label: "UTC +3 — Doha (Qatar)", value: "Asia/Qatar" },
  { label: "UTC +3 — Manama (Bahrain)", value: "Asia/Bahrain" },
  { label: "UTC +3 — Aden (Yemen)", value: "Asia/Aden" },
  { label: "UTC +3 — Nairobi", value: "Africa/Nairobi" },
  { label: "UTC +3 — Addis Ababa", value: "Africa/Addis_Ababa" },
  { label: "UTC +3 — Dar es Salaam", value: "Africa/Dar_es_Salaam" },
  { label: "UTC +3 — Kampala (Uganda)", value: "Africa/Kampala" },

  // ── UTC +3:30 ─────────────────────────────────────────────────────────────
  { label: "UTC +3:30 — Tehran (Iran)", value: "Asia/Tehran" },

  // ── UTC +4 ────────────────────────────────────────────────────────────────
  { label: "UTC +4 — Dubai (UAE)", value: "Asia/Dubai" },
  { label: "UTC +4 — Muscat (Oman)", value: "Asia/Muscat" },
  { label: "UTC +4 — Baku (Azerbaijan)", value: "Asia/Baku" },
  { label: "UTC +4 — Tbilisi (Georgia)", value: "Asia/Tbilisi" },
  { label: "UTC +4 — Yerevan (Armenia)", value: "Asia/Yerevan" },
  { label: "UTC +4 — Samara", value: "Europe/Samara" },
  { label: "UTC +4 — Port Louis (Mauritius)", value: "Indian/Mauritius" },

  // ── UTC +4:30 ─────────────────────────────────────────────────────────────
  { label: "UTC +4:30 — Kabul (Afghanistan)", value: "Asia/Kabul" },

  // ── UTC +5 ────────────────────────────────────────────────────────────────
  { label: "UTC +5 — Karachi (Pakistan)", value: "Asia/Karachi" },
  { label: "UTC +5 — Tashkent (Uzbekistan)", value: "Asia/Tashkent" },
  { label: "UTC +5 — Dushanbe (Tajikistan)", value: "Asia/Dushanbe" },
  { label: "UTC +5 — Ashgabat (Turkmenistan)", value: "Asia/Ashgabat" },
  { label: "UTC +5 — Yekaterinburg", value: "Asia/Yekaterinburg" },

  // ── UTC +5:30 ─────────────────────────────────────────────────────────────
  { label: "UTC +5:30 — Mumbai / New Delhi (IST)", value: "Asia/Kolkata" },
  { label: "UTC +5:30 — Colombo (Sri Lanka)", value: "Asia/Colombo" },

  // ── UTC +5:45 ─────────────────────────────────────────────────────────────
  { label: "UTC +5:45 — Kathmandu (Nepal)", value: "Asia/Kathmandu" },

  // ── UTC +6 ────────────────────────────────────────────────────────────────
  { label: "UTC +6 — Dhaka (Bangladesh)", value: "Asia/Dhaka" },
  { label: "UTC +6 — Almaty (Kazakhstan)", value: "Asia/Almaty" },
  { label: "UTC +6 — Bishkek (Kyrgyzstan)", value: "Asia/Bishkek" },
  { label: "UTC +6 — Thimphu (Bhutan)", value: "Asia/Thimphu" },
  { label: "UTC +6 — Omsk", value: "Asia/Omsk" },

  // ── UTC +6:30 ─────────────────────────────────────────────────────────────
  { label: "UTC +6:30 — Yangon (Myanmar)", value: "Asia/Yangon" },

  // ── UTC +7 ────────────────────────────────────────────────────────────────
  { label: "UTC +7 — Bangkok (Thailand)", value: "Asia/Bangkok" },
  { label: "UTC +7 — Ho Chi Minh City (Vietnam)", value: "Asia/Ho_Chi_Minh" },
  { label: "UTC +7 — Hanoi (Vietnam)", value: "Asia/Bangkok" },
  { label: "UTC +7 — Jakarta (Indonesia)", value: "Asia/Jakarta" },
  { label: "UTC +7 — Phnom Penh (Cambodia)", value: "Asia/Phnom_Penh" },
  { label: "UTC +7 — Vientiane (Laos)", value: "Asia/Vientiane" },
  { label: "UTC +7 — Novosibirsk / Krasnoyarsk", value: "Asia/Krasnoyarsk" },

  // ── UTC +8 ────────────────────────────────────────────────────────────────
  { label: "UTC +8 — Shanghai / Beijing (China)", value: "Asia/Shanghai" },
  { label: "UTC +8 — Hong Kong", value: "Asia/Hong_Kong" },
  { label: "UTC +8 — Singapore", value: "Asia/Singapore" },
  { label: "UTC +8 — Kuala Lumpur (Malaysia)", value: "Asia/Kuala_Lumpur" },
  { label: "UTC +8 — Manila (Philippines)", value: "Asia/Manila" },
  { label: "UTC +8 — Taipei (Taiwan)", value: "Asia/Taipei" },
  { label: "UTC +8 — Perth (Australia)", value: "Australia/Perth" },
  { label: "UTC +8 — Ulaanbaatar (Mongolia)", value: "Asia/Ulaanbaatar" },
  { label: "UTC +8 — Irkutsk", value: "Asia/Irkutsk" },
  { label: "UTC +8 — Brunei", value: "Asia/Brunei" },

  // ── UTC +8:45 ─────────────────────────────────────────────────────────────
  { label: "UTC +8:45 — Eucla (Australia)", value: "Australia/Eucla" },

  // ── UTC +9 ────────────────────────────────────────────────────────────────
  { label: "UTC +9 — Tokyo (Japan)", value: "Asia/Tokyo" },
  { label: "UTC +9 — Seoul (South Korea)", value: "Asia/Seoul" },
  { label: "UTC +9 — Yakutsk", value: "Asia/Yakutsk" },
  { label: "UTC +9 — Dili (Timor-Leste)", value: "Asia/Dili" },

  // ── UTC +9:30 ─────────────────────────────────────────────────────────────
  { label: "UTC +9:30 — Adelaide (CST/CDT)", value: "Australia/Adelaide" },
  { label: "UTC +9:30 — Darwin", value: "Australia/Darwin" },

  // ── UTC +10 ───────────────────────────────────────────────────────────────
  { label: "UTC +10 — Sydney / Melbourne (AEDT)", value: "Australia/Sydney" },
  { label: "UTC +10 — Brisbane (AEST, no DST)", value: "Australia/Brisbane" },
  { label: "UTC +10 — Hobart", value: "Australia/Hobart" },
  { label: "UTC +10 — Port Moresby (Papua New Guinea)", value: "Pacific/Port_Moresby" },
  { label: "UTC +10 — Guam", value: "Pacific/Guam" },
  { label: "UTC +10 — Vladivostok", value: "Asia/Vladivostok" },

  // ── UTC +10:30 ────────────────────────────────────────────────────────────
  { label: "UTC +10:30 — Lord Howe Island", value: "Australia/Lord_Howe" },

  // ── UTC +11 ───────────────────────────────────────────────────────────────
  { label: "UTC +11 — Noumea (New Caledonia)", value: "Pacific/Noumea" },
  { label: "UTC +11 — Honiara (Solomon Islands)", value: "Pacific/Guadalcanal" },
  { label: "UTC +11 — Port Vila (Vanuatu)", value: "Pacific/Efate" },
  { label: "UTC +11 — Sakhalin", value: "Asia/Sakhalin" },
  { label: "UTC +11 — Magadan", value: "Asia/Magadan" },

  // ── UTC +12 ───────────────────────────────────────────────────────────────
  { label: "UTC +12 — Auckland (New Zealand)", value: "Pacific/Auckland" },
  { label: "UTC +12 — Fiji", value: "Pacific/Fiji" },
  { label: "UTC +12 — Tarawa (Kiribati)", value: "Pacific/Tarawa" },
  { label: "UTC +12 — Majuro (Marshall Islands)", value: "Pacific/Majuro" },
  { label: "UTC +12 — Petropavlovsk-Kamchatsky", value: "Asia/Kamchatka" },

  // ── UTC +12:45 ────────────────────────────────────────────────────────────
  { label: "UTC +12:45 — Chatham Islands (NZ)", value: "Pacific/Chatham" },

  // ── UTC +13 ───────────────────────────────────────────────────────────────
  { label: "UTC +13 — Nuku'alofa (Tonga)", value: "Pacific/Tongatapu" },
  { label: "UTC +13 — Apia (Samoa)", value: "Pacific/Apia" },
  { label: "UTC +13 — Fakaofo (Tokelau)", value: "Pacific/Fakaofo" },

  // ── UTC +14 ───────────────────────────────────────────────────────────────
  { label: "UTC +14 — Kiritimati (Line Islands)", value: "Pacific/Kiritimati" },

  // ── UTC −1 ────────────────────────────────────────────────────────────────
  { label: "UTC −1 — Azores", value: "Atlantic/Azores" },
  { label: "UTC −1 — Cape Verde", value: "Atlantic/Cape_Verde" },

  // ── UTC −2 ────────────────────────────────────────────────────────────────
  { label: "UTC −2 — Fernando de Noronha", value: "America/Noronha" },
  { label: "UTC −2 — South Georgia", value: "Atlantic/South_Georgia" },

  // ── UTC −3 ────────────────────────────────────────────────────────────────
  { label: "UTC −3 — Greenland", value: "America/Godthab" },

  // ── UTC −3:30 ─────────────────────────────────────────────────────────────
  { label: "UTC −3:30 — St. John's, Newfoundland", value: "America/St_Johns" },

  // ── UTC −4 ────────────────────────────────────────────────────────────────
  { label: "UTC −4 — Puerto Rico (AST, no DST)", value: "America/Puerto_Rico" },
  { label: "UTC −4 — US Virgin Islands", value: "America/St_Thomas" },
  { label: "UTC −4 — Halifax, NS (AST/ADT)", value: "America/Halifax" },

  // ── UTC −5 ────────────────────────────────────────────────────────────────
  { label: "UTC −5 — New York (EST/EDT)", value: "America/New_York" },
  { label: "UTC −5 — Detroit", value: "America/Detroit" },
  { label: "UTC −5 — Toronto", value: "America/Toronto" },
  { label: "UTC −5 — Indiana (no DST)", value: "America/Indiana/Indianapolis" },
  { label: "UTC −5 — Panama City (no DST)", value: "America/Panama" },

  // ── UTC −6 ────────────────────────────────────────────────────────────────
  { label: "UTC −6 — Chicago (CST/CDT)", value: "America/Chicago" },
  { label: "UTC −6 — Dallas / Houston", value: "America/Chicago" },
  { label: "UTC −6 — Winnipeg", value: "America/Winnipeg" },
  { label: "UTC −6 — Mexico City", value: "America/Mexico_City" },

  // ── UTC −7 ────────────────────────────────────────────────────────────────
  { label: "UTC −7 — Denver (MST/MDT)", value: "America/Denver" },
  { label: "UTC −7 — Salt Lake City", value: "America/Denver" },
  { label: "UTC −7 — Phoenix (MST, no DST)", value: "America/Phoenix" },
  { label: "UTC −7 — Calgary / Edmonton", value: "America/Edmonton" },

  // ── UTC −8 ────────────────────────────────────────────────────────────────
  { label: "UTC −8 — Los Angeles (PST/PDT)", value: "America/Los_Angeles" },
  { label: "UTC −8 — Seattle / Portland", value: "America/Los_Angeles" },
  { label: "UTC −8 — Las Vegas", value: "America/Los_Angeles" },
  { label: "UTC −8 — Vancouver", value: "America/Vancouver" },

  // ── UTC −9 ────────────────────────────────────────────────────────────────
  { label: "UTC −9 — Anchorage (Alaska)", value: "America/Anchorage" },
  { label: "UTC −9 — Juneau (Alaska)", value: "America/Juneau" },

  // ── UTC −9:30 ─────────────────────────────────────────────────────────────
  { label: "UTC −9:30 — Marquesas Islands", value: "Pacific/Marquesas" },

  // ── UTC −10 ───────────────────────────────────────────────────────────────
  { label: "UTC −10 — Honolulu (Hawaii)", value: "Pacific/Honolulu" },
  { label: "UTC −10 — Tahiti (French Polynesia)", value: "Pacific/Tahiti" },
  { label: "UTC −10 — Rarotonga (Cook Islands)", value: "Pacific/Rarotonga" },

  // ── UTC −11 ───────────────────────────────────────────────────────────────
  { label: "UTC −11 — Pago Pago (American Samoa)", value: "Pacific/Pago_Pago" },
  { label: "UTC −11 — Niue", value: "Pacific/Niue" },

  // ── UTC −12 ───────────────────────────────────────────────────────────────
  { label: "UTC −12 — Baker Island / Howland Island", value: "Etc/GMT+12" },
];

const INTERVALS = [
  { label: "1 hour", value: "60" },
  { label: "2 hours", value: "120" },
  { label: "6 hours", value: "360" },
  { label: "12 hours", value: "720" },
  { label: "1 day", value: "1440" },
];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { session } = await authenticate.admin(request);
  const settings = await prisma.appSettings.findUnique({ where: { shop: session.shop } });
  // widgetHideHours may not exist in the Prisma result yet if migration is pending —
  // read it directly via raw SQL so the page always loads correctly.
  let widgetHideHours = 24;
  try {
    const rows = await prisma.$queryRaw<{ widgetHideHours: number }[]>`
      SELECT "widgetHideHours" FROM "AppSettings" WHERE "shop" = ${session.shop} LIMIT 1
    `;
    if (rows.length > 0) widgetHideHours = rows[0].widgetHideHours;
  } catch { /* column not yet created */ }
  return { settings, widgetHideHours };
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const { session } = await authenticate.admin(request);
  const shop = session.shop;
  const formData = await request.formData();

  const timezone = String(formData.get("timezone"));
  const intervalMinutes = Number(formData.get("intervalMinutes"));

  // Validate timezone against IANA list before saving
  try {
    Intl.DateTimeFormat(undefined, { timeZone: timezone });
  } catch {
    return { ok: false, error: "Invalid timezone. Please select a valid option." };
  }

  // Validate interval
  const validIntervals = [60, 120, 360, 720, 1440];
  if (!validIntervals.includes(intervalMinutes)) {
    return { ok: false, error: "Invalid interval value." };
  }

  const widgetHideHours = Number(formData.get("widgetHideHours"));
  if (!Number.isInteger(widgetHideHours) || widgetHideHours < 1 || widgetHideHours > 168) {
    return { ok: false, error: "Widget hide hours must be between 1 and 168." };
  }

  // Save core settings first — always works regardless of migration state
  const baseData = {
    timezone,
    intervalMinutes,
    autoAdvance: formData.get("autoAdvance") === "true",
    showNextDeals: formData.get("showNextDeals") === "true",
  };

  await prisma.appSettings.upsert({
    where: { shop },
    create: { shop, ...baseData },
    update: baseData,
  });

  // Save widgetHideHours via raw SQL so it works even if Prisma client
  // hasn't been regenerated yet after the schema migration.
  try {
    await prisma.$executeRaw`
      UPDATE "AppSettings" SET "widgetHideHours" = ${widgetHideHours} WHERE "shop" = ${shop}
    `;
  } catch {
    // Column not yet created — migration pending; will save after next deploy+setup.
  }

  return { ok: true, saved: true };
};

export default function Settings() {
  const { settings, widgetHideHours: initialWidgetHideHours } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const submit = useSubmit();
  const navigation = useNavigation();
  const navigate = useNavigate();
  const [banner, setBanner] = useState<{ tone: "success" | "critical"; message: string } | null>(null);

  // Show banner after save completes, auto-dismiss after 4 seconds
  useEffect(() => {
    if (navigation.state === "idle" && actionData?.ok) {
      setBanner({ tone: "success", message: "Settings saved successfully!" });
      const t = setTimeout(() => setBanner(null), 4000);
      return () => clearTimeout(t);
    }
    if (navigation.state === "idle" && actionData?.error) {
      setBanner({ tone: "critical", message: actionData.error });
    }
  }, [navigation.state, actionData]);

  const [form, setForm] = useState({
    timezone: settings?.timezone ?? "UTC",
    intervalMinutes: String(settings?.intervalMinutes ?? 60),
    autoAdvance: settings?.autoAdvance ?? false,
    showNextDeals: settings?.showNextDeals ?? true,
    widgetHideHours: String(initialWidgetHideHours ?? 24),
  });

  const handleSave = () => {
    const fd = new FormData();
    fd.append("timezone", form.timezone);
    fd.append("intervalMinutes", form.intervalMinutes);
    fd.append("autoAdvance", String(form.autoAdvance));
    fd.append("showNextDeals", String(form.showNextDeals));
    fd.append("widgetHideHours", form.widgetHideHours);
    submit(fd, { method: "post" });
  };

  return (
    <Page title="Settings" backAction={{ content: "Dashboard", onAction: () => navigate("/app") }}>
      <BlockStack gap="500">
        {banner && (
          <div style={{ position: "absolute", top: "20px", left: '50%', transform: "translate(-50%, 0)" }}>
            <Banner tone={banner.tone} onDismiss={() => setBanner(null)}>
              {banner.message}
            </Banner>
          </div>
        )}
        <Card>
          <BlockStack gap="400">
            <Text as="h2" variant="headingMd">Time Configuration</Text>
            <FormLayout>
              <Select
                label="Timezone"
                options={TIMEZONES}
                value={form.timezone}
                onChange={(v) => setForm({ ...form, timezone: v })}
                helpText="All deal times in the schedule are interpreted in this timezone"
              />
              <Select
                label="Default Deal Interval"
                options={INTERVALS}
                value={form.intervalMinutes}
                onChange={(v) => setForm({ ...form, intervalMinutes: v })}
                helpText="How long each deal runs by default"
              />
            </FormLayout>
          </BlockStack>
        </Card>

        <Card>
          <BlockStack gap="400">
            <Text as="h2" variant="headingMd">Deal Behavior</Text>
            <FormLayout>
              {/* Auto-advance: hidden until the feature is fully implemented */}
              {/* <Checkbox
                label="Auto-advance to next deal when sold out"
                checked={form.autoAdvance}
                onChange={(v) => setForm({ ...form, autoAdvance: v })}
                helpText="When enabled, the next deal starts immediately once current stock hits zero (shifts all subsequent times)"
              /> */}
              <Checkbox
                label="Show upcoming deals on storefront"
                checked={form.showNextDeals}
                onChange={(v) => setForm({ ...form, showNextDeals: v })}
                helpText="Display the next 2–3 scheduled deals below the current one"
              />
            </FormLayout>
          </BlockStack>
        </Card>

        <Card>
          <BlockStack gap="400">
            <BlockStack gap="100">
              <Text as="h2" variant="headingMd">Widget Visibility</Text>
              <Text as="p" variant="bodyMd" tone="subdued">
                Controls when the storefront widget hides itself during idle periods between deals.
              </Text>
            </BlockStack>
            <FormLayout>
              <InlineStack gap="200" blockAlign="end">
                <div style={{ flex: "0 0 140px" }}>
                  <TextField
                    label="Hide widget after"
                    type="number"
                    value={form.widgetHideHours}
                    onChange={(v) => {
                      // Allow only positive integers up to 168
                      const n = parseInt(v, 10);
                      if (v === "" || (Number.isInteger(n) && n >= 1 && n <= 168)) {
                        setForm({ ...form, widgetHideHours: v });
                      }
                    }}
                    suffix="hours"
                    min={1}
                    max={168}
                    autoComplete="off"
                  />
                </div>
              </InlineStack>
              <Text as="p" variant="bodySm" tone="subdued">
                If no deal is scheduled to start within this window, the widget hides itself entirely on the storefront.
                If the next deal starts within this window, the widget shows a "Coming Soon" countdown instead.
                Set to <strong>1</strong> to only show the widget during active deals. Default: <strong>24 hours</strong>.
              </Text>
            </FormLayout>
          </BlockStack>
        </Card>

        <Button variant="primary" onClick={handleSave} loading={navigation.state === "submitting"}>
          Save Settings
        </Button>
      </BlockStack>
    </Page>
  );
}
