import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { getAdminCourse, updateSettings } from "@/lib/admin.functions";
import { toast } from "sonner";

const q = queryOptions({ queryKey: ["admin-course"], queryFn: () => getAdminCourse() });

export const Route = createFileRoute("/_authenticated/admin/settings")({
  loader: ({ context }) => context.queryClient.ensureQueryData(q),
  component: AdminSettings,
});

function AdminSettings() {
  const { data } = useSuspenseQuery(q);
  const qc = useQueryClient();
  const saveFn = useServerFn(updateSettings);
  const s = data.settings;
  const [form, setForm] = useState({
    bkash_number: s?.bkash_number ?? "",
    bkash_account_type: s?.bkash_account_type ?? "Personal",
    bkash_instructions: s?.bkash_instructions ?? "",
    support_email: s?.support_email ?? "",
    support_phone: s?.support_phone ?? "",
  });

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    try { await saveFn({ data: form }); toast.success("Settings saved"); qc.invalidateQueries({ queryKey: ["admin-course"] }); qc.invalidateQueries({ queryKey: ["landing"] }); }
    catch (e: any) { toast.error(e.message); }
  };

  return (
    <div>
      <h1 className="mb-6 font-display text-3xl font-bold">Settings</h1>
      <form onSubmit={save} className="max-w-xl space-y-4 rounded-2xl border border-border bg-card p-6">
        <h2 className="font-semibold">bKash Payment</h2>
        <Field label="bKash Number" value={form.bkash_number} onChange={(v) => setForm({ ...form, bkash_number: v })} />
        <Field label="Account Type (Personal / Merchant)" value={form.bkash_account_type} onChange={(v) => setForm({ ...form, bkash_account_type: v })} />
        <Text label="Payment Instructions" value={form.bkash_instructions} onChange={(v) => setForm({ ...form, bkash_instructions: v })} />
        <h2 className="pt-2 font-semibold">Support</h2>
        <Field label="Support Email" value={form.support_email ?? ""} onChange={(v) => setForm({ ...form, support_email: v })} />
        <Field label="Support Phone" value={form.support_phone ?? ""} onChange={(v) => setForm({ ...form, support_phone: v })} />
        <button className="rounded-lg bg-gradient-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow-glow">Save Settings</button>
      </form>
    </div>
  );
}

function Field({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <input value={value} onChange={(e) => onChange(e.target.value)} className="mt-1.5 block w-full rounded-lg border border-border bg-input px-3 py-2.5 text-sm outline-none ring-primary/40 focus:ring-2" />
    </label>
  );
}
function Text({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <textarea value={value} onChange={(e) => onChange(e.target.value)} rows={4} className="mt-1.5 block w-full rounded-lg border border-border bg-input px-3 py-2.5 text-sm outline-none ring-primary/40 focus:ring-2" />
    </label>
  );
}
