import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { KeyRound, Shield } from "lucide-react";
import { toast } from "sonner";
import { AdminShell } from "@/components/admin/AdminShell";
import { changeAdminPassword } from "@/lib/admin.functions";

export const Route = createFileRoute("/admin/settings")({
  head: () => ({ meta: [{ title: "Settings · Admin" }] }),
  component: SettingsPage,
});

function SettingsPage() {
  const change = useServerFn(changeAdminPassword);
  const [pw, setPw] = useState("");
  const [confirm, setConfirm] = useState("");

  const m = useMutation({
    mutationFn: (newPassword: string) => change({ data: { newPassword } }),
    onSuccess: () => {
      toast.success("Password updated");
      setPw(""); setConfirm("");
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
  });

  return (
    <AdminShell title="Settings" subtitle="Manage your admin account">
      <div className="max-w-xl">
        <div className="glass-strong rounded-2xl border border-border p-6">
          <div className="flex items-center gap-3 mb-5">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-accent flex items-center justify-center">
              <KeyRound className="w-5 h-5 text-primary-foreground" />
            </div>
            <div>
              <h2 className="font-display text-lg font-bold">Change Password</h2>
              <p className="text-xs text-muted-foreground">Minimum 8 characters</p>
            </div>
          </div>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              if (pw.length < 8) return toast.error("Password too short");
              if (pw !== confirm) return toast.error("Passwords don't match");
              m.mutate(pw);
            }}
            className="space-y-4"
          >
            <label className="block">
              <span className="block text-[11px] uppercase tracking-widest text-muted-foreground mb-1">New Password</span>
              <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} className="w-full px-3 py-2 rounded-lg glass border border-border focus:border-primary outline-none text-sm" />
            </label>
            <label className="block">
              <span className="block text-[11px] uppercase tracking-widest text-muted-foreground mb-1">Confirm Password</span>
              <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} className="w-full px-3 py-2 rounded-lg glass border border-border focus:border-primary outline-none text-sm" />
            </label>
            <button disabled={m.isPending} className="w-full py-3 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold disabled:opacity-50">
              {m.isPending ? "Updating…" : "Update Password"}
            </button>
          </form>
        </div>

        <div className="mt-6 glass rounded-2xl border border-primary/20 p-5 flex gap-3">
          <Shield className="w-5 h-5 text-primary shrink-0 mt-0.5" />
          <div className="text-xs text-muted-foreground">
            Your admin role is enforced server-side via the <code className="text-primary">user_roles</code> table and Row-Level Security. Even with a stolen session, write operations re-check the role on every request.
          </div>
        </div>
      </div>
    </AdminShell>
  );
}
