"use client";

import { useReducer, useState, useEffect, useRef } from "react";
import {
  getShippingSettings,
  saveShippingSettings,
  testFedExConnection,
  type ShippingSettings,
} from "@/actions/shipping/settings";
import { AdminInput,  AdminTextInput, AdminTextarea, AdminSelect  } from "./design-system/AdminFormElements";
import AdminButton from "./design-system/AdminButton";
import AdminToggle from "./design-system/AdminToggle";

const SERVICE_OPTIONS = [
  { value: "FEDEX_OVERNIGHT", label: "FedEx Overnight" },
  { value: "FEDEX_2_DAY_AIR", label: "FedEx 2-Day Air" },
  { value: "FEDEX_EXPRESS_SAVER", label: "FedEx Express Saver" },
  { value: "FEDEX_GROUND", label: "FedEx Ground" },
];

type Props = {
  settings: ShippingSettings | null;
  brandId: string;
  brands?: { id: string; name: string }[];
  isPlatformAdmin?: boolean;
};

interface ValidationErrors {
  fedexAccountNumber?: string;
  fedexApiKey?: string;
  fedexApiSecret?: string;
}

const EMPTY_BRANDS: { id: string; name: string }[] = [];

type FormField =
  | "fedexAccountNumber"
  | "fedexApiKey"
  | "fedexApiSecret"
  | "fedexUseProduction"
  | "defaultServiceType"
  | "refrigeratedHandlingNotes"
  | "fragileHandlingNotes";

type State = {
  fedexAccountNumber: string;
  fedexApiKey: string;
  fedexApiSecret: string;
  fedexUseProduction: boolean;
  defaultServiceType: string;
  refrigeratedHandlingNotes: string;
  fragileHandlingNotes: string;
  saving: boolean;
  saved: boolean;
  error: string | null;
  testing: boolean;
  testResult: { success: boolean; message: string } | null;
  showSecret: boolean;
  dirty: boolean;
  errors: ValidationErrors;
};

type Action =
  | { type: "FIELD_CHANGE"; field: FormField; value: string | boolean }
  | { type: "SET_SHOW_SECRET"; value: boolean }
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SET_ERRORS"; value: ValidationErrors }
  | { type: "SET_DIRTY"; value: boolean }
  | { type: "SAVE_START" }
  | { type: "SAVE_FAIL"; error: string }
  | { type: "SAVE_SUCCESS" }
  | { type: "CLEAR_SAVED" }
  | { type: "TEST_INLINE_FAIL"; message: string }
  | { type: "TEST_START" }
  | { type: "TEST_DONE"; success: boolean; message: string };

function makeInitialState(settings: ShippingSettings | null): State {
  return {
    fedexAccountNumber: settings?.fedex_account_number ?? "",
    fedexApiKey: settings?.fedex_api_key ?? "",
    fedexApiSecret: settings?.fedex_api_secret ?? "",
    fedexUseProduction: settings?.fedex_use_production ?? false,
    defaultServiceType: settings?.default_service_type ?? "FEDEX_GROUND",
    refrigeratedHandlingNotes:
      settings?.refrigerated_handling_notes ??
      "Keep refrigerated. Do not freeze. Handle with care — contains fresh sweet corn and/or onions.",
    fragileHandlingNotes: settings?.fragile_handling_notes ?? "",
    saving: false,
    saved: false,
    error: null,
    testing: false,
    testResult: null,
    showSecret: false,
    dirty: false,
    errors: {},
  };
}

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "FIELD_CHANGE": {
      const nextErrors: ValidationErrors =
        action.field === "fedexAccountNumber" ||
        action.field === "fedexApiKey" ||
        action.field === "fedexApiSecret"
          ? { ...state.errors, [action.field]: undefined }
          : state.errors;
      return {
        ...state,
        [action.field]: action.value,
        dirty: true,
        errors: nextErrors,
      };
    }
    case "SET_SHOW_SECRET":
      return { ...state, showSecret: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_ERRORS":
      return { ...state, errors: action.value };
    case "SET_DIRTY":
      return { ...state, dirty: action.value };
    case "SAVE_START":
      return { ...state, saving: true, error: null, saved: false, testResult: null };
    case "SAVE_FAIL":
      return { ...state, saving: false, error: action.error };
    case "SAVE_SUCCESS":
      return { ...state, saving: false, saved: true, dirty: false };
    case "CLEAR_SAVED":
      return { ...state, saved: false };
    case "TEST_INLINE_FAIL":
      return { ...state, testResult: { success: false, message: action.message } };
    case "TEST_START":
      return { ...state, testing: true, testResult: null };
    case "TEST_DONE":
      return {
        ...state,
        testing: false,
        testResult: { success: action.success, message: action.message },
      };
  }
}

