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.jsx';
import {Input} from '@/components/ui/input.jsx';

const MockRouteList = ({onMenuClick}) => {
  const {
    mockRoutes,
    loadMockRoutes,
    deleteMockRoutes,
    loading
  } = useAPI();

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

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

  const columns = [
    {key: 'method', label: 'Method'},
    {key: 'pathPattern', label: 'Path'},
    {key: 'name', label: '이름'}
  ];

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

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

  const handleEdit = (item) => {
    setSelectedItem(item);
    setDialogState(prev => ({...prev, showMockRouteEdit: true}));
  };

  const handleCreate = () => {
    setSelectedItem(null);
    setDialogState(prev => ({...prev, showMockRouteEdit: true}));
  };

  const handleDialogChange = (key, value) => {
    setDialogState(prev => ({...prev, [key]: value}));
    if (!value) {
      setSelectedItem(null);
    }
  };

  const renderRowActions = (row) => (
      <>
        <Button
            variant="outline"
            size="sm"
            className="mr-2"
            onClick={() => onMenuClick('response-edit', null, row)}

        >
          수정
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => onMenuClick('response-clone', null, {...row, id: null})}
        >
          복제
        </Button>
      </>
  );

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

      </>
  );

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

export default MockRouteList;
