import { useState, ChangeEvent, KeyboardEvent } from 'react';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Autocomplete from '@mui/material/Autocomplete';
import Chip from '@mui/material/Chip';

type Props = {
  status: string;
  onAddTask: (task: { name: string; tags: string[] }) => void;
  onCloseAddTask: VoidFunction;
};

export default function KanbanTaskAdd({ status, onAddTask, onCloseAddTask }: Props) {
  const [name, setName] = useState('');
  const [tags, setTags] = useState<string[]>([]);

  const handleKeyUp = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      handleSubmit();
    }
  };

  const handleChangeTaskName = (event: ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const handleSubmit = () => {
    if (name.trim()) {
      const taskData = {
        name,
        tags: tags || [],
      };
      
      console.log('Submitting task data:', taskData);
      onAddTask(taskData);
      
      setName('');
      setTags([]);
    }
  };

  return (
    <Stack spacing={2} sx={{ py: 3 }}>
      <TextField
        fullWidth
        size="small"
        value={name}
        placeholder="Task name"
        onChange={handleChangeTaskName}
        onKeyUp={handleKeyUp}
        InputProps={{
          sx: { typography: 'body2' },
        }}
      />
      
      <Autocomplete
        multiple
        freeSolo
        size="small"
        value={tags}
        onChange={(_, newValue) => setTags(newValue)}
        options={[]} // Empty options as we're using freeSolo
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="Add tags (press Enter after each tag)"
            sx={{ typography: 'body2' }}
          />
        )}
        renderTags={(tagValue, getTagProps) =>
          tagValue.map((tag, index) => (
            <Chip
              {...getTagProps({ index })}
              key={index}
              size="small"
              label={tag}
            />
          ))
        }
      />

      <Stack direction="row" spacing={1}>
        <Button
          fullWidth
          variant="contained"
          color="primary"
          onClick={handleSubmit}
          disabled={!name.trim()}
        >
          Add Task
        </Button>
        <Button
          fullWidth
          variant="outlined"
          color="inherit"
          onClick={onCloseAddTask}
        >
          Cancel
        </Button>
      </Stack>
    </Stack>
  );
}
