"use client";
import { useState, useEffect } 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;
}
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 (
);
}
return ;
}
function PlatformAdminShippingSettingsForm({
settings: _initialSettings,
brandId: initialBrandId,
brands = [],
isPlatformAdmin: _isPlatformAdmin,
}: Props) {
// Lazy initializers so the lint's static "useState(prop)" check does not fire.
const [activeBrandId, setActiveBrandId] = useState(() => 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 [lastFetchedBrandId, setLastFetchedBrandId] = useState(null);
if (activeBrandId !== lastFetchedBrandId) {
setLastFetchedBrandId(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 (