import { useState, useCallback } from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import MenuItem from '@mui/material/MenuItem';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import CircleIcon from '@mui/icons-material/Circle';
import Popover from '@mui/material/Popover';
import { alpha } from '@mui/material/styles';

import Iconify from '@/shared/components/iconify';
import { usePopover } from '@/hooks/use-popover';

// ----------------------------------------------------------------------

const COLORS = [
  '', // Add empty string for default/reset option
  '#00A76F', // green
  '#FF5630', // red
  '#FFAB00', // yellow
  '#1890FF', // blue
  '#8E33FF', // purple
  '#00B8D9', // cyan
  '#36B37E', // teal
  '#FF5C93', // pink
  '#54D62C', // bright green
  '#FFA723', // orange
];

type Props = {
  columnName: string;
  color?: string;
  onDelete: () => Promise<void>;
  onClear: () => Promise<void>;
  onUpdateColumn: (columnName: string) => Promise<void>;
  onUpdateColor: (color: string) => void;
};

export default function KanbanColumnToolBar({
  columnName,
  color,
  onDelete,
  onClear,
  onUpdateColumn,
  onUpdateColor,
}: Props) {
  const [name, setName] = useState(columnName);
  const [editing, setEditing] = useState(false);
  const popover = usePopover();
  const [anchorElColor, setAnchorElColor] = useState<null | HTMLElement>(null);

  const handleOpenColorPicker = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElColor(event.currentTarget);
  };

  const handleCloseColorPicker = () => {
    setAnchorElColor(null);
  };

  const handleClickColor = (newColor: string) => {
    onUpdateColor(newColor);
    handleCloseColorPicker();
  };

  const handleChangeName = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  }, []);

  const handleUpdateName = useCallback(() => {
    if (name !== columnName) {
      onUpdateColumn(name);
    }
    setEditing(false);
  }, [name, columnName, onUpdateColumn]);

  const handleKeyUp = useCallback(
    (event: React.KeyboardEvent<HTMLInputElement>) => {
      if (event.key === 'Enter') {
        handleUpdateName();
      }
    },
    [handleUpdateName]
  );

  return (
    <>
      <Stack
        spacing={1}
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{
          pt: 3,
          pb: 2,
          px: 2,
          bgcolor: (theme) => alpha(color || theme.palette.grey[500], 0.08),
        }}
      >
        <Stack direction="row" alignItems="center" spacing={1}>
          {editing ? (
            <input
              type="text"
              value={name}
              onChange={handleChangeName}
              onBlur={handleUpdateName}
              onKeyUp={handleKeyUp}
              autoFocus
              style={{
                width: '100%',
                fontSize: '1rem',
                padding: '4px 8px',
                borderRadius: '4px',
                border: '1px solid #ddd',
              }}
            />
          ) : (
            <Typography variant="h6" onClick={() => setEditing(true)} sx={{ cursor: 'pointer' }}>
              {columnName}
            </Typography>
          )}

          <IconButton 
            size="small" 
            onClick={handleOpenColorPicker}
            sx={{ 
              width: 24, 
              height: 24,
              bgcolor: 'background.paper',
              border: '1px solid',
              borderColor: 'divider',
              '&:hover': { bgcolor: 'background.paper' },
            }}
          >
            <CircleIcon sx={{ 
              color: color || 'action.disabled',
              width: 16,
              height: 16,
            }} />
          </IconButton>
        </Stack>

        <IconButton
          size="small"
          onClick={popover.onOpen}
          sx={{
            '&:hover': {
              bgcolor: 'action.selected',
            },
          }}
        >
          <Iconify icon="eva:more-horizontal-fill" />
        </IconButton>
      </Stack>

      <Popover
        open={Boolean(anchorElColor)}
        anchorEl={anchorElColor}
        onClose={handleCloseColorPicker}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        PaperProps={{
          sx: {
            p: 1,
            width: 180,
            '& .MuiMenuItem-root': {
              px: 1,
              typography: 'body2',
              borderRadius: 0.75,
            },
          },
        }}
      >
        <Stack direction="row" spacing={0.5} sx={{ p: 0.5 }}>
          {COLORS.map((colorOption) => (
            <IconButton
              key={colorOption}
              size="small"
              onClick={() => handleClickColor(colorOption)}
              sx={{
                p: 0,
                width: 24,
                height: 24,
                bgcolor: colorOption || 'background.paper',
                border: (theme) => `solid 1px ${theme.palette.divider}`,
                '&:hover': { bgcolor: colorOption ? alpha(colorOption, 0.8) : 'background.paper' },
                ...(colorOption === '' && {
                  '&:after': {
                    content: "'×'",
                    color: 'text.disabled',
                    fontSize: 16,
                    fontWeight: 'bold',
                    lineHeight: 0,
                  },
                }),
              }}
            >
              {color === colorOption && colorOption !== '' && (
                <Iconify icon="eva:checkmark-fill" sx={{ width: 16, height: 16, color: 'white' }} />
              )}
            </IconButton>
          ))}
        </Stack>
      </Popover>

      <Popover
        open={popover.open}
        onClose={popover.onClose}
        anchorEl={popover.anchorEl}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        PaperProps={{
          sx: { width: 200, p: 1 },
        }}
      >
        <MenuItem onClick={onClear} sx={{ color: 'error.main' }}>
          <Iconify icon="solar:trash-bin-trash-bold" />
          Clear Column
        </MenuItem>

        <MenuItem onClick={onDelete} sx={{ color: 'error.main' }}>
          <Iconify icon="solar:trash-bin-trash-bold" />
          Delete Column
        </MenuItem>
      </Popover>
    </>
  );
}
