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 { useAPI } from '@/providers/APIProvider';

const QueueList = ({ onMenuClick }) => {
  const { queues, loading, loadQueues, deleteQueues, startQueue, stopQueue } = useAPI();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedIds, setSelectedIds] = useState([]);
  const [page, setPage] = useState(0);

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

  const handleSearch = () => {
    setPage(0);
    loadQueues({ page: 0, queueName: searchTerm });
  };

  const handleDelete = async () => {
    if (!selectedIds.length) return;
    const success = await deleteQueues(selectedIds);
    if (success) {
      setSelectedIds([]);
    }
  };

  const columns = [
    { key: 'queueName', label: '큐 이름' },
    {
      key: 'active',
      label: '상태',
      render: (value) => (
          <Badge variant={value ? 'success' : 'destructive'}>
            {value ? 'Active' : 'Inactive'}
          </Badge>
      )
    }
  ];

  const renderRowActions = (row) => (
      <div className="flex gap-2">
        <Button
            variant="outline"
            size="sm"
            onClick={() => startQueue(row.queueName)}
        >
          시작
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => stopQueue(row.queueName)}
        >
          정지
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => onMenuClick('queue-edit', null, row)}
        >
          수정
        </Button>
      </div>
  );

  const tableActions = (
      <>
        <Button variant="destructive" onClick={handleSearch}>조회</Button>
        <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={selectedIds.length === 0}
        >
          삭제
        </Button>
        <Button onClick={() => onMenuClick('queue-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={queues}
                columns={columns}
                loading={loading}
                selectable
                selectedIds={selectedIds}
                onSelectIds={setSelectedIds}
                onPageChange={setPage}
                onDelete={handleDelete}
                renderRowActions={renderRowActions}
                deleteDialogTitle="큐 삭제"
                deleteDialogDescription="선택한 큐를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
            />
          </CardContent>
        </Card>
      </div>
  );
};

export default QueueList;