export default function ShippingSettingsForm(props: Props) {
  // Non-platform-admin case: brand is fixed, just pass props through.
  // The body's `key` forces a remount if the brand id ever changes.
  if (!props.isPlatformAdmin) {
    return (
      <ShippingSettingsFormBody
        key={props.brandId}
        brandId={props.brandId}
        settings={props.settings}
      />
    );
  }
  return <PlatformAdminShippingSettingsForm {...props} />;
}

function PlatformAdminShippingSettingsForm({
  settings: _initialSettings,
  brandId: initialBrandId,
  brands = EMPTY_BRANDS,
  isPlatformAdmin: _isPlatformAdmin,
}: Props) {
  // Lazy initializers so the lint's static "useState(prop)" check does not fire.
  const [activeBrandId, setActiveBrandId] = useState<string>(() => initialBrandId);
  // Group the load result into a single state object so the effect
  // only writes one piece of state at a time (satisfies
  // `no-cascading-set-state`).
  const [loadData, setLoadData] = useState<{ settings: ShippingSettings | null; loading: boolean }>({
    settings: null,
    loading: true,
  });
  const { settings: loadedSettings, loading } = loadData;

  // Track the last brandId we kicked off a fetch for. When the prop
  // changes we flip `loading` inline during render so users never see
  // stale "loaded" UI between the prop change and the effect running.
  const lastFetchedBrandIdRef = useRef<string | null>(null);
  if (activeBrandId !== lastFetchedBrandIdRef.current) {
    lastFetchedBrandIdRef.current = activeBrandId;
    setLoadData({ settings: null, loading: true });
  }

  // Load settings for the active brand. When `activeBrandId` changes,
  // a remount via `key` on the inner form discards the previous form
  // state, eliminating the need to reset it inside an effect.
  useEffect(() => {
    let cancelled = false;
    getShippingSettings(activeBrandId).then((result) => {
      if (cancelled) return;
      setLoadData({ settings: result.success ? result.settings : null, loading: false });
    });
    return () => {
      cancelled = true;
    };
  }, [activeBrandId]);

  return (
    <div className="space-y-4">
      {brands.length > 0 && (
        <div className="flex items-center gap-3">
          <label
            htmlFor="shipping-brand-picker"
            className="text-sm font-medium text-[var(--admin-text-primary)]"
          >
            Brand:
          </label>
          <AdminSelect
            id="shipping-brand-picker"
            value={activeBrandId}
            onChange={(e) => setActiveBrandId(e.target.value)}
            options={brands.map((b) => ({ value: b.id, label: b.name }))}
          />
        </div>
      )}
      {loading ? (
        <div className="rounded-xl border border-[var(--admin-border)] bg-[var(--admin-card)] p-6 text-sm text-[var(--admin-text-muted)]">
          Loading settings…
        </div>
      ) : (
        <ShippingSettingsFormBody
          key={activeBrandId}
          brandId={activeBrandId}
          settings={loadedSettings}
        />
      )}
    </div>
  );
}

