import { useState } from 'react';
import { Button, Box } from '@mui/material';
import { CreateDialog } from './CreateDialog';
import { useTaskData } from '../hooks/useTaskData';

interface BaseCreateData {
  name: string;
}

interface CreateTaskData extends BaseCreateData {
  groupId: string;
}

interface CreateStepData extends BaseCreateData {
  instructions: string;
  taskId: string;
  order: number;
}

type CreateData = BaseCreateData | CreateTaskData | CreateStepData;

interface CreateButtonsProps {
  type: 'group' | 'task' | 'step';
  parentId?: string;
}

export function CreateButtons({ type, parentId }: CreateButtonsProps) {
  const [open, setOpen] = useState(false);
  const { handleCreateGroup, handleCreateTask, handleCreateStep } = useTaskData();

  const handleSubmit = (data: CreateData) => {
    let stepData: CreateStepData;
    switch (type) {
      case 'group':
        handleCreateGroup(data.name);
        break;
      case 'task':
        if (!parentId) {
          console.error('Cannot create task: no group selected');
          return;
        }
        handleCreateTask(data.name, parentId);
        break;
      case 'step':
        if (!parentId) {
          console.error('Cannot create step: no task selected');
          return;
        }
        stepData = data as CreateStepData;
        handleCreateStep(stepData.name, stepData.instructions, parentId, stepData.order);
        break;
    }
  };

  const getTitle = () => {
    switch (type) {
      case 'group':
        return 'Create New Group';
      case 'task':
        return 'Create New Task';
      case 'step':
        return 'Create New Step';
    }
  };

  const isDisabled = (type === 'task' || type === 'step') && !parentId;

  return (
    <Box>
      <Button
        variant="contained"
        onClick={() => setOpen(true)}
        disabled={isDisabled}
      >
        Create {type.charAt(0).toUpperCase() + type.slice(1)}
      </Button>
      <CreateDialog
        open={open}
        onClose={() => setOpen(false)}
        onSubmit={handleSubmit}
        title={getTitle()}
        type={type}
        parentId={parentId}
      />
    </Box>
  );
}