'use client';
import { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  TextField,
  Button,
  Stack,
} from '@mui/material';
import { useSnackbar } from 'notistack';
import { axiosInstance } from "@/utils/axios";
import Iconify from '@/shared/components/iconify';

interface AIDialogProps {
  open: boolean;
  onClose: () => void;
  onDescriptionGenerated: (description: string) => void;
  type: 'project' | 'task';
  systemPrompt?: string;
}

export default function AIDialog({ 
  open, 
  onClose, 
  onDescriptionGenerated,
  type
}: AIDialogProps) {
  const [loading, setLoading] = useState(false);
  const [prompt, setPrompt] = useState('');
  const { enqueueSnackbar } = useSnackbar();

  const handleGenerateDescription = async () => {
    try {
      setLoading(true);
      
      const response = await axiosInstance.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/ai/generate`,
        {
          prompt,
          type
        }
      );

      if (response.data.description) {
        onDescriptionGenerated(response.data.description);
        onClose();
        enqueueSnackbar('Description generated successfully!', { variant: 'success' });
      } else {
        throw new Error('No description received from server');
      }
    } catch (error) {
      console.error('Error generating description:', error);
      enqueueSnackbar(
         'Failed to generate description', 
        { variant: 'error' }
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>AI Assistant - Generate Project Description</DialogTitle>
      <DialogContent>
        <Stack spacing={3} sx={{ mt: 2 }}>
          <TextField
            fullWidth
            multiline
            rows={3}
            label="Enter your prompt"
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder="Describe your project briefly, and I'll help you create a detailed description..."
          />
          
          <Button
            variant="contained"
            onClick={handleGenerateDescription}
            disabled={!prompt || loading}
            startIcon={<Iconify icon="fluent-emoji:magic-wand" />}
          >
            Generate Description
          </Button>
        </Stack>
      </DialogContent>
    </Dialog>
  );
}
