import { ActionIcon, Badge, Group, Stack, Text, Tooltip } from "@mantine/core";
import { IconEdit, IconFileSpreadsheet, IconPlayerPlay, IconPower, IconStar, IconTrash } from "@tabler/icons-react";
import type { MRT_ColumnDef } from "mantine-react-table";
import type { AgentRow } from "./agent.types";

export const agentColumns = (
  onEdit: (row: AgentRow) => void,
  onDelete: (row: AgentRow) => void,
  onTest: (row: AgentRow) => void,
  onMakeGlobal?: (row: AgentRow) => void,
  onToggleActive?: (row: AgentRow) => void,
): MRT_ColumnDef<AgentRow>[] => [
  {
    header: "Agent Name",
    accessorKey: "agent_name",
    minSize: 180,
    Cell: ({ row }) => (
      <Group gap={6} wrap="nowrap">
        <Text size="sm">{row.original.agent_name}</Text>
        {row.original.is_global && (
          <Tooltip label="This is the global agent">
            <Badge size="xs" color="yellow" variant="light" leftSection={<IconStar size={10} />}>
              Global
            </Badge>
          </Tooltip>
        )}
      </Group>
    ),
  },
  {
    header: "Prompt",
    accessorKey: "prompt_name",
    minSize: 180,
    Cell: ({ row }) => {
      const hasPrompt = !!row.original.prompt_name;
      return (
        <Badge size="sm" variant="light" tt="none" color={hasPrompt ? "gray" : "pink"}>
          {row.original.prompt_name ?? "No prompt"}
        </Badge>
      );
    },
  },
  {
    header: "Category",
    accessorKey: "category_key",
    minSize: 120,
    Cell: ({ row }) => {
      const value = row.original.category_key;
      return value ? (
        <Badge size="sm" variant="light" color="blue" tt="none">
          {value}
        </Badge>
      ) : (
        <Text size="sm" c="dimmed">
          -
        </Text>
      );
    },
  },
  {
    header: "Status",
    accessorKey: "is_active",
    minSize: 90,
    Cell: ({ row }) => (
      <Badge size="sm" variant="light" color={row.original.is_active ? "green" : "red"}>
        {row.original.is_active ? "Active" : "Inactive"}
      </Badge>
    ),
  },
  {
    header: "Data Sources",
    accessorKey: "data_sources",
    minSize: 160,
    enableSorting: false,
    Cell: ({ row }) => {
      const sources = row.original.data_sources ?? [];
      if (sources.length === 0) {
        return <Text size="xs" c="dimmed">No files</Text>;
      }
      const getFileName = (url: string) => {
        try {
          const decoded = decodeURIComponent(url);
          const last = decoded.split("/").pop() ?? url;
          return last.replace(/^[0-9a-f]{32}_/, "");
        } catch {
          return url;
        }
      };
      return (
        <Tooltip
          label={
            <Stack gap={2}>
              {sources.map((s, i) => (
                <Text key={i} size="xs">{getFileName(s.url)}</Text>
              ))}
            </Stack>
          }
          withArrow
          multiline
          maw={320}
        >
          <Group gap={4} wrap="nowrap">
            <IconFileSpreadsheet size={14} color="var(--mantine-color-green-6)" />
            <Badge size="sm" variant="light" color="green">
              {sources.length} file{sources.length > 1 ? "s" : ""}
            </Badge>
          </Group>
        </Tooltip>
      );
    },
  },
  { header: "Language Model", accessorKey: "language_model", minSize: 170 },
  { header: "Created By", accessorKey: "created_by", minSize: 150 },
  { header: "Updated By", accessorKey: "updated_by", minSize: 150 },
  {
    id: "actions",
    header: "Actions",
    enableSorting: false,
    enableColumnFilter: false,
    minSize: 170,
    Cell: ({ row }) => {
      const item = row.original;
      return (
        <Group gap="xs">
          <Tooltip label="Test this agent">
            <ActionIcon
              variant="light"
              color="teal"
              onClick={(e) => { e.stopPropagation(); onTest(item); }}
            >
              <IconPlayerPlay size={16} />
            </ActionIcon>
          </Tooltip>
          <Tooltip label="Edit">
            <ActionIcon
              variant="light"
              color="blue"
              onClick={(e) => { e.stopPropagation(); onEdit(item); }}
            >
              <IconEdit size={16} />
            </ActionIcon>
          </Tooltip>
          {!item.is_global && onToggleActive && (
            <Tooltip label={item.is_active ? "Deactivate agent" : "Activate agent"}>
              <ActionIcon
                variant="light"
                color={item.is_active ? "orange" : "green"}
                onClick={(e) => { e.stopPropagation(); onToggleActive(item); }}
              >
                <IconPower size={16} />
              </ActionIcon>
            </Tooltip>
          )}
          {!item.is_global && onMakeGlobal && (
            <Tooltip label="Mark as Global Agent">
              <ActionIcon
                variant="light"
                color="yellow"
                onClick={(e) => { e.stopPropagation(); onMakeGlobal(item); }}
              >
                <IconStar size={16} />
              </ActionIcon>
            </Tooltip>
          )}
          {!item.is_global && (
            <Tooltip label="Delete">
              <ActionIcon
                variant="light"
                color="red"
                onClick={(e) => { e.stopPropagation(); onDelete(item); }}
              >
                <IconTrash size={16} />
              </ActionIcon>
            </Tooltip>
          )}
        </Group>
      );
    },
  },
];
