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 { roleMatrix, users } from "@/data/mock";
import type { UserRow } from "@/data/types";

export const Route = createFileRoute("/users")({
  head: () => ({
    meta: [
      { title: "Users & roles | KareVoyage Operations" },
      { name: "description", content: "Team accounts, role assignments and what each role can access." },
      { property: "og:title", content: "Users & roles | KareVoyage Operations" },
      { property: "og:description", content: "Control who can see and change what." },
    ],
  }),
  component: UsersPage,
});

const gridColumns: GridColumn<UserRow>[] = [
  { key: "id", header: "ID", width: 100, editable: false, frozen: true },
  { key: "name", header: "Name", width: 170, validate: validators.required("Name") },
  { key: "email", header: "Email", width: 230, validate: validators.email },
  { key: "role", header: "Role", width: 160, type: "status" },
  { key: "lastLogin", header: "Last login", width: 130, type: "date", validate: validators.date },
  { key: "status", header: "Status", width: 120, type: "status" },
];

function UsersPage() {
  const columns: TableColumn<UserRow>[] = [
    {
      key: "user",
      header: "User",
      sortValue: (u) => u.name,
      cell: (u) => (
        <div className="flex items-center gap-3">
          <Avatar name={u.name} />
          <div className="min-w-0">
            <p className="truncate font-medium">{u.name}</p>
            <p className="truncate text-xs text-muted-foreground">{u.email}</p>
          </div>
        </div>
      ),
    },
    { key: "role", header: "Role", sortValue: (u) => u.role, cell: (u) => <StatusPill value={u.role} /> },
    { key: "lastLogin", header: "Last login", responsive: "hidden lg:table-cell", sortValue: (u) => u.lastLogin, cell: (u) => formatDate(u.lastLogin) },
    { key: "status", header: "Status", sortValue: (u) => u.status, cell: (u) => <StatusPill value={u.status} /> },
  ];

  return (
    <ListPage
      title="Users & roles"
      description="Who works in the portal, and what each role is allowed to do."
      countLabel={(n) => `${n} team members`}
      searchPlaceholder="Search team members…"
      actions={<Button onClick={() => toast.info("Invite form opens here.")}>Invite user</Button>}
      rows={users}
      columns={columns}
      getId={(u) => u.id}
      searchText={(u) => `${u.name} ${u.email} ${u.role}`}
      filters={[
        { key: "role", label: "Role", get: (u) => u.role },
        { key: "status", label: "Status", get: (u) => u.status },
      ]}
      gridColumns={gridColumns}
      gridModule="Users"
      emptyTitle="No users"
      emptyMessage="Invite your first team member."
      above={
        <div className="overflow-x-auto rounded-xl border border-border bg-surface">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left">
                {Object.keys(roleMatrix[0] ?? {}).map((k) => (
                  <th key={k} className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
                    {k}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {roleMatrix.map((row, i) => (
                <tr key={i} className="border-b border-border last:border-0">
                  {Object.values(row).map((v, j) => (
                    <td key={j} className="px-4 py-2.5 text-sm text-foreground">
                      {String(v)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      }
    />
  );
}
