"use client";

import * as React from "react";
import type { ColumnDef } from "@tanstack/react-table";
import Link from "next/link";

import { DashboardMasterRowActions } from "@/app/dashboard/_components/dashboard-master-row-actions";
import { Input } from "@/components/ui/input";

import { ActiveReviewBadge } from "@/components/shared/status-pill";
import type { UserWidgetRow } from "./schema";
import { useChanged } from "@/hooks/use-changed";

const DELETE_HREF = "/dashboard/master/user-widgets/delete";

type PriorityHandlers = {
  onPriorityChange: (id: number, priority: string) => void;
};

function PriorityCell({
  id,
  initialValue,
  onPriorityChange,
}: {
  id: number;
  initialValue: number | string;
  onPriorityChange: (id: number, priority: string) => void;
}) {
  const [value, setValue] = React.useState(String(initialValue ?? "0"));

  // Re-sync when the server sends a new row value; local typing wins until then.
  if (useChanged(initialValue)) {
    setValue(String(initialValue ?? "0"));
  }

  return (
    <Input
      type="number"
      min={0}
      className="h-8 w-14 bg-background text-center text-xs tabular-nums"
      value={value}
      onChange={(event) => {
        const next = event.target.value;
        setValue(next);
        onPriorityChange(id, next);
      }}
    />
  );
}

function UserWidgetActions({ row }: { row: UserWidgetRow }) {
  const base = `/dashboard/master/user-widgets/${row.id}`;

  return (
    <DashboardMasterRowActions
      editHref={base}
      editAriaLabel="Update user widget"
      deleteUrl={DELETE_HREF}
      entityId={row.id}
      entityName={row.name}
      entityLabel="user widget"
      fallbackError="User widget could not be deleted."
      defaultSuccessMessage="User widget deleted."
    />
  );
}

export function createUserWidgetColumns({
  onPriorityChange,
}: PriorityHandlers): ColumnDef<UserWidgetRow>[] {
  return [
    {
      accessorKey: "name",
      header: "Name",
      cell: ({ row }) => (
        <div className="min-w-[180px]">
          <Link
            href={`/dashboard/master/user-widgets/${row.original.id}`}
            className="font-medium text-primary hover:underline"
          >
            {row.original.name}
          </Link>
          <p className="mt-0.5 font-mono text-muted-foreground text-[11px]">
            {row.original.filePath}
          </p>
        </div>
      ),
    },
    {
      accessorKey: "categoryName",
      header: "Category",
      cell: ({ row }) => <span className="text-sm">{row.original.categoryName}</span>,
    },
    {
      accessorKey: "status",
      header: "Status",
      cell: ({ row }) => (
        <ActiveReviewBadge status={row.original.status} label={row.original.statusLabel} />
      ),
    },
    {
      accessorKey: "dateAdded",
      header: "Date added",
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="text-muted-foreground text-sm whitespace-nowrap">
          {row.original.dateAdded}
        </span>
      ),
    },
    {
      id: "priority",
      header: "Priority",
      enableColumnFilter: false,
      cell: ({ row }) => (
        <PriorityCell
          id={row.original.id}
          initialValue={row.original.priority}
          onPriorityChange={onPriorityChange}
        />
      ),
    },
    {
      id: "options",
      header: () => <span className="block w-full text-right">Options</span>,
      cell: ({ row }) => <UserWidgetActions row={row.original} />,
      enableSorting: false,
    },
  ];
}