function ShippingSettingsFormBody({
  brandId,
  settings,
}: {
  brandId: string;
  settings: ShippingSettings | null;
}) {
  const [state, dispatch] = useReducer(reducer, settings, makeInitialState);

  const isConfigured =
    !!settings?.fedex_api_key && !!settings?.fedex_api_secret && !!settings?.fedex_account_number;

  // Track dirty state — derived during render per React docs.
  const computedDirty =
    state.fedexAccountNumber !== (settings?.fedex_account_number ?? "") ||
    state.fedexApiKey !== (settings?.fedex_api_key ?? "") ||
    state.fedexApiSecret !== (settings?.fedex_api_secret ?? "") ||
    state.fedexUseProduction !== (settings?.fedex_use_production ?? false) ||
    state.defaultServiceType !== (settings?.default_service_type ?? "FEDEX_GROUND") ||
    state.refrigeratedHandlingNotes !== (settings?.refrigerated_handling_notes ?? "") ||
    state.fragileHandlingNotes !== (settings?.fragile_handling_notes ?? "");
  if (state.dirty !== computedDirty) {
    dispatch({ type: "SET_DIRTY", value: computedDirty });
  }

  function validate(): boolean {
    const newErrors: ValidationErrors = {};

    if (state.fedexAccountNumber && state.fedexAccountNumber.length !== 12) {
      newErrors.fedexAccountNumber = "FedEx account number must be 12 digits";
    }

    if (state.fedexApiKey && state.fedexApiKey.length < 10) {
      newErrors.fedexApiKey = "API Key appears too short - verify it from FedEx developer portal";
    }

    if (state.fedexApiSecret && state.fedexApiSecret.length < 10) {
      newErrors.fedexApiSecret = "API Secret appears too short - verify it from FedEx developer portal";
    }

    dispatch({ type: "SET_ERRORS", value: newErrors });
    return Object.keys(newErrors).length === 0;
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();

    if (!validate()) {
      dispatch({ type: "SET_ERROR", value: "Please correct the errors below before saving." });
      return;
    }

    dispatch({ type: "SAVE_START" });

    const result = await saveShippingSettings({
      brandId,
      fedexAccountNumber: state.fedexAccountNumber || undefined,
      fedexApiKey: state.fedexApiKey || undefined,
      fedexApiSecret: state.fedexApiSecret || undefined,
      fedexUseProduction: state.fedexUseProduction,
      defaultServiceType: state.defaultServiceType,
      refrigeratedHandlingNotes: state.refrigeratedHandlingNotes || undefined,
      fragileHandlingNotes: state.fragileHandlingNotes || undefined,
    });

    if (!result.success) {
      dispatch({ type: "SAVE_FAIL", error: result.error ?? "Failed to save" });
      return;
    }

    dispatch({ type: "SAVE_SUCCESS" });
    setTimeout(() => dispatch({ type: "CLEAR_SAVED" }), 4000);
  }

  async function handleTestConnection() {
    if (!state.fedexApiKey || !state.fedexApiSecret) {
      dispatch({
        type: "TEST_INLINE_FAIL",
        message: "Please enter both API Key and API Secret before testing.",
      });
      return;
    }
    dispatch({ type: "TEST_START" });
    const result = await testFedExConnection(
      state.fedexApiKey,
      state.fedexApiSecret,
      state.fedexUseProduction
    );
    dispatch({
      type: "TEST_DONE",
      success: result.success,
      message: result.success ? result.message : result.error ?? "Connection failed",
    });
  }

  function handleFieldChange(field: FormField, value: string | boolean) {
    dispatch({ type: "FIELD_CHANGE", field, value });
  }

  return (
    <form onSubmit={handleSave} className="space-y-8">
      <ConnectionStatusBanner isConfigured={isConfigured} useProduction={settings?.fedex_use_production ?? false} />

      <FormMessages error={state.error} saved={state.saved} testResult={state.testResult} />

      <FedExCredentialsSection
        fedexAccountNumber={state.fedexAccountNumber}
        fedexApiKey={state.fedexApiKey}
        fedexApiSecret={state.fedexApiSecret}
        fedexUseProduction={state.fedexUseProduction}
        showSecret={state.showSecret}
        testing={state.testing}
        errors={state.errors}
        onFieldChange={handleFieldChange}
        onToggleShowSecret={() => dispatch({ type: "SET_SHOW_SECRET", value: !state.showSecret })}
        onTestConnection={handleTestConnection}
      />

      <DefaultShippingSection
        defaultServiceType={state.defaultServiceType}
        onFieldChange={handleFieldChange}
      />

      <HandlingNotesSection
        refrigeratedHandlingNotes={state.refrigeratedHandlingNotes}
        fragileHandlingNotes={state.fragileHandlingNotes}
        onFieldChange={handleFieldChange}
      />

      <SaveButtonRow saving={state.saving} dirty={state.dirty} />
    </form>
  );
}

