import React, { useState, useEffect } from 'react';
import { 
  DataTable, 
  TableColumn,
  Badge,
  Group,
  Text,
  Stack
} from '@skybridge/web-components';
import { Avatar } from '@mantine/core';
import { IconUser, IconMail } from '@tabler/icons-react';
import UserSidebar from './UserSidebar';
import { userService } from '../services/userService';
import { User, UserStatus, UserRole, ListUsersRequest } from '../types/user';

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [totalUsers, setTotalUsers] = useState(0);
  const [userSidebarOpened, setUserSidebarOpened] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);

  const pageSize = 10;

  const loadUsers = async (page: number = currentPage, newFilters = filters) => {
    setLoading(true);
    try {
      const request: ListUsersRequest = {
        search: newFilters.search || undefined,
        status: newFilters.status as UserStatus || undefined,
        role: newFilters.role as UserRole || undefined,
        limit: pageSize,
        offset: (page - 1) * pageSize,
        order_by: 'created_at',
        order_dir: 'desc',
      };

      const response = await userService.listUsers(request);
      setUsers(response.users);
      setTotalUsers(response.total);
      setCurrentPage(page);
    } catch (error) {
      console.error('Failed to load users:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleAdd = () => {
    setEditingUser(null);
    setUserSidebarOpened(true);
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setUserSidebarOpened(true);
  };

  const handleDelete = async (user: User) => {
    await userService.deleteUser(user.id);
    loadUsers();
  };

  const handleSuccess = () => {
    setUserSidebarOpened(false);
    setEditingUser(null);
    loadUsers();
  };

  const handleFiltersChange = (newFilters) => {
    setFilters(newFilters);
    setCurrentPage(1);
  };

  const columns: TableColumn[] = [
    { 
      key: 'user', 
      label: 'User',
      render: (_, user: User) => (
        <Group gap="sm">
          <Avatar
            src={user.avatar || null}
            radius="sm"
            size={32}
          >
            <IconUser size={16} />
          </Avatar>
          <div>
            <Text size="sm" fw={500}>
              {user.display_name || `${user.first_name} ${user.last_name}`}
            </Text>
            <Text size="xs" c="dimmed">
              {user.first_name} {user.last_name}
            </Text>
          </div>
        </Group>
      )
    },
    { 
      key: 'email', 
      label: 'Email',
      render: (value) => (
        <Group gap="xs">
          <IconMail size={14} />
          <Text size="sm">{value}</Text>
        </Group>
      )
    },
    { 
      key: 'role', 
      label: 'Role',
      render: (value) => {
        const roleColors = {
          admin: 'red',
          moderator: 'orange', 
          user: 'blue',
          viewer: 'gray'
        };
        return (
          <Badge color={roleColors[value] || 'blue'} size="sm">
            {value}
          </Badge>
        );
      }
    },
    { 
      key: 'status', 
      label: 'Status' 
    },
    { 
      key: 'created_at', 
      label: 'Created',
      render: (value) => (
        <Text size="sm">
          {new Date(value).toLocaleDateString()}
        </Text>
      )
    },
  ];

  return (
    <Stack 
      gap="md" 
      style={{
        transition: 'margin-right 0.3s ease',
        marginRight: userSidebarOpened ? '400px' : '0',
      }}
    >
      <DataTable
        data={users}
        columns={columns}
        loading={loading}
        title="User Management"
        total={totalUsers}
        page={currentPage}
        pageSize={pageSize}
        onPageChange={loadUsers}
        searchable
        filters={filters}
        onFiltersChange={handleFiltersChange}
        onAdd={handleAdd}
        onEdit={handleEdit}
        onDelete={handleDelete}
        onRefresh={() => loadUsers()}
        emptyMessage="No users found"
      />
      
      <UserSidebar
        opened={userSidebarOpened}
        onClose={() => setUserSidebarOpened(false)}
        onSuccess={handleSuccess}
        editUser={editingUser}
      />
    </Stack>
  );
};

export default UserManagement;