import React from 'react';
import { Button } from '@/components/ui/button';
import DataTable from '@/components/shared/DataTable';
import { useAPI } from '@/providers/APIProvider';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';

const ServerList = ({ onMenuClick }) => {
  const {
    serverList,
    loadServerList,
    deleteServers,
    loading
  } = useAPI();

  const [searchTerm, setSearchTerm] = React.useState('');
  const [selectedIds, setSelectedIds] = React.useState([]);
  const [page, setPage] = React.useState(0);

  React.useEffect(() => {
    loadServerList({ page });
  }, [page, loadServerList]);

  const columns = [
    { key: 'name', label: '이름' },
    {
      key: 'address',
      label: '주소',
      render: (_, row) => `${row.scheme}://${row.hostname}:${row.port}${row.basePath}`
    },
    {
      key: 'enabled',
      label: '사용 중',
      render: (value) => (
          <Badge variant={value ? 'success' : 'destructive'}>
            {value ? '사용' : '미사용'}
          </Badge>
      )
    }
  ];

  const handleSearch = () => {
    setPage(0);
    loadServerList({ name: searchTerm, page: 0 });
  };

  const handleDelete = async () => {
    const success = await deleteServers(selectedIds);
    if (success) {
      setSelectedIds([]);
    }
  };

  const renderRowActions = (row) => (
      <>
        <Button
            variant="outline"
            size="sm"
            className="mr-2"
            // onClick={() => onMenuClick('server-edit', null, {...row})}
            onClick={() => {
              console.log('Before onMenuClick:', row); // Debug log
              onMenuClick('server-edit', null, row);
            }}
        >
          수정
        </Button>
      </>
  );

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

  return (
      <div className="container mx-auto p-4">
        <Card>
          <CardHeader>
            <CardTitle>서버 목록</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={serverList}
                columns={columns}
                loading={loading}
                selectable
                selectedIds={selectedIds}
                onSelectIds={setSelectedIds}
                onPageChange={setPage}
                onDelete={handleDelete}
                renderRowActions={renderRowActions}
                deleteDialogTitle="서버 삭제"
                deleteDialogDescription="선택한 서버를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
            />
          </CardContent>
        </Card>
      </div>
  );
};

export default ServerList;
