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 UserList = ({ onMenuClick }) => {
  const {
    users,
    loadUsers,
    deleteUsers,
    loading,
    error
  } = useAPI();

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

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

  const handleSearch = () => {
    setPage(0);
    loadUsers({ username: searchTerm, page: 0 });
  };

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

    const success = await deleteUsers(selectedIds);
    if (success) {
      setSelectedIds([]);
    }
  };

  const handlePasswordReset = async (userId) => {
    onMenuClick('user-password-reset', null, { esntlId: userId });
  };

  const columns = [
    { key: 'esntlId', label: 'ID' },
    { key: 'username', label: '이름' },
    {
      key: 'status',
      label: '상태',
      render: (value) => (
          <Badge variant={value === 'ACTIVE' ? 'success' : 'destructive'}>
            {value}
          </Badge>
      )
    },
    {
      key: 'userSecurity',
      label: '권한',
      render: (value) => (
          <Badge variant="secondary">
            {value === 'ROLE_ADMIN' ? '관리자' : '사용자'}
          </Badge>
      )
    }
  ];

  const renderRowActions = (row) => (
      <div className="flex gap-2">
        <Button
            variant="outline"
            size="sm"
            onClick={() => onMenuClick('user-edit', null, row)}
        >
          수정
        </Button>
        <Button
            variant="outline"
            size="sm"
            onClick={() => handlePasswordReset(row.esntlId)}
        >
          비밀번호 변경
        </Button>
      </div>
  );

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

  if (error) {
    return (
        <div className="p-4 text-red-500">
          Error loading users: {error}
        </div>
    );
  }

  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
                idField="esntlId"
                data={users}
                columns={columns}
                loading={loading}
                selectable
                selectedIds={selectedIds}
                onSelectIds={setSelectedIds}
                onPageChange={setPage}
                onDelete={handleDelete}
                renderRowActions={renderRowActions}
                deleteDialogTitle="사용자 삭제"
                deleteDialogDescription="선택한 사용자를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
            />
          </CardContent>
        </Card>
      </div>
  );
};

export default UserList;
