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, upsertCourse } from "@/lib/admin.functions";
import { toast } from "sonner";

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

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

function AdminCourse() {
  const { data } = useSuspenseQuery(q);
  const qc = useQueryClient();
  const saveFn = useServerFn(upsertCourse);
  const c = data.courses[0];
  const [form, setForm] = useState({
    id: c?.id,
    title: c?.title ?? "",
    subtitle: c?.subtitle ?? "",
    description: c?.description ?? "",
    instructor_name: c?.instructor_name ?? "Admin",
    thumbnail_url: c?.thumbnail_url ?? "",
    intro_video_url: c?.intro_video_url ?? "",
    price: Number(c?.price ?? 0),
    discount_price: c?.discount_price != null ? Number(c.discount_price) : null,
    is_published: c?.is_published ?? true,
    benefits: (c?.benefits ?? []) as string[],
  });
  const [benefitsText, setBenefitsText] = useState((form.benefits ?? []).join("\n"));

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await saveFn({
        data: {
          ...form,
          subtitle: form.subtitle || null,
          description: form.description || null,
          thumbnail_url: form.thumbnail_url || null,
          intro_video_url: form.intro_video_url || null,
          benefits: benefitsText.split("\n").map((s) => s.trim()).filter(Boolean),
        },
      });
      toast.success("Course 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">Course</h1>
      <form onSubmit={save} className="max-w-2xl space-y-4 rounded-2xl border border-border bg-card p-6">
        <Field label="Title" value={form.title} onChange={(v) => setForm({ ...form, title: v })} />
        <Field label="Subtitle" value={form.subtitle ?? ""} onChange={(v) => setForm({ ...form, subtitle: v })} />
        <Textarea label="Description" value={form.description ?? ""} onChange={(v) => setForm({ ...form, description: v })} />
        <Field label="Instructor name" value={form.instructor_name} onChange={(v) => setForm({ ...form, instructor_name: v })} />
        <Field label="Thumbnail URL" value={form.thumbnail_url ?? ""} onChange={(v) => setForm({ ...form, thumbnail_url: v })} />
        <Field label="Intro Video URL (YouTube / Vimeo / .mp4)" value={form.intro_video_url ?? ""} onChange={(v) => setForm({ ...form, intro_video_url: v })} />
        <div className="grid gap-4 sm:grid-cols-2">
          <Field label="Price (BDT)" type="number" value={String(form.price)} onChange={(v) => setForm({ ...form, price: Number(v) })} />
          <Field label="Discount Price (BDT)" type="number" value={form.discount_price != null ? String(form.discount_price) : ""} onChange={(v) => setForm({ ...form, discount_price: v ? Number(v) : null })} />
        </div>
        <Textarea label="Benefits (one per line)" value={benefitsText} onChange={setBenefitsText} rows={6} />
        <label className="inline-flex items-center gap-2 text-sm">
          <input type="checkbox" checked={form.is_published} onChange={(e) => setForm({ ...form, is_published: e.target.checked })} className="h-4 w-4 rounded border-border" />
          Published
        </label>
        <button className="rounded-lg bg-gradient-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow-glow">Save Course</button>
      </form>
    </div>
  );
}

function Field({ label, value, onChange, type = "text" }: { label: string; value: string; onChange: (v: string) => void; type?: string }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <input type={type} 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 Textarea({ label, value, onChange, rows = 3 }: { label: string; value: string; onChange: (v: string) => void; rows?: number }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <textarea rows={rows} 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>
  );
}
