import { Table, Badge, ActionIcon, Text } from '@mantine/core';
import { IconTrash } from '@tabler/icons-react';
import { useGetItemsQuery, useDeleteItemMutation, type Item } from '../api/item-api';
import { notify, useErrorHandler } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';

const STATUS_COLORS: Record<Item['status'], string> = {
  DRAFT: 'gray',
  ACTIVE: 'green',
  ARCHIVED: 'orange',
};

export function ItemTable() {
  const { data, isLoading } = useGetItemsQuery({});
  const [deleteItem] = useDeleteItemMutation();
  const { handleError } = useErrorHandler();
  const showDate = useDateDisplayer();

  const handleDelete = async (id: string) => {
    try {
      await deleteItem(id).unwrap();
      notify.success('Item deleted');
    } catch (e) {
      handleError(e);
    }
  };

  if (isLoading) return <Text>Loading...</Text>;
  if (!data?.data.length) return <Text c="dimmed">No items found.</Text>;

  return (
    <Table striped highlightOnHover>
      <Table.Thead>
        <Table.Tr>
          <Table.Th>Name</Table.Th>
          <Table.Th>Status</Table.Th>
          <Table.Th>Created</Table.Th>
          <Table.Th />
        </Table.Tr>
      </Table.Thead>
      <Table.Tbody>
        {data.data.map((item) => (
          <Table.Tr key={item.id}>
            <Table.Td>{item.name}</Table.Td>
            <Table.Td>
              <Badge color={STATUS_COLORS[item.status]}>{item.status}</Badge>
            </Table.Td>
            <Table.Td>{showDate(item.createdAt)}</Table.Td>
            <Table.Td>
              <ActionIcon
                color="red"
                variant="subtle"
                onClick={() => handleDelete(item.id)}
              >
                <IconTrash size={16} />
              </ActionIcon>
            </Table.Td>
          </Table.Tr>
        ))}
      </Table.Tbody>
    </Table>
  );
}
