import { useState } from 'react';
import { Modal, TextInput, Textarea, Button, Stack } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { useMutation } from '@tanstack/react-query';
import api from '../../services/api';

interface IdeaModalProps {
  opened: boolean;
  onClose: () => void;
}

export function IdeaModal({ opened, onClose }: IdeaModalProps) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const submitIdea = useMutation({
    mutationFn: async () => {
      const { data } = await api.post('/ideas', { title, description });
      return data;
    },
    onSuccess: () => {
      notifications.show({ message: 'Idea submitted — thank you!', color: 'green' });
      setTitle('');
      setDescription('');
      onClose();
    },
    onError: (err: any) => {
      notifications.show({
        message: err.response?.data?.message || 'Failed to submit idea',
        color: 'red',
      });
    },
  });

  const handleClose = () => {
    setTitle('');
    setDescription('');
    onClose();
  };

  return (
    <Modal opened={opened} onClose={handleClose} title="Submit an Idea" size="md">
      <Stack>
        <TextInput
          label="Title"
          placeholder="Brief summary of your idea"
          required
          value={title}
          onChange={(e) => setTitle(e.currentTarget.value)}
          maxLength={255}
        />
        <Textarea
          label="Description"
          placeholder="Describe your idea in more detail (optional)"
          minRows={4}
          value={description}
          onChange={(e) => setDescription(e.currentTarget.value)}
        />
        <Button
          onClick={() => submitIdea.mutate()}
          loading={submitIdea.isPending}
          disabled={!title.trim()}
        >
          Submit Idea
        </Button>
      </Stack>
    </Modal>
  );
}