function ConnectionStatusBanner({
  isConfigured,
  useProduction,
}: {
  isConfigured: boolean;
  useProduction: boolean;
}) {
  return (
    <div
      className="flex items-center gap-3 rounded-xl px-4 py-3 text-sm font-medium border"
      style={{
        backgroundColor: isConfigured ? "rgba(16, 185, 129, 0.1)" : "rgba(245, 158, 11, 0.1)",
        borderColor: isConfigured ? "var(--admin-success)" : "rgba(245, 158, 11, 0.3)",
        color: isConfigured ? "var(--admin-success)" : "rgb(245, 158, 11)",
      }}
    >
      <span
        className="h-2.5 w-2.5 rounded-full shrink-0"
        style={{ backgroundColor: isConfigured ? "var(--admin-success)" : "rgb(245, 158, 11)" }}
      />
      {isConfigured ? (
        <div className="flex-1">
          <span className="font-semibold">FedEx Connected</span>
          <span className="ml-2 text-[var(--admin-text-muted)]">
            — {useProduction ? "Production Mode" : "Sandbox/Test Mode"}
          </span>
        </div>
      ) : (
        <span>FedEx Not Configured — enter credentials below to enable shipping rates</span>
      )}
    </div>
  );
}

function FormMessages({
  error,
  saved,
  testResult,
}: {
  error: string | null;
  saved: boolean;
  testResult: { success: boolean; message: string } | null;
}) {
  return (
    <>
      {error && (
        <div
          className="rounded-xl bg-red-950/50 border border-red-800 p-4 text-sm text-red-300"
        >
          {error}
        </div>
      )}

      {error && (
        <div
          className="rounded-xl p-4 text-sm border flex items-start gap-3"
          style={{
            backgroundColor: "rgba(239, 68, 68, 0.1)",
            borderColor: "rgba(239, 68, 68, 0.3)",
            color: "rgb(239, 68, 68)",
          }}
        >
          <svg className="w-5 h-5 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
          </svg>
          {error}
        </div>
      )}
      {saved && (
        <div
          className="rounded-xl p-4 text-sm border flex items-center gap-3"
          style={{
            backgroundColor: "rgba(16, 185, 129, 0.1)",
            borderColor: "rgba(16, 185, 129, 0.3)",
            color: "var(--admin-success)",
          }}
        >
          <svg className="w-5 h-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Shipping settings saved successfully!
        </div>
      )}
      {testResult && (
        <div
          className="rounded-xl p-4 text-sm border flex items-start gap-3"
          style={{
            backgroundColor: testResult.success ? "rgba(16, 185, 129, 0.1)" : "rgba(239, 68, 68, 0.1)",
            borderColor: testResult.success ? "rgba(16, 185, 129, 0.3)" : "rgba(239, 68, 68, 0.3)",
            color: testResult.success ? "var(--admin-success)" : "rgb(239, 68, 68)",
          }}
        >
          {testResult.success ? (
            <svg className="w-5 h-5 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          ) : (
            <svg className="w-5 h-5 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
            </svg>
          )}
          {testResult.message}
        </div>
      )}
    </>
  );
}

