import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import DataTable from '@/components/shared/DataTable';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { format } from 'date-fns';

const TCPServerList = ({ onMenuClick }) => {
  const [servers, setServers] = useState({
    content: [],
    totalPages: 0,
    number: 0,
    first: true,
    last: true,
    numberOfElements: 0,
    totalElements: 0
  });
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedIds, setSelectedIds] = useState([]);
  const [page, setPage] = useState(0);

  const loadServers = async (params = { page: 0 }) => {
    setLoading(true);
    try {
      const searchParams = new URLSearchParams({
        page: params.page,
        size: 10,
        ...(searchTerm && { name: searchTerm })
      });

      const response = await fetch(`/api/socket?${searchParams}`);
      const data = await response.json();
      setServers(data);
    } catch (error) {
      console.error('Error loading servers:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadServers({ page });
  }, [page]);

  const handleSearch = () => {
    setPage(0);
    loadServers({ page: 0 });
  };

  const handleDelete = async () => {
    if (!selectedIds.length) return;

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

      if (response.ok) {
        setSelectedIds([]);
        loadServers({ page });
      }
    } catch (error) {
      console.error('Error deleting servers:', error);
    }
  };

  const handleStartServer = async (id) => {
    try {
      const response = await fetch(`/api/socket/${id}/start`, {
        method: 'POST',
        headers: {
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        }
      });

      if (response.ok) {
        loadServers({ page });
      }
    } catch (error) {
      console.error('Error starting server:', error);
    }
  };

  const handleStopServer = async (id) => {
    try {
      const response = await fetch(`/api/socket/${id}/stop`, {
        method: 'POST',
        headers: {
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        }
      });

      if (response.ok) {
        loadServers({ page });
      }
    } catch (error) {
      console.error('Error stopping server:', error);
    }
  };

  const columns = [
    { key: 'name', label: 'Name' },
    { key: 'port', label: 'Port' },
    {
      key: 'active',
      label: 'Status',
      render: (value) => (
          <Badge variant={value ? 'success' : 'destructive'}>
            {value ? 'Active' : 'Inactive'}
          </Badge>
      )
    },
    {
      key: 'lastModified',
      label: 'Last Modified',
      render: (value) => format(new Date(value), 'yyyy-MM-dd HH:mm:ss')
    }
  ];

  const renderRowActions = (row) => (
      <div className="flex gap-2">
        <Button
            variant="outline"
            size="sm"
            disabled={!row.active}
            onClick={() => handleStartServer(row.id)}
        >
          Start
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => handleStopServer(row.id)}
        >
          Stop
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => onMenuClick('socket-edit', null, row)}
        >
          Edit
        </Button>
      </div>
  );

  const tableActions = (
      <>
        <Button variant="destructive" onClick={handleSearch}>조회</Button>
        <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={selectedIds.length === 0}
        >
          삭제
        </Button>
        <Button onClick={() => onMenuClick('socket-add')}>등록</Button>
      </>
  );

  return (
      <div className="container mx-auto p-4">
        <Card>
          <CardHeader>
            <CardTitle>TCP Server List</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-4 mb-4">
              <div className="flex-1 max-w-sm">
                <Input
                    placeholder="서버 이름으로 검색"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onKeyUp={(e) => {
                      if (e.key === 'Enter') {
                        handleSearch();
                      }
                    }}
                />
              </div>
              {tableActions}
            </div>
            <DataTable
                data={servers}
                columns={columns}
                loading={loading}
                selectable
                selectedIds={selectedIds}
                onSelectIds={setSelectedIds}
                onPageChange={setPage}
                onDelete={handleDelete}
                renderRowActions={renderRowActions}
                deleteDialogTitle="서버 삭제"
                deleteDialogDescription="선택한 서버를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
            />
          </CardContent>
        </Card>
      </div>
  );
};

export default TCPServerList;
