import {
  Paper, Stack, Table, Text,
} from "@mantine/core";
import { IconSearch } from "@tabler/icons-react";
import {
  flexRender,
  MRT_GlobalFilterTextInput,
  MRT_TableBodyCellValue,
  MRT_TablePagination,
  MRT_ToolbarAlertBanner,
  useMantineReactTable,
  type MRT_RowSelectionState,
} from "mantine-react-table";
import { useCallback, useState } from "react";
import { useNavigate } from "react-router";
import { deleteAgent, makeAgentGlobal, toggleAgentActive } from "@/lib/features/chatbot/agent/action";
import ConfirmModal from "@/layouts/shared/ConfirmModal";
import { agentColumns } from "./(widgets)/agent.columns";
import AgentTableHeader from "./(widgets)/AgentTableHeader";
import { TestAgentModal } from "./(widgets)/AgentForm";
import type { AgentRow } from "./(widgets)/agent.types";

const AgentsClientPage: React.FC<{
  tableProps: { data: AgentRow[]; totalRows: number };
}> = ({ tableProps: { data } }) => {
  const navigate = useNavigate();
  const [rowSelection, setRowSelection] = useState<MRT_RowSelectionState>({});
  const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 });

  const [confirmState, setConfirmState] = useState<{
    opened: boolean;
    title: string;
    message: string;
    onConfirm: () => void | Promise<void>;
  }>({ opened: false, title: "", message: "", onConfirm: () => {} });

  const [testModal, setTestModal] = useState<{ opened: boolean; agentId?: string; agentName?: string }>({
    opened: false,
  });

  const openConfirm = useCallback(
    (opts: { title: string; message: string; onConfirm: () => void | Promise<void> }) => {
      setConfirmState({ opened: true, ...opts });
    },
    [],
  );
  const closeConfirm = useCallback(() => setConfirmState((s) => ({ ...s, opened: false })), []);

  const onEdit = (row: AgentRow) => navigate(`edit/${row.id}`);

  const onDelete = (row: AgentRow) => {
    openConfirm({
      title: "Delete Agent",
      message: `Delete agent "${row.agent_name}"?\n\nThis cannot be undone.`,
      onConfirm: async () => {
        await deleteAgent(row.id);
        navigate(0);
      },
    });
  };

  const onTest = (row: AgentRow) => {
    setTestModal({ opened: true, agentId: row.id, agentName: row.agent_name });
  };

  const onToggleActive = (row: AgentRow) => {
    openConfirm({
      title: row.is_active ? "Deactivate Agent" : "Activate Agent",
      message: `${row.is_active ? "Deactivate" : "Activate"} agent "${row.agent_name}"?`,
      onConfirm: async () => {
        await toggleAgentActive(row.id);
        navigate(0);
      },
    });
  };

  const onMakeGlobal = (row: AgentRow) => {
    openConfirm({
      title: "Make Global Agent",
      message: `Promote "${row.agent_name}" to Global Agent?\n\nThis will replace the current global agent and cannot be undone easily.`,
      onConfirm: async () => {
        await makeAgentGlobal(row.id);
        navigate(0);
      },
    });
  };

  const columns = agentColumns(onEdit, onDelete, onTest, onMakeGlobal, onToggleActive);

  const table = useMantineReactTable({
    columns,
    data,
    enableSorting: true,
    enableRowSelection: false,
    getRowId: (row) => row.id,
    onRowSelectionChange: setRowSelection,
    state: { rowSelection, pagination },
    onPaginationChange: (updater) => {
      const next = typeof updater === "function" ? updater(pagination) : updater;
      setPagination(next);
      window.scrollTo({ top: 0, behavior: "smooth" });
    },
    initialState: { showGlobalFilter: true },
    paginationDisplayMode: "pages",
    mantinePaginationProps: { rowsPerPageOptions: ["10", "25", "50"], p: 0 },
    mantineSearchTextInputProps: { size: "sm" },
    enablePinning: false,
  });

  return (
    <Stack>
      <ConfirmModal
        opened={confirmState.opened}
        onClose={closeConfirm}
        title={confirmState.title}
        message={confirmState.message}
        confirmLabel="Confirm"
        confirmColor="red"
        onConfirm={confirmState.onConfirm}
      />

      <TestAgentModal
        opened={testModal.opened}
        onClose={() => setTestModal({ opened: false })}
        agentId={testModal.agentId}
        agentName={testModal.agentName}
      />

      <AgentTableHeader onCreate={() => navigate("create")} />

      <MRT_GlobalFilterTextInput
        table={table}
        variant="default"
        size="sm"
        leftSection={<IconSearch size={16} />}
        c="dark.8"
        p={0}
      />

      <Paper bdrs={4} style={{ overflow: "hidden", border: "1px solid var(--mantine-color-white-2)" }}>
        <Table fz={11} highlightOnHover horizontalSpacing="xl" verticalSpacing="xs" withColumnBorders m="0">
          <Table.Thead>
            {table.getHeaderGroups().map((hg) => (
              <Table.Tr key={hg.id} c="dark.4" bg="gray.1">
                {hg.headers.map((header) => (
                  <Table.Th key={header.id} px={12}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.Header ?? header.column.columnDef.header,
                          header.getContext(),
                        )}
                  </Table.Th>
                ))}
              </Table.Tr>
            ))}
          </Table.Thead>
          <Table.Tbody>
            {table.getRowModel().rows.map((row) => (
              <Table.Tr key={row.id} style={{ cursor: "pointer" }}>
                {row.getVisibleCells().map((cell) => (
                  <Table.Td
                    key={cell.id}
                    px={12}
                    onClick={() => {
                      if (cell.column.id === "actions") return;
                      navigate(`edit/${row.original.id}`);
                    }}
                  >
                    <MRT_TableBodyCellValue cell={cell} table={table} />
                  </Table.Td>
                ))}
              </Table.Tr>
            ))}
            {data.length === 0 && (
              <Table.Tr>
                <Table.Td colSpan={99} ta="center" py="xl" c="dimmed">
                  <Text size="sm">No agents yet. Click "Create New Agent" to get started.</Text>
                </Table.Td>
              </Table.Tr>
            )}
          </Table.Tbody>
        </Table>
      </Paper>

      <MRT_TablePagination table={table} />
      <MRT_ToolbarAlertBanner stackAlertBanner table={table} />
    </Stack>
  );
};

export default AgentsClientPage;
