import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { getStudentDashboard } from "@/lib/dashboard.functions";
import { DashboardLayout } from "@/components/DashboardLayout";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

const dashQ = queryOptions({ queryKey: ["dashboard"], queryFn: () => getStudentDashboard() });

export const Route = createFileRoute("/_authenticated/profile")({
  loader: ({ context }) => context.queryClient.ensureQueryData(dashQ),
  component: ProfilePage,
});

function ProfilePage() {
  const { data: dash } = useSuspenseQuery(dashQ);
  const p = dash.profile;
  const [fullName, setFullName] = useState(p?.full_name ?? "");
  const [phone, setPhone] = useState(p?.phone ?? "");
  const [loading, setLoading] = useState(false);

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!p) return;
    setLoading(true);
    try {
      const { error } = await supabase.from("profiles").update({ full_name: fullName, phone }).eq("id", p.id);
      if (error) throw error;
      toast.success("Profile saved");
    } catch (e: any) { toast.error(e.message); }
    finally { setLoading(false); }
  };

  return (
    <DashboardLayout isAdmin={dash.isAdmin}>
      <h1 className="mb-6 font-display text-3xl font-bold">Profile</h1>
      <form onSubmit={save} className="max-w-lg space-y-4 rounded-2xl border border-border bg-card p-6">
        <Field label="Email" value={p?.email ?? ""} disabled />
        <Field label="Full name" value={fullName} onChange={setFullName} />
        <Field label="Phone (bKash)" value={phone} onChange={setPhone} />
        <button disabled={loading} className="rounded-lg bg-gradient-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow-glow disabled:opacity-60">
          {loading ? "Saving…" : "Save"}
        </button>
      </form>
    </DashboardLayout>
  );
}

function Field({ label, value, onChange, disabled }: { label: string; value: string; onChange?: (v: string) => void; disabled?: boolean }) {
  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)} disabled={disabled}
        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 disabled:opacity-60" />
    </label>
  );
}
