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 { Send, MessageSquare, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { AdminShell } from "@/components/admin/AdminShell";
import { listTicketsAdmin, replyToTicket, deleteTicket } from "@/lib/tickets.functions";

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

function TicketsPage() {
  const fetchAll = useServerFn(listTicketsAdmin);
  const reply = useServerFn(replyToTicket);
  const del = useServerFn(deleteTicket);
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: ["admin-tickets"], queryFn: () => fetchAll() });
  const [openId, setOpenId] = useState<string | null>(null);
  const [draft, setDraft] = useState("");

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

  const send = useMutation({
    mutationFn: (vars: { ticket_id: string; message: string; new_status?: "in_progress" | "closed" }) =>
      reply({ data: vars }),
    onSuccess: () => {
      toast.success("Reply sent");
      setDraft("");
      qc.invalidateQueries({ queryKey: ["admin-tickets"] });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
  });

  const tickets = data?.tickets ?? [];
  const open = tickets.find((t) => t.id === openId);

  return (
    <AdminShell title="Support Tickets" subtitle="Help users and resolve issues">
      <div className="grid grid-cols-1 lg:grid-cols-[360px_1fr] gap-5">
        <div className="glass-strong rounded-2xl border border-border overflow-hidden max-h-[70vh] overflow-y-auto">
          {isLoading ? (
            <p className="p-10 text-center text-sm text-muted-foreground">Loading…</p>
          ) : tickets.length === 0 ? (
            <p className="p-10 text-center text-sm text-muted-foreground">No tickets yet.</p>
          ) : (
            tickets.map((t) => (
              <button
                key={t.id}
                onClick={() => setOpenId(t.id)}
                className={`w-full text-left p-4 border-b border-border/40 last:border-0 transition-colors ${
                  openId === t.id ? "bg-primary/10" : "hover:bg-muted/30"
                }`}
              >
                <div className="flex items-center justify-between mb-1">
                  <span className="font-semibold text-sm truncate">{t.subject}</span>
                  <span className={`text-[10px] uppercase tracking-widest font-bold px-2 py-0.5 rounded-full ${
                    t.status === "closed" ? "bg-muted text-muted-foreground"
                    : t.status === "in_progress" ? "bg-yellow-500/20 text-yellow-400"
                    : "bg-pink-500/20 text-pink-400"
                  }`}>{t.status}</span>
                </div>
                <p className="text-xs text-muted-foreground line-clamp-2">{t.message}</p>
                <p className="text-[10px] text-muted-foreground mt-1">{new Date(t.created_at).toLocaleString()}</p>
              </button>
            ))
          )}
        </div>

        <div className="glass-strong rounded-2xl border border-border p-6 min-h-[70vh] flex flex-col">
          {!open ? (
            <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
              <MessageSquare className="w-10 h-10 mb-3 opacity-50" />
              <p className="text-sm">Select a ticket to reply</p>
            </div>
          ) : (
            <>
              <div className="border-b border-border pb-4 mb-4 flex items-start justify-between gap-3">
                <div>
                  <h3 className="font-display font-bold text-lg">{open.subject}</h3>
                  <p className="text-xs text-muted-foreground">User: {open.user_id.slice(0, 8)}… · {new Date(open.created_at).toLocaleString()}</p>
                </div>
                <button
                  onClick={() => confirm(`Delete ticket "${open.subject}"? This cannot be undone.`) && remove.mutate(open.id)}
                  disabled={remove.isPending}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg glass border border-destructive/30 text-destructive text-xs uppercase tracking-widest font-bold hover:bg-destructive/10 disabled:opacity-50"
                >
                  <Trash2 className="w-3.5 h-3.5" /> Delete
                </button>
              </div>
              <div className="flex-1 overflow-y-auto space-y-3 mb-4">
                <div className="p-3 rounded-xl bg-muted/30">
                  <p className="text-[10px] uppercase tracking-widest text-muted-foreground mb-1">User</p>
                  <p className="text-sm whitespace-pre-wrap">{open.message}</p>
                </div>
                {(open.ticket_replies ?? [])
                  .slice()
                  .sort((a, b) => +new Date(a.created_at) - +new Date(b.created_at))
                  .map((r) => (
                    <div key={r.id} className={`p-3 rounded-xl ${r.is_admin ? "bg-primary/10 border border-primary/30" : "bg-muted/30"}`}>
                      <p className="text-[10px] uppercase tracking-widest text-muted-foreground mb-1">{r.is_admin ? "Admin" : "User"}</p>
                      <p className="text-sm whitespace-pre-wrap">{r.message}</p>
                    </div>
                  ))}
              </div>
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  if (!draft.trim()) return;
                  send.mutate({ ticket_id: open.id, message: draft, new_status: "in_progress" });
                }}
                className="space-y-2"
              >
                <textarea value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Type your reply…" rows={3} className="w-full px-3 py-2 rounded-lg glass border border-border focus:border-primary outline-none text-sm" />
                <div className="flex justify-between gap-2">
                  <button type="button" onClick={() => send.mutate({ ticket_id: open.id, message: draft || "Closed by admin.", new_status: "closed" })} className="px-4 py-2 rounded-xl glass border border-border text-xs uppercase tracking-widest font-bold">
                    Close ticket
                  </button>
                  <button disabled={send.isPending} className="inline-flex items-center gap-2 px-5 py-2 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold disabled:opacity-50">
                    <Send className="w-4 h-4" /> {send.isPending ? "Sending…" : "Send Reply"}
                  </button>
                </div>
              </form>
            </>
          )}
        </div>
      </div>
    </AdminShell>
  );
}