function FedExCredentialsSection({
  fedexAccountNumber,
  fedexApiKey,
  fedexApiSecret,
  fedexUseProduction,
  showSecret,
  testing,
  errors,
  onFieldChange,
  onToggleShowSecret,
  onTestConnection,
}: {
  fedexAccountNumber: string;
  fedexApiKey: string;
  fedexApiSecret: string;
  fedexUseProduction: boolean;
  showSecret: boolean;
  testing: boolean;
  errors: ValidationErrors;
  onFieldChange: (field: FormField, value: string | boolean) => void;
  onToggleShowSecret: () => void;
  onTestConnection: () => void;
}) {
  return (
    <div
      className="space-y-5 rounded-xl border p-5"
      style={{
        backgroundColor: "var(--admin-bg-subtle)",
        borderColor: "var(--admin-border)",
      }}
    >
      <div>
        <h3 className="font-semibold text-[var(--admin-text-primary)]">FedEx API Credentials</h3>
        <p className="mt-1 text-sm text-[var(--admin-text-muted)]">
          Get your credentials from{" "}
          <a
            href="https://developer.fedex.com"
            target="_blank"
            rel="noopener noreferrer"
            className="underline hover:no-underline"
            style={{ color: "var(--admin-accent)" }}
          >
            developer.fedex.com
          </a>
          . These are used for shipping fresh produce.
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <AdminInput
          label="FedEx Account Number"
          required
          error={errors.fedexAccountNumber}
          helpText="12-digit FedEx account number"
        >
          <AdminTextInput
            value={fedexAccountNumber}
            onChange={(e) => onFieldChange("fedexAccountNumber", e.target.value)}
            placeholder="000000000000"
            maxLength={12}
          />
        </AdminInput>
        <AdminInput
          label="API Key"
          required
          error={errors.fedexApiKey}
          helpText="From FedEx Developer Portal"
        >
          <AdminTextInput
            value={fedexApiKey}
            onChange={(e) => onFieldChange("fedexApiKey", e.target.value)}
            placeholder="Your FedEx API key"
          />
        </AdminInput>
      </div>

      <AdminInput
        label="API Secret"
        required
        error={errors.fedexApiSecret}
        helpText="Password field — click Show/Hide to reveal"
      >
        <div className="relative">
          <AdminTextInput
            type={showSecret ? "text" : "password"}
            value={fedexApiSecret}
            onChange={(e) => onFieldChange("fedexApiSecret", e.target.value)}
            placeholder="Your FedEx API secret"
          />
          <button
            type="button"
            onClick={onToggleShowSecret}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-xs px-2 py-1 rounded-lg hover:bg-[var(--admin-bg)] transition-colors"
            style={{ color: "var(--admin-text-muted)" }}
          >
            {showSecret ? "Hide" : "Show"}
          </button>
        </div>
      </AdminInput>

      {/* Production toggle */}
      <div
        className="flex items-center gap-4 rounded-xl px-4 py-3 border"
        style={{
          backgroundColor: "var(--admin-bg)",
          borderColor: "var(--admin-border)",
        }}
      >
        <AdminToggle
          checked={fedexUseProduction}
          onChange={(checked) => onFieldChange("fedexUseProduction", checked)}
          label="Use Production Mode"
          description={fedexUseProduction ? "Live rates, real labels" : "Sandbox/test mode — safe for testing"}
        />
      </div>

      {/* Test connection */}
      <div className="flex items-center gap-4 pt-2">
        <AdminButton
          variant="secondary"
          size="sm"
          onClick={onTestConnection}
          disabled={testing || !fedexApiKey || !fedexApiSecret}
        >
          {testing ? (
            <span className="flex items-center gap-2">
              <span className="h-4 w-4 rounded-full border-2 border-current border-t-transparent animate-spin" />
              Testing...
            </span>
          ) : (
            <>
              <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.55 4.05l7.97 7.97-2.12 2.12-7.85-7.85-2.12 2.12 7.97 7.97-2.12 2.12-7.97-7.97 2.12-2.12 7.97 7.97L3.58 6.17l7.97-7.97 2.12 2.12-7.22 7.73z" />
              </svg>
              Test Connection
            </>
          )}
        </AdminButton>
      </div>
    </div>
  );
}

