import React from 'react';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';
import { Box, Typography, CardContent, alpha } from '@mui/material';
import { SortableItem } from './sortable-item';
import { ColumnContainerProps } from './types';
import { styled } from '@mui/system';
import { ScrollBox } from '@/shared/theme/css';

export function EmptyPlaceholder({ text }: { text: string }) {
  return (
    <Box
      sx={{
        p: 2,
        textAlign: 'center',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'text.secondary',
        bgcolor: (theme) => alpha(theme.palette.primary.main, 0.1),
        borderRadius: 1,
        border: '2px dashed',
        borderColor: (theme) => alpha(theme.palette.primary.main, 0.2),
      }}
    >
      <Typography variant="body2">{text}</Typography>
    </Box>
  );
}

export const ColumnContainer: React.FC<ColumnContainerProps> = ({
  columns,
  checkedColumns,
  onCheckChange,
  containerId,
  title,
}) => {
  const { setNodeRef, isOver } = useDroppable({
    id: containerId,
  });

  return (
    <CardContent
      sx={{ flex: 1, display: 'flex', overflowY: 'auto', flexDirection: 'column' }}
    >
      {columns.length > 0 ? (
        <Typography variant="subtitle2" gutterBottom>
          {title}
        </Typography>
      ) : (
        <EmptyPlaceholder
          text={
            containerId === 'available-columns'
              ? 'Glissez un élément ici'
              : "Glissez un élément pour l'ajouter à votre liste"
          }
        />
      )}
      <ScrollBox>
        <SortableContext items={columns.map((col) => col.id)} strategy={verticalListSortingStrategy}>
          <Box
            ref={setNodeRef}
            id={containerId}
            sx={{
              display: 'flex',
              flexDirection: 'column',
              gap: 1,
              flex: 1,
              minHeight: columns.length === 0 ? '200px' : 'auto',
              p: columns.length === 0 ? 2 : 0,
              borderRadius: 1,
              bgcolor: isOver ? (theme) => alpha(theme.palette.primary.main, 0.08) : 'transparent',
              transition: 'background-color 0.2s ease',
            }}
          >
            {columns.map((column) => (
              <SortableItem
                key={column.id}
                id={column.id}
                label={column.label}
                checked={checkedColumns.includes(column.id)}
                onCheckChange={() => onCheckChange(column.id)}
              />
            ))}
          </Box>
        </SortableContext>
      </ScrollBox>
    </CardContent>
  );
};
