import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import MonacoEditor from '@/components/shared/MonacoEditor';
import {getCSRFToken} from '@/services/token.js';

const defaultScript = `
//message를 사용 가능
var URL = Java.type('java.net.URL');
var HttpURLConnection = Java.type('java.net.HttpURLConnection');
var BufferedReader = Java.type('java.io.BufferedReader');
var InputStreamReader = Java.type('java.io.InputStreamReader');
var StringBuilder = Java.type('java.lang.StringBuilder');

try {
    
    var url = new URL('http://localhost:38080/');
    var connection = url.openConnection();
    connection.setRequestMethod('POST');
    connection.setDoOutput(true);
    
    // Write the body
    var outputStream = connection.getOutputStream();
    var body =  'async_result' + message; 
    outputStream.write(new java.lang.String(body).getBytes('UTF-8'));
    outputStream.close();
    
    console.log(body);
    // Read the response
    var responseCode = connection.getResponseCode();
    if (responseCode === 200) {
        var inputStream = connection.getInputStream();
        var reader = new BufferedReader(new InputStreamReader(inputStream));
        var builder = new StringBuilder();
        var line;
        
        while ((line = reader.readLine()) !== null) {
            builder.append(line);
            builder.append('\\n');
        }
        
        reader.close();
        console.log('POST Response:' + builder.toString());
    } else {
        console.log('HTTP Error! Status:' + responseCode);
    }
} catch (error) {
    console.log('Error making POST request:' + error);
}
`;

const QueueEditDialog = ({ open, onOpenChange, item }) => {
  const [queueHandler, setQueueHandler] = useState({
    queueName: '',
    handlerScript: defaultScript
  });

  // Initialize form when item changes
  useEffect(() => {
    if (item) {
      setQueueHandler(item);
    } else {
      // Reset to default state when creating new
      setQueueHandler({
        queueName: '',
        handlerScript: defaultScript
      });
    }
  }, [item]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!queueHandler.queueName || !queueHandler.handlerScript) {
      return;
    }

    try {
      const url = item ? `/api/queue-handlers/update/${item.queueName}` : '/api/queue-handlers';
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': getCSRFToken()
        },
        body: JSON.stringify(queueHandler)
      });

      if (!response.ok) {
        throw new Error('Failed to save queue handler');
      }

      onOpenChange(false);
    } catch (error) {
      console.error('Failed to save queue handler:', error);
      alert('Failed to save queue handler');
    }
  };

  const handleChange = (field, value) => {
    setQueueHandler(prev => ({ ...prev, [field]: value }));
  };

  return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-full">
          <DialogHeader>
            <DialogTitle>
              {item ? '큐 핸들러 수정' : '큐 핸들러 등록'}
            </DialogTitle>
            <DialogDescription>
              큐 핸들러의 정보를 입력하거나 수정할 수 있습니다. 필수 항목을 모두 입력해주세요.
            </DialogDescription>
          </DialogHeader>

          <ScrollArea className="max-h-[80vh]">
            <form id="queueForm" onSubmit={handleSubmit} className="space-y-4 p-1">
              {/* Queue Name */}
              <div className="space-y-2">
                <Label htmlFor="queueName" className="must">
                  큐 이름
                </Label>
                <Input
                    id="queueName"
                    required
                    value={queueHandler.queueName}
                    onChange={(e) => handleChange('queueName', e.target.value)}
                    disabled={!!item} // Disable editing of queue name for existing handlers
                />
              </div>

              {/* Handler Script */}
              <Card>
                <CardHeader>
                  <CardTitle>핸들러 스크립트</CardTitle>
                </CardHeader>
                <CardContent className="h-[400px]">
                  <MonacoEditor
                      value={queueHandler.handlerScript}
                      language="javascript"
                      onChange={(value) => handleChange('handlerScript', value)}
                      height="full"
                  />
                </CardContent>
              </Card>
            </form>
          </ScrollArea>

          <DialogFooter className="flex justify-end space-x-2">
            <Button variant="secondary" onClick={() => onOpenChange(false)}>
              닫기
            </Button>
            <Button type="submit" variant="default" onClick={handleSubmit}>
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
  );
};

export default QueueEditDialog;
