import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState, type FormEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Session } from "@supabase/supabase-js";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";

export const Route = createFileRoute("/admin")({
  head: () => ({ meta: [
    { title: "Blog Admin — Arun Shield" },
    { name: "description", content: "Private blog management for Arun Shield Security Services." },
    { property: "og:title", content: "Arun Shield Blog Administration" },
    { property: "og:description", content: "Private blog management for Arun Shield Security Services." },
    { property: "og:type", content: "website" },
    { name: "twitter:card", content: "summary" },
    { name: "robots", content: "noindex" },
  ] }),
  component: AdminPage,
});

type Post = { id: string; title: string; slug: string; excerpt: string; content: string; cover_image_url: string | null; published: boolean; created_at: string };
const empty = { title: "", slug: "", excerpt: "", content: "", cover_image_url: "", published: true };
const slugify = (s: string) => s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

function AdminPage() {
  const [session, setSession] = useState<Session | null>(null);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const { data } = supabase.auth.onAuthStateChange((_e, s) => setSession(s));
    supabase.auth.getSession().then(({ data }) => { setSession(data.session); setReady(true); });
    return () => data.subscription.unsubscribe();
  }, []);
  if (!ready) return <div className="py-32 text-center text-muted-foreground">Loading…</div>;
  if (!session) return <SignIn />;
  return <AdminGate userId={session.user.id} email={session.user.email ?? ""} />;
}

function SignIn() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const submit = async (e: FormEvent) => {
    e.preventDefault(); setBusy(true);
    const res = await supabase.auth.signInWithPassword({ email, password });
    setBusy(false);
    if (res.error) toast.error("Wrong username or password");
  };
  return (
    <section className="mx-auto max-w-md px-4 py-24">
      <div className="rounded-2xl border bg-card p-8 shadow-sm">
        <h1 className="text-3xl uppercase text-primary">Blog Admin</h1>
        <p className="mt-1 text-sm text-muted-foreground">Sign in to manage blog posts.</p>
        <form onSubmit={submit} className="mt-6 space-y-4">
          <div><Label htmlFor="email">Username</Label><Input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} /></div>
          <div><Label htmlFor="password">Password</Label><Input id="password" type="password" required minLength={6} value={password} onChange={(e) => setPassword(e.target.value)} /></div>
          <Button type="submit" className="w-full" disabled={busy}>Sign in</Button>
        </form>
      </div>
    </section>
  );
}

function AdminGate({ userId, email }: { userId: string; email: string }) {
  const { data: isAdmin, isLoading } = useQuery({
    queryKey: ["is-admin", userId],
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", userId).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });
  if (isLoading) return <div className="py-32 text-center text-muted-foreground">Checking access…</div>;
  if (!isAdmin) return (
    <div className="py-32 text-center">
      <p className="text-primary">This account ({email}) is not an admin.</p>
      <Button variant="outline" className="mt-4" onClick={() => supabase.auth.signOut()}>Sign out</Button>
    </div>
  );
  return <Dashboard email={email} />;
}

function Dashboard({ email }: { email: string }) {
  const qc = useQueryClient();
  const [form, setForm] = useState(empty);
  const [editId, setEditId] = useState<string | null>(null);
  const { data: posts = [] } = useQuery({
    queryKey: ["posts", "admin"],
    queryFn: async () => {
      const { data, error } = await supabase.from("posts").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data as Post[];
    },
  });
  const refresh = () => qc.invalidateQueries({ queryKey: ["posts"] });
  const save = useMutation({
    mutationFn: async () => {
      const row = { ...form, slug: slugify(form.slug || form.title), cover_image_url: form.cover_image_url || null, updated_at: new Date().toISOString() };
      if (!row.title.trim() || !row.slug) throw new Error("Title is required");
      const { error } = editId ? await supabase.from("posts").update(row).eq("id", editId) : await supabase.from("posts").insert(row);
      if (error) throw error;
    },
    onSuccess: () => { toast.success(editId ? "Post updated" : "Post published"); setForm(empty); setEditId(null); refresh(); },
    onError: (e: Error) => toast.error(e.message),
  });
  const del = useMutation({
    mutationFn: async (id: string) => { const { error } = await supabase.from("posts").delete().eq("id", id); if (error) throw error; },
    onSuccess: () => { toast.success("Post deleted"); refresh(); },
    onError: (e: Error) => toast.error(e.message),
  });
  const edit = (p: Post) => { setEditId(p.id); setForm({ title: p.title, slug: p.slug, excerpt: p.excerpt, content: p.content, cover_image_url: p.cover_image_url ?? "", published: p.published }); window.scrollTo({ top: 0, behavior: "smooth" }); };

  return (
    <section className="mx-auto max-w-6xl px-4 py-12">
      <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 sm:flex sm:justify-between">
        <div className="min-w-0"><h1 className="text-3xl uppercase text-primary">Blog Admin</h1><p className="break-all text-sm text-muted-foreground">Signed in as {email}</p></div>
        <Button variant="outline" onClick={() => supabase.auth.signOut()}>Sign out</Button>
      </div>
      <div className="mt-8 grid lg:grid-cols-[1.2fr_1fr] gap-8">
        <form onSubmit={(e) => { e.preventDefault(); save.mutate(); }} className="min-w-0 space-y-4 rounded-xl border bg-card p-6">
          <h2 className="text-xl uppercase text-primary">{editId ? "Edit post" : "New post"}</h2>
          <div><Label htmlFor="title">Title</Label><Input id="title" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} required /></div>
          <div><Label htmlFor="slug">Link name (optional)</Label><Input id="slug" placeholder={slugify(form.title)} value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></div>
          <div><Label htmlFor="excerpt">Short summary</Label><Textarea id="excerpt" rows={2} value={form.excerpt} onChange={(e) => setForm({ ...form, excerpt: e.target.value })} /></div>
          <div><Label htmlFor="cover">Cover image link (optional)</Label><Input id="cover" type="url" value={form.cover_image_url} onChange={(e) => setForm({ ...form, cover_image_url: e.target.value })} /></div>
          <div><Label htmlFor="content">Content</Label><Textarea id="content" rows={12} value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} /><p className="mt-1 text-xs text-muted-foreground">Leave an empty line between paragraphs.</p></div>
          <div className="flex items-center gap-2"><Switch id="pub" checked={form.published} onCheckedChange={(v) => setForm({ ...form, published: v })} /><Label htmlFor="pub">Published</Label></div>
          <div className="flex gap-2">
            <Button type="submit" disabled={save.isPending}>{editId ? "Save changes" : "Publish post"}</Button>
            {editId && <Button type="button" variant="outline" onClick={() => { setEditId(null); setForm(empty); }}>Cancel</Button>}
          </div>
        </form>
        <div className="min-w-0 space-y-3">
          <h2 className="text-xl uppercase text-primary">All posts ({posts.length})</h2>
          {posts.map((p) => (
            <div key={p.id} className="rounded-lg border bg-card p-4">
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0"><div className="font-semibold text-primary truncate">{p.title}</div><div className="text-xs text-muted-foreground">{p.published ? "Published" : "Draft"} • {new Date(p.created_at).toLocaleDateString("en-IN")}</div></div>
              </div>
              <div className="mt-3 flex gap-2">
                <Button size="sm" variant="outline" onClick={() => edit(p)}>Edit</Button>
                <Button size="sm" variant="destructive" onClick={() => { if (confirm("Delete this post?")) del.mutate(p.id); }}>Delete</Button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
