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 { Checkbox } from '@/components/ui/checkbox';
import MonacoEditor from '@/components/shared/MonacoEditor';

const defaultScript = `function processJson(message) {
    //process message;

    return "response_message";
}`;

const TCPServerEditDialog = ({ open, onOpenChange, item }) => {
  const [server, setServer] = useState({
    id: null,
    name: '',
    port: 1024,
    active: true,
    script: defaultScript
  });

  // Initialize form when item changes
  useEffect(() => {
    if (item) {
      setServer(item);
    } else {
      // Reset to default state when creating new
      setServer({
        id: null,
        name: '',
        port: 1024,
        active: true,
        script: defaultScript
      });
    }
  }, [item]);

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

    if (!server.name || !server.port) {
      return;
    }

    try {
      const url = server.id ? `/api/socket/update/${server.id}` : '/api/socket';
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        },
        body: JSON.stringify(server)
      });

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

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

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

  return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>
              {server.id == null ? 'TCP 서버 등록' : 'TCP 서버 수정'}
            </DialogTitle>
            <DialogDescription>
              TCP 서버의 정보를 입력하거나 수정할 수 있습니다. 필수 항목을 모두 입력해주세요.
            </DialogDescription>
          </DialogHeader>

          <ScrollArea className="max-h-[80vh]">
            <form id="serverForm" onSubmit={handleSubmit} className="space-y-4 p-1">
              {/* Server Name */}
              <div className="space-y-2">
                <Label htmlFor="name" className="must">
                  서버 이름
                </Label>
                <Input
                    id="name"
                    required
                    value={server.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                />
              </div>

              {/* Port Number */}
              <div className="space-y-2">
                <Label htmlFor="port" className="must">
                  포트
                </Label>
                <Input
                    id="port"
                    type="number"
                    required
                    min="1024"
                    max="65535"
                    value={server.port}
                    onChange={(e) => handleChange('port', parseInt(e.target.value))}
                />
              </div>

              {/* Active Status */}
              <div className="flex items-center space-x-2">
                <Checkbox
                    id="active"
                    checked={server.active}
                    onCheckedChange={(checked) => handleChange('active', checked)}
                />
                <Label htmlFor="active">Active</Label>
              </div>

              {/* Script Editor */}
              <Card>
                <CardHeader>
                  <CardTitle>서버 스크립트</CardTitle>
                </CardHeader>
                <CardContent className="h-[400px]">
                  <MonacoEditor
                      value={server.script}
                      language="javascript"
                      onChange={(value) => handleChange('script', 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 TCPServerEditDialog;
