import { createColumnHelper } from '@tanstack/react-table';
import { Chip, Box, IconButton } from '@mui/material';
import { Delete } from '@mui/icons-material';
import type { Idea, IdeaStatus, IdeaPriority } from '../../types/idea';
import { EditableCell } from './EditableCell';
import { statusOptions, priorityOptions } from './constants';
import { DragHandle } from './DraggableRow';

const columnHelper = createColumnHelper<Idea>();

const statusColors: Record<
  IdeaStatus,
  'default' | 'primary' | 'secondary' | 'success' | 'error'
> = {
  backlog: 'default',
  todo: 'primary',
  in_progress: 'secondary',
  done: 'success',
  cancelled: 'error',
};

const priorityColors: Record<
  IdeaPriority,
  'default' | 'info' | 'warning' | 'error'
> = {
  low: 'default',
  medium: 'info',
  high: 'warning',
  critical: 'error',
};

export const createColumns = (onDelete: (id: string) => void) => [
  columnHelper.display({
    id: 'drag',
    header: '',
    cell: () => <DragHandle />,
    size: 40,
    enableSorting: false,
  }),
  columnHelper.accessor('title', {
    header: 'Название',
    cell: (info) => (
      <EditableCell
        idea={info.row.original}
        field="title"
        value={info.getValue()}
        renderDisplay={(value) => (
          <Box sx={{ fontWeight: 500 }}>{value ?? '—'}</Box>
        )}
      />
    ),
    size: 250,
  }),
  columnHelper.accessor('status', {
    header: 'Статус',
    cell: (info) => {
      const status = info.getValue();
      const label =
        statusOptions.find((s) => s.value === status)?.label ?? status;
      return (
        <EditableCell
          idea={info.row.original}
          field="status"
          value={status}
          type="select"
          options={statusOptions}
          renderDisplay={() => (
            <Chip label={label} color={statusColors[status]} size="small" />
          )}
        />
      );
    },
    size: 140,
  }),
  columnHelper.accessor('priority', {
    header: 'Приоритет',
    cell: (info) => {
      const priority = info.getValue();
      const label =
        priorityOptions.find((p) => p.value === priority)?.label ?? priority;
      return (
        <EditableCell
          idea={info.row.original}
          field="priority"
          value={priority}
          type="select"
          options={priorityOptions}
          renderDisplay={() => (
            <Chip
              label={label}
              color={priorityColors[priority]}
              size="small"
              variant="outlined"
            />
          )}
        />
      );
    },
    size: 120,
  }),
  columnHelper.accessor('module', {
    header: 'Модуль',
    cell: (info) => (
      <EditableCell
        idea={info.row.original}
        field="module"
        value={info.getValue()}
        renderDisplay={(value) => value ?? '—'}
      />
    ),
    size: 120,
  }),
  columnHelper.accessor('targetAudience', {
    header: 'Целевая аудитория',
    cell: (info) => (
      <EditableCell
        idea={info.row.original}
        field="targetAudience"
        value={info.getValue()}
        renderDisplay={(value) => value ?? '—'}
      />
    ),
    size: 150,
  }),
  columnHelper.accessor('description', {
    header: 'Описание',
    cell: (info) => {
      const value = info.getValue();
      return (
        <EditableCell
          idea={info.row.original}
          field="description"
          value={value}
          renderDisplay={(val) => {
            if (!val) return '—';
            return val.length > 80 ? `${val.slice(0, 80)}...` : val;
          }}
        />
      );
    },
    size: 200,
  }),
  columnHelper.display({
    id: 'actions',
    header: '',
    cell: (info) => (
      <IconButton
        size="small"
        onClick={() => onDelete(info.row.original.id)}
        sx={{ opacity: 0.5, '&:hover': { opacity: 1 } }}
      >
        <Delete fontSize="small" />
      </IconButton>
    ),
    size: 50,
  }),
];
