import { useState, useCallback } from 'react';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import { inputBaseClasses } from '@mui/material/InputBase';
import ClickAwayListener from '@mui/material/ClickAwayListener';
import { useBoolean } from '../../../hooks';
import Iconify from '@/shared/components/iconify/iconify';
import { axiosInstance } from '@/utils/axios';
import { useSnackbar } from '@/shared/components/snackbar';

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

interface KanbanColumnAddProps {
  projectId: string;
  onColumnAdded: (columnName: string) => void;
}

export default function KanbanColumnAdd({ projectId, onColumnAdded }: KanbanColumnAddProps) {
  const { enqueueSnackbar } = useSnackbar();
  const [columnName, setColumnName] = useState('');
  const openAddColumn = useBoolean();

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

  const handleCreateColumn = useCallback(async () => {
    try {
      if (columnName && projectId) {
        // Call the parent's onColumnAdded callback with the column name
        onColumnAdded(columnName);
        setColumnName('');
        openAddColumn.onFalse();
      }
    } catch (error) {
      console.error('Failed to create column:', error);
      enqueueSnackbar('Failed to create column', { variant: 'error' });
    }
  }, [columnName, projectId, onColumnAdded, openAddColumn, enqueueSnackbar]);

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

  return (
    <Paper sx={{ minWidth: 250, width: 250 }}>
      {openAddColumn.value ? (
        <ClickAwayListener onClickAway={openAddColumn.onFalse}>
          <TextField
            autoFocus
            fullWidth
            placeholder="New section"
            value={columnName}
            onChange={handleChangeName}
            onKeyUp={handleKeyUpCreateColumn}
            sx={{
              [`& .${inputBaseClasses.input}`]: {
                typography: 'h6',
              },
            }}
          />
        </ClickAwayListener>
      ) : (
        <Button
          fullWidth
          size="large"
          color="inherit"
          variant="outlined"
          startIcon={<Iconify icon="mingcute:add-line" sx={{ mr: -0.5 }} />}
          onClick={openAddColumn.onTrue}
        >
          Add Section
        </Button>
      )}
    </Paper>
  );
}

