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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table';
import { useAPI } from '@/providers/APIProvider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Trash2 } from 'lucide-react';

const DEFAULT_SERVER = {
  id: null,
  name: '',
  scheme: 'http',
  hostname: '',
  port: 80,
  basePath: '/',
  enabled: true,
  serverOptions: []
};

const ServerEditDialog = ({ open, onOpenChange, item }) => {
  const { createServer, updateServer } = useAPI();
  const [server, setServer] = useState(DEFAULT_SERVER);

  // useEffect(() => {
  //   if (item) {
  //     // Ensure serverOptions is always an array
  //     setServer({
  //       ...item,
  //       serverOptions: item.serverOptions || []
  //     });
  //   } else {
  //     setServer(DEFAULT_SERVER);
  //   }
  // }, [item]);
  useEffect(() => {
    console.log('Dialog useEffect - item:', item, 'open:', open); // Debug log
    if (!open) {
      setServer(DEFAULT_SERVER);
      return;
    }

    if (item) {
      setServer({
        ...item,
        serverOptions: item.serverOptions || []
      });
    } else {
      setServer(DEFAULT_SERVER);
    }
  }, [item, open]);

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

  const addOption = () => {
    setServer(prev => ({
      ...prev,
      serverOptions: [
        ...(prev.serverOptions || []),
        {
          optionKey: '',
          optionName: '',
          offset: 0,
          length: 0,
          defaultValue: ''
        }
      ]
    }));
  };

  const removeOption = (index) => {
    setServer(prev => {
      const newOptions = [...prev.serverOptions];
      newOptions.splice(index, 1);
      return { ...prev, serverOptions: newOptions };
    });
  };

  const updateOptionField = (index, field, value) => {
    setServer(prev => {
      const newOptions = [...prev.serverOptions];
      newOptions[index] = { ...newOptions[index], [field]: value };
      return { ...prev, serverOptions: newOptions };
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (server.id) {
        await updateServer(server);
      } else {
        await createServer(server);
      }
      onOpenChange(false);
    } catch (error) {
      console.error('Failed to save server:', error);
      alert('Failed to save server');
    }
  };

  const handleDialogChange = (open) => {
    if (!open) {
      setServer(DEFAULT_SERVER);
    }
    onOpenChange(open);
  };

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

              {/* Server Address */}
              <div className="space-y-2">
                <Label className="must">서버 주소</Label>
                <div className="flex gap-2">
                  <Select
                      value={server.scheme}
                      onValueChange={(value) => handleChange('scheme', value)}
                  >
                    <SelectTrigger className="w-[120px]">
                      <SelectValue placeholder="Scheme" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="http">http</SelectItem>
                      <SelectItem value="https">https</SelectItem>
                      <SelectItem value="tcp">tcp</SelectItem>
                    </SelectContent>
                  </Select>
                  <span className="flex items-center">://</span>
                  <Input
                      placeholder="hostname"
                      required
                      value={server.hostname}
                      onChange={(e) => handleChange('hostname', e.target.value)}
                  />
                  <span className="flex items-center">:</span>
                  <Input
                      type="number"
                      required
                      className="w-[120px]"
                      value={server.port}
                      onChange={(e) => handleChange('port', parseInt(e.target.value))}
                  />
                  <Input
                      placeholder="base path"
                      required
                      value={server.basePath}
                      onChange={(e) => handleChange('basePath', e.target.value)}
                  />
                </div>
              </div>

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

              {/* Server Options */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <Label>서버 메시지 옵션</Label>
                  <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={addOption}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    옵션 추가
                  </Button>
                </div>

                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[150px]">키</TableHead>
                      <TableHead className="w-[150px]">이름</TableHead>
                      <TableHead className="w-[120px]">메시지 위치</TableHead>
                      <TableHead className="w-[120px]">메시지 길이</TableHead>
                      <TableHead>기본 값</TableHead>
                      <TableHead className="w-[80px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(server.serverOptions || []).map((option, index) => (
                        <TableRow key={index}>
                          <TableCell>
                            <Input
                                value={option.optionKey}
                                onChange={(e) => updateOptionField(index, 'optionKey', e.target.value)}
                            />
                          </TableCell>
                          <TableCell>
                            <Input
                                value={option.optionName}
                                onChange={(e) => updateOptionField(index, 'optionName', e.target.value)}
                            />
                          </TableCell>
                          <TableCell>
                            <Input
                                type="number"
                                value={option.offset}
                                onChange={(e) => updateOptionField(index, 'offset', parseInt(e.target.value))}
                            />
                          </TableCell>
                          <TableCell>
                            <Input
                                type="number"
                                value={option.length}
                                onChange={(e) => updateOptionField(index, 'length', parseInt(e.target.value))}
                            />
                          </TableCell>
                          <TableCell>
                            <Input
                                value={option.defaultValue}
                                onChange={(e) => updateOptionField(index, 'defaultValue', e.target.value)}
                            />
                          </TableCell>
                          <TableCell>
                            <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => removeOption(index)}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </form>
          </ScrollArea>

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

export default ServerEditDialog;
