import { notificationsApi } from "@/lib/api/notifications";
import { requireServerToken } from "@/lib/auth/server";
import type { NotificationSettings } from "@/lib/api/types";
import { saveNotificationSettings } from "./actions";
import SaveButton from "./SaveButton";

type PageProps = {
  searchParams: Promise<{ saved?: string; error?: string }>;
};

const FIELDS: Array<{ key: keyof NotificationSettings; label: string; description: string }> = [
  {
    key: "notify_new_order_enquiry",
    label: "New orders & enquiries",
    description: "Get notified when buyers place orders or send enquiries.",
  },
  {
    key: "notify_seller_reply",
    label: "Seller replies",
    description: "Get notified when sellers respond to your enquiries.",
  },
  {
    key: "notify_booking_confirmed",
    label: "Booking confirmations",
    description: "Get notified when transport bookings are confirmed.",
  },
];

async function loadSettings(token: string): Promise<NotificationSettings> {
  try {
    return await notificationsApi.getSettings(token);
  } catch {
    return {
      notify_new_order_enquiry: false,
      notify_seller_reply: false,
      notify_booking_confirmed: false,
    };
  }
}

/**
 * Server-rendered form. The toggles are uncontrolled `defaultChecked`
 * checkboxes, so the browser owns their state and no client component is needed
 * to keep them in sync — the previous `settings` object in `useState` existed
 * only to feed `checked`, and re-implemented what the DOM already does.
 *
 * Save posts every field at once to a Server Action; the result comes back as a
 * query flag rather than `savedAt`/`error` state.
 */
export default async function NotificationSettingsPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/notifications/settings");
  const [settings, sp] = await Promise.all([loadSettings(token), searchParams]);

  const error = sp.error === "1" ? "Failed to save" : null;
  const saved = sp.saved === "1";

  return (
    <div className="rounded-xl bg-white p-6 shadow-sm ring-1 ring-gray-100">
      <div className="border-b border-gray-100 pb-4">
        <h1 className="text-xl font-semibold text-gray-900">Notification settings</h1>
        <p className="mt-1 text-sm text-gray-600">Choose which alerts you receive.</p>
      </div>

      <form action={saveNotificationSettings}>
        <div className="mt-4 space-y-3">
          {FIELDS.map((f) => (
            <label
              key={f.key}
              className="flex cursor-pointer items-start justify-between gap-4 rounded-lg border border-gray-200 p-4 hover:bg-gray-50"
            >
              <div>
                <p className="text-sm font-medium text-gray-900">{f.label}</p>
                <p className="text-xs text-gray-500">{f.description}</p>
              </div>
              <input
                type="checkbox"
                name={f.key}
                defaultChecked={!!settings[f.key]}
                className="mt-1 h-5 w-5 rounded border-gray-300 text-[#CC1414] focus:ring-[#CC1414]"
              />
            </label>
          ))}
        </div>

        {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
        {saved && !error && <p className="mt-3 text-sm text-green-600">Saved.</p>}

        <div className="mt-5 flex justify-end gap-2">
          <a
            href="/notifications"
            className="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
          >
            Back
          </a>
          <SaveButton />
        </div>
      </form>
    </div>
  );
}