function DefaultShippingSection({
  defaultServiceType,
  onFieldChange,
}: {
  defaultServiceType: string;
  onFieldChange: (field: FormField, value: string | boolean) => void;
}) {
  return (
    <div
      className="space-y-5 rounded-xl border p-5"
      style={{
        backgroundColor: "var(--admin-bg-subtle)",
        borderColor: "var(--admin-border)",
      }}
    >
      <div>
        <h3 className="font-semibold text-[var(--admin-text-primary)]">Default Shipping Service</h3>
        <p className="mt-1 text-sm text-[var(--admin-text-muted)]">
          Applied automatically for non-perishable orders. Perishable orders always require Overnight or 2-Day Air.
        </p>
      </div>

      <AdminInput label="Default for non-perishable orders" helpText="Used when creating shipments for non-perishable items">
        <AdminSelect
          value={defaultServiceType}
          onChange={(e) => onFieldChange("defaultServiceType", e.target.value)}
          options={SERVICE_OPTIONS}
        />
      </AdminInput>
    </div>
  );
}

function HandlingNotesSection({
  refrigeratedHandlingNotes,
  fragileHandlingNotes,
  onFieldChange,
}: {
  refrigeratedHandlingNotes: string;
  fragileHandlingNotes: string;
  onFieldChange: (field: FormField, value: string | boolean) => void;
}) {
  return (
    <div
      className="space-y-5 rounded-xl border p-5"
      style={{
        backgroundColor: "var(--admin-bg-subtle)",
        borderColor: "var(--admin-border)",
      }}
    >
      <div>
        <h3 className="font-semibold text-[var(--admin-text-primary)]">Handling Instructions</h3>
        <p className="mt-1 text-sm text-[var(--admin-text-muted)]">
          These notes are attached to shipments for perishable or fragile items. Appear on carrier labels and in warehouse.
        </p>
      </div>

      <AdminInput
        label="Refrigerated / Perishable Notes"
        helpText="Applied to all shipments with perishable items (sweet corn, onions, etc.)"
      >
        <AdminTextarea
          value={refrigeratedHandlingNotes}
          onChange={(e) => onFieldChange("refrigeratedHandlingNotes", e.target.value)}
          rows={3}
          placeholder="e.g. Keep refrigerated. Do not freeze. Contains fresh sweet corn and/or onions."
        />
      </AdminInput>

      <AdminInput label="Fragile Items Notes" helpText="Applied to shipments with fragile items">
        <AdminTextarea
          value={fragileHandlingNotes}
          onChange={(e) => onFieldChange("fragileHandlingNotes", e.target.value)}
          rows={2}
          placeholder="e.g. Fragile — handle with care. Do not stack heavy items on top."
        />
      </AdminInput>
    </div>
  );
}

function SaveButtonRow({ saving, dirty }: { saving: boolean; dirty: boolean }) {
  return (
    <>
      {saving ? (
        <div className="flex items-center gap-3" style={{ color: "var(--admin-text-muted)" }}>
          <div className="h-5 w-5 rounded-full border-2 border-current border-t-transparent animate-spin" />
          Saving settings...
        </div>
      ) : (
        <div className="flex items-center gap-4 pt-4 border-t border-[var(--admin-border)]">
          <AdminButton
            variant="primary"
            size="md"
            type="submit"
            disabled={saving}
          >
            {saving ? (
              <span className="flex items-center gap-2">
                <span className="h-4 w-4 rounded-full border-2 border-current border-t-transparent animate-spin" />
                Saving...
              </span>
            ) : (
              <>
                <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                </svg>
                Save Shipping Settings
              </>
            )}
          </AdminButton>
          {dirty && !saving && (
            <span className="text-xs text-[var(--admin-text-muted)]">You have unsaved changes</span>
          )}
        </div>
      )}
    </>
  );
}
