import { createFileRoute } from "@tanstack/react-router";
import { toast } from "sonner";

import { ListPage } from "@/components/app/ListPage";
import { Avatar, formatDate } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import type { TableColumn } from "@/components/table/DataTable";
import type { GridColumn } from "@/components/grid/types";
import { validators } from "@/components/grid/types";
import { Button } from "@/components/ui/button";
import { communityPosts, moderationQueue } from "@/data/mock";
import type { CommunityPost } from "@/data/types";
import { destinationImage } from "@/lib/images";

export const Route = createFileRoute("/community")({
  head: () => ({
    meta: [
      { title: "Community | KareVoyage Operations" },
      { name: "description", content: "Traveller stories, reviews and photos with moderation and featuring controls." },
      { property: "og:title", content: "Community | KareVoyage Operations" },
      { property: "og:description", content: "Moderate and celebrate traveller stories." },
    ],
  }),
  component: CommunityPage,
});

const gridColumns: GridColumn<CommunityPost>[] = [
  { key: "id", header: "ID", width: 100, editable: false, frozen: true },
  { key: "guest", header: "Author", width: 170, validate: validators.required("Author") },
  { key: "type", header: "Type", width: 130, type: "status" },
  { key: "destination", header: "Destination", width: 150 },
  { key: "trip", header: "Trip", width: 140 },
  { key: "createdDate", header: "Created", width: 120, type: "date", validate: validators.date },
  { key: "likes", header: "Likes", width: 90, type: "number", align: "right" },
  { key: "comments", header: "Comments", width: 100, type: "number", align: "right" },
  { key: "status", header: "Status", width: 120, type: "status" },
];

function CommunityPage() {
  const columns: TableColumn<CommunityPost>[] = [
    {
      key: "post",
      header: "Post",
      sortValue: (p) => p.createdDate,
      cell: (p) => (
        <div className="flex items-center gap-3">
          <img src={destinationImage(p.destination)} alt="" loading="lazy" width={64} height={64} className="h-10 w-10 shrink-0 rounded-lg object-cover" />
          <div className="min-w-0">
            <p className="truncate font-medium">{p.type} · {p.destination}</p>
            <p className="truncate text-xs text-muted-foreground">{p.guest} · {formatDate(p.createdDate)}</p>
          </div>
        </div>
      ),
    },
    { key: "engagement", header: "Engagement", responsive: "hidden lg:table-cell", sortValue: (p) => p.likes, cell: (p) => `${p.likes} likes · ${p.comments} comments` },
    { key: "reported", header: "Reported", cell: (p) => (p.reported ? <StatusPill value="Reported" /> : "—") },
    { key: "featured", header: "Featured", responsive: "hidden lg:table-cell", cell: (p) => (p.featured ? "Yes" : "—") },
    { key: "status", header: "Status", sortValue: (p) => p.status, cell: (p) => <StatusPill value={p.status} /> },
  ];

  return (
    <ListPage
      title="Community"
      description="Stories, photos and reviews from travellers — and anything that needs a decision."
      countLabel={(n) => `${n} posts`}
      searchPlaceholder="Search authors, destinations, types…"
      actions={<Button onClick={() => toast.info("Feature-post picker opens here.")}>Feature a story</Button>}
      above={
        <div className="rounded-xl border border-border bg-surface p-5">
          <p className="kv-eyebrow mb-3">Moderation queue</p>
          {moderationQueue.slice(0, 4).length === 0 ? (
            <p className="text-sm text-muted-foreground">Nothing waiting for review.</p>
          ) : (
            <ul className="divide-y divide-border">
              {moderationQueue.slice(0, 4).map((m) => (
                <li key={m.id} className="flex flex-wrap items-center gap-4 py-2.5">
                  <Avatar name={m.author} className="h-7 w-7 text-[10px]" />
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium">{m.reason}</p>
                    <p className="truncate text-xs text-muted-foreground">{m.post} · reported by {m.reporter} · {formatDate(m.date)}</p>
                  </div>
                  <StatusPill value={m.status} />
                  <Button size="sm" variant="outline" onClick={() => toast.success("Report resolved.")}>Resolve</Button>
                </li>
              ))}
            </ul>
          )}
        </div>
      }
      rows={communityPosts}
      columns={columns}
      getId={(p) => p.id}
      searchText={(p) => `${p.guest} ${p.type} ${p.destination} ${p.trip}`}
      filters={[
        { key: "type", label: "Type", get: (p) => p.type },
        { key: "status", label: "Status", get: (p) => p.status },
        { key: "destination", label: "Destination", get: (p) => p.destination },
      ]}
      rowActions={[
        { label: "Feature", onSelect: () => toast.success("Post featured.") },
        { label: "Hide", onSelect: () => toast.error("Post hidden."), destructive: true },
      ]}
      gridColumns={gridColumns}
      gridModule="Community"
      emptyTitle="No posts"
      emptyMessage="Traveller stories will appear here."
    />
  );
}
