import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Plus, Pencil, Trash2, X, Star } from "lucide-react";
import { toast } from "sonner";
import { AdminShell } from "@/components/admin/AdminShell";
import { listMangaAdmin, upsertManga, deleteManga } from "@/lib/manga.functions";

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

type MangaForm = {
  id?: string;
  title: string;
  slug: string;
  description: string;
  cover_url: string;
  author: string;
  type: "free" | "premium";
  price: number;
  status: "ongoing" | "completed" | "hiatus";
  category: string;
  tags: string;
  featured: boolean;
};

const empty: MangaForm = {
  title: "", slug: "", description: "", cover_url: "", author: "",
  type: "free", price: 0, status: "ongoing", category: "", tags: "", featured: false,
};

function MangaAdminPage() {
  const fetchAll = useServerFn(listMangaAdmin);
  const upsert = useServerFn(upsertManga);
  const del = useServerFn(deleteManga);
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: ["admin-manga"], queryFn: () => fetchAll() });
  const [editing, setEditing] = useState<MangaForm | null>(null);

  const save = useMutation({
    mutationFn: (form: MangaForm) =>
      upsert({
        data: {
          id: form.id,
          title: form.title.trim(),
          slug: form.slug.trim().toLowerCase(),
          description: form.description || null,
          cover_url: form.cover_url || null,
          author: form.author || null,
          type: form.type,
          price: Number(form.price) || 0,
          status: form.status,
          category: form.category || null,
          tags: form.tags.split(",").map((t) => t.trim()).filter(Boolean),
          featured: form.featured,
        },
      }),
    onSuccess: () => {
      toast.success("Saved");
      setEditing(null);
      qc.invalidateQueries({ queryKey: ["admin-manga"] });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
  });

  const remove = useMutation({
    mutationFn: (id: string) => del({ data: { id } }),
    onSuccess: () => {
      toast.success("Deleted");
      qc.invalidateQueries({ queryKey: ["admin-manga"] });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
  });

  return (
    <AdminShell title="Manga Library" subtitle="Upload, edit and curate the catalogue">
      <div className="flex justify-end mb-6">
        <button
          onClick={() => setEditing(empty)}
          className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold tracking-wide glow-hover"
        >
          <Plus className="w-4 h-4" /> New Manga
        </button>
      </div>

      <div className="glass-strong rounded-2xl border border-border overflow-hidden">
        {isLoading ? (
          <p className="p-10 text-center text-sm text-muted-foreground">Loading…</p>
        ) : (data?.manga ?? []).length === 0 ? (
          <p className="p-10 text-center text-sm text-muted-foreground">No manga yet. Add your first title.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="text-left text-[11px] uppercase tracking-widest text-muted-foreground border-b border-border">
              <tr>
                <th className="p-4">Title</th>
                <th className="p-4 hidden md:table-cell">Type</th>
                <th className="p-4 hidden md:table-cell">Status</th>
                <th className="p-4">Price</th>
                <th className="p-4"></th>
              </tr>
            </thead>
            <tbody>
              {data!.manga.map((m) => (
                <tr key={m.id} className="border-b border-border/40 last:border-0 hover:bg-muted/20">
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      {m.cover_url ? (
                        <img src={m.cover_url} alt="" className="w-10 h-14 object-cover rounded-md" />
                      ) : (
                        <div className="w-10 h-14 rounded-md bg-muted" />
                      )}
                      <div>
                        <div className="font-semibold flex items-center gap-1">
                          {m.title}
                          {m.featured && <Star className="w-3 h-3 text-yellow-400 fill-yellow-400" />}
                        </div>
                        <div className="text-xs text-muted-foreground">{m.slug}</div>
                      </div>
                    </div>
                  </td>
                  <td className="p-4 hidden md:table-cell uppercase text-xs tracking-widest">{m.type}</td>
                  <td className="p-4 hidden md:table-cell uppercase text-xs tracking-widest">{m.status}</td>
                  <td className="p-4 font-display">{m.type === "premium" ? `₹${Number(m.price).toLocaleString()}` : "Free"}</td>
                  <td className="p-4 text-right">
                    <div className="inline-flex gap-2">
                      <button
                        onClick={() =>
                          setEditing({
                            id: m.id,
                            title: m.title,
                            slug: m.slug,
                            description: m.description ?? "",
                            cover_url: m.cover_url ?? "",
                            author: m.author ?? "",
                            type: m.type,
                            price: Number(m.price),
                            status: m.status,
                            category: m.category ?? "",
                            tags: (m.tags ?? []).join(", "),
                            featured: m.featured,
                          })
                        }
                        className="p-2 rounded-lg glass hover:border-primary/40 border border-transparent"
                      >
                        <Pencil className="w-3.5 h-3.5" />
                      </button>
                      <button
                        onClick={() => confirm(`Delete "${m.title}"?`) && remove.mutate(m.id)}
                        className="p-2 rounded-lg glass hover:border-destructive/40 border border-transparent text-destructive"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {editing && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-md">
          <div className="glass-strong rounded-2xl p-6 border border-primary/30 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-5">
              <h2 className="font-display text-xl font-bold">{editing.id ? "Edit" : "New"} Manga</h2>
              <button onClick={() => setEditing(null)} className="p-1 rounded-lg hover:bg-muted">
                <X className="w-4 h-4" />
              </button>
            </div>
            <form
              onSubmit={(e) => { e.preventDefault(); save.mutate(editing); }}
              className="grid grid-cols-1 sm:grid-cols-2 gap-4"
            >
              <Field label="Title">
                <input required value={editing.title} onChange={(e) => setEditing({ ...editing, title: e.target.value })} className={inputCls} />
              </Field>
              <Field label="Slug (a-z 0-9 -)">
                <input required pattern="[a-z0-9-]+" value={editing.slug} onChange={(e) => setEditing({ ...editing, slug: e.target.value })} className={inputCls} />
              </Field>
              <Field label="Author" className="sm:col-span-2">
                <input value={editing.author} onChange={(e) => setEditing({ ...editing, author: e.target.value })} className={inputCls} />
              </Field>
              <Field label="Cover URL" className="sm:col-span-2">
                <input value={editing.cover_url} onChange={(e) => setEditing({ ...editing, cover_url: e.target.value })} placeholder="https://…" className={inputCls} />
              </Field>
              <Field label="Type">
                <select value={editing.type} onChange={(e) => setEditing({ ...editing, type: e.target.value as "free" | "premium" })} className={inputCls}>
                  <option value="free">Free</option>
                  <option value="premium">Premium</option>
                </select>
              </Field>
              <Field label="Price (₹)">
                <input type="number" min={0} value={editing.price} onChange={(e) => setEditing({ ...editing, price: Number(e.target.value) })} className={inputCls} />
              </Field>
              <Field label="Status">
                <select value={editing.status} onChange={(e) => setEditing({ ...editing, status: e.target.value as MangaForm["status"] })} className={inputCls}>
                  <option value="ongoing">Ongoing</option>
                  <option value="completed">Completed</option>
                  <option value="hiatus">Hiatus</option>
                </select>
              </Field>
              <Field label="Category">
                <input value={editing.category} onChange={(e) => setEditing({ ...editing, category: e.target.value })} className={inputCls} />
              </Field>
              <Field label="Tags (comma-separated)" className="sm:col-span-2">
                <input value={editing.tags} onChange={(e) => setEditing({ ...editing, tags: e.target.value })} className={inputCls} />
              </Field>
              <Field label="Description" className="sm:col-span-2">
                <textarea rows={4} value={editing.description} onChange={(e) => setEditing({ ...editing, description: e.target.value })} className={inputCls} />
              </Field>
              <label className="sm:col-span-2 flex items-center gap-2 text-sm">
                <input type="checkbox" checked={editing.featured} onChange={(e) => setEditing({ ...editing, featured: e.target.checked })} />
                Feature on homepage
              </label>
              <div className="sm:col-span-2 flex justify-end gap-2 pt-2">
                <button type="button" onClick={() => setEditing(null)} className="px-4 py-2 rounded-xl glass border border-border text-sm">Cancel</button>
                <button disabled={save.isPending} className="px-5 py-2 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold disabled:opacity-50">
                  {save.isPending ? "Saving…" : "Save"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </AdminShell>
  );
}

const inputCls = "w-full px-3 py-2 rounded-lg glass border border-border focus:border-primary outline-none text-sm";

function Field({ label, children, className = "" }: { label: string; children: React.ReactNode; className?: string }) {
  return (
    <label className={`block ${className}`}>
      <span className="block text-[11px] uppercase tracking-widest text-muted-foreground mb-1">{label}</span>
      {children}
    </label>
  );
}
