import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Tabs,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Chip,
  IconButton,
  Alert,
  CircularProgress,
  Grid,
  Card,
  CardContent,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Checkbox,
  FormGroup,
  FormControlLabel,
  Tooltip,
  List,
  ListItem,
  ListItemText,
  Divider,
  Badge
} from '@mui/material';
import {
  Add,
  Edit,
  Delete,
  Security,
  Group,
  Assessment,
  Visibility,
  VisibilityOff,
  Info,
  Warning,
  CheckCircle,
  Block,
  ArrowBack
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import api from '../utils/api';
import { useSecurityNotification } from './SecurityNotificationProvider';

function TabPanel(props) {
  const { children, value, index, ...other } = props;
  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
}

const RBACDashboard = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { showNotification } = useSecurityNotification();
  
  const [tabValue, setTabValue] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // Roles state
  const [roles, setRoles] = useState([]);
  const [selectedRole, setSelectedRole] = useState(null);
  const [roleDialog, setRoleDialog] = useState(false);
  const [roleFormData, setRoleFormData] = useState({
    role_key: '',
    name: '',
    description: '',
    permissions: []
  });
  
  // Permissions state
  const [permissions, setPermissions] = useState([]);
  const [permissionCategories, setPermissionCategories] = useState({});
  const [myPermissions, setMyPermissions] = useState(null);
  
  // Users state
  const [users, setUsers] = useState([]);
  const [userRoleDialog, setUserRoleDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [newUserRole, setNewUserRole] = useState('');
  
  // Audit log state
  const [auditLogs, setAuditLogs] = useState([]);
  const [auditFilters, setAuditFilters] = useState({
    action: '',
    userId: '',
    targetType: ''
  });
  
  // Statistics state
  const [stats, setStats] = useState(null);

  useEffect(() => {
    loadData();
  }, [tabValue]);

  const loadData = async () => {
    setLoading(true);
    setError(null);
    
    try {
      if (tabValue === 0) {
        await Promise.all([loadRoles(), loadPermissions()]);
      } else if (tabValue === 1) {
        await Promise.all([loadUsers(), loadRoles()]);
      } else if (tabValue === 2) {
        await loadAuditLog();
      } else if (tabValue === 3) {
        await loadStats();
      } else if (tabValue === 4) {
        await loadMyPermissions();
      }
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to load data');
      showNotification('error', err.response?.data?.error || 'Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const loadRoles = async () => {
    try {
      const response = await api.get('/rbac/roles');
      setRoles(Array.isArray(response.data) ? response.data : []);
    } catch (err) {
      console.error('Failed to load roles:', err);
      setRoles([]);
    }
  };

  const loadPermissions = async () => {
    try {
      const response = await api.get('/rbac/permissions');
      setPermissions(Array.isArray(response.data.permissions) ? response.data.permissions : []);
      setPermissionCategories(response.data.categories || {});
    } catch (err) {
      console.error('Failed to load permissions:', err);
      setPermissions([]);
      setPermissionCategories({});
    }
  };

  const loadMyPermissions = async () => {
    try {
      const response = await api.get('/rbac/my-permissions');
      setMyPermissions(response.data);
    } catch (err) {
      console.error('Failed to load my permissions:', err);
      setMyPermissions({ permissions: [], role: null });
    }
  };

  const loadUsers = async () => {
    try {
      const response = await api.get('/users');
      setUsers(Array.isArray(response.data) ? response.data : []);
    } catch (err) {
      console.error('Failed to load users:', err);
      setUsers([]);
    }
  };

  const loadAuditLog = async () => {
    try {
      const params = new URLSearchParams();
      if (auditFilters.action) params.append('action', auditFilters.action);
      if (auditFilters.userId) params.append('userId', auditFilters.userId);
      if (auditFilters.targetType) params.append('targetType', auditFilters.targetType);
      
      const response = await api.get(`/rbac/audit-log?${params.toString()}`);
      setAuditLogs(Array.isArray(response.data.logs) ? response.data.logs : []);
    } catch (err) {
      console.error('Failed to load audit log:', err);
      setAuditLogs([]);
    }
  };

  const loadStats = async () => {
    try {
      const response = await api.get('/rbac/stats');
      setStats(response.data);
    } catch (err) {
      console.error('Failed to load stats:', err);
      setStats(null);
    }
  };

  const handleCreateRole = () => {
    setSelectedRole(null);
    setRoleFormData({
      role_key: '',
      name: '',
      description: '',
      permissions: []
    });
    setRoleDialog(true);
  };

  const handleEditRole = (role) => {
    setSelectedRole(role);
    setRoleFormData({
      role_key: role.role_key,
      name: role.name,
      description: role.description,
      permissions: role.permissions
    });
    setRoleDialog(true);
  };

  const handleSaveRole = async () => {
    try {
      if (selectedRole) {
        // Update existing role
        await api.patch(`/rbac/roles/${selectedRole.role_key}`, {
          name: roleFormData.name,
          description: roleFormData.description,
          permissions: roleFormData.permissions
        });
        showNotification('success', t('rbac.roleUpdated'));
      } else {
        // Create new role
        await api.post('/rbac/roles', roleFormData);
        showNotification('success', t('rbac.roleCreated'));
      }
      setRoleDialog(false);
      loadRoles();
    } catch (err) {
      showNotification('error', err.response?.data?.error || 'Failed to save role');
    }
  };

  const handleDeleteRole = async (roleKey) => {
    if (!window.confirm(t('rbac.confirmDeleteRole'))) return;
    
    try {
      await api.delete(`/rbac/roles/${roleKey}`);
      showNotification('success', t('rbac.roleDeleted'));
      loadRoles();
    } catch (err) {
      showNotification('error', err.response?.data?.error || 'Failed to delete role');
    }
  };

  const handleTogglePermission = (permissionKey) => {
    setRoleFormData(prev => ({
      ...prev,
      permissions: prev.permissions.includes(permissionKey)
        ? prev.permissions.filter(p => p !== permissionKey)
        : [...prev.permissions, permissionKey]
    }));
  };

  const handleAssignRole = (user) => {
    setSelectedUser(user);
    setNewUserRole(user.role);
    setUserRoleDialog(true);
  };

  const handleSaveUserRole = async () => {
    try {
      await api.post(`/rbac/users/${selectedUser.id}/role`, {
        role: newUserRole
      });
      showNotification('success', t('rbac.roleAssigned'));
      setUserRoleDialog(false);
      loadUsers();
    } catch (err) {
      showNotification('error', err.response?.data?.error || 'Failed to assign role');
    }
  };

  const getRoleColor = (roleKey) => {
    const colors = {
      admin: 'error',
      moderator: 'warning',
      user: 'primary',
      viewer: 'info'
    };
    return colors[roleKey] || 'default';
  };

  const getCategoryIcon = (category) => {
    const icons = {
      'User Management': <Group />,
      'Session Management': <Security />,
      'Content Management': <Assessment />,
      'System & Settings': <Info />,
      'Security Management': <Security />,
      'Search & Discovery': <Visibility />,
      'VPN & Network': <Warning />
    };
    return icons[category] || <Info />;
  };

  if (loading && tabValue === 0) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Security sx={{ mr: 1, fontSize: 32 }} />
          <Typography variant="h5" fontWeight="bold">
            {t('rbac.dashboard')}
          </Typography>
        </Box>
        <Button
          variant="outlined"
          startIcon={<ArrowBack />}
          onClick={() => navigate('/security')}
        >
          {t('backToSecurity')}
        </Button>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}

      <Paper>
        <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)}>
          <Tab label={t('rbac.rolesAndPermissions')} />
          <Tab label={t('rbac.userRoles')} />
          <Tab label={t('rbac.auditLog')} />
          <Tab label={t('rbac.statistics')} />
          <Tab label={t('rbac.myPermissions')} />
        </Tabs>

        {/* Roles & Permissions Tab */}
        <TabPanel value={tabValue} index={0}>
          <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between' }}>
            <Typography variant="h6">{t('rbac.roles')}</Typography>
            <Button
              variant="contained"
              startIcon={<Add />}
              onClick={handleCreateRole}
            >
              {t('rbac.createRole')}
            </Button>
          </Box>

          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('rbac.roleName')}</TableCell>
                  <TableCell>{t('rbac.description')}</TableCell>
                  <TableCell>{t('rbac.permissions')}</TableCell>
                  <TableCell>{t('rbac.type')}</TableCell>
                  <TableCell align="right">{t('actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {roles.map((role) => (
                  <TableRow key={role.role_key}>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Chip
                          label={role.name}
                          color={getRoleColor(role.role_key)}
                          size="small"
                          sx={{ mr: 1 }}
                        />
                        <Typography variant="caption" color="text.secondary">
                          ({role.role_key})
                        </Typography>
                      </Box>
                    </TableCell>
                    <TableCell>{role.description}</TableCell>
                    <TableCell>
                      <Badge badgeContent={role.permissions.length} color="primary">
                        <Chip
                          label={t('rbac.permissionsCount')}
                          size="small"
                          variant="outlined"
                        />
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {role.is_system_role ? (
                        <Chip label={t('rbac.system')} size="small" color="default" />
                      ) : (
                        <Chip label={t('rbac.custom')} size="small" color="secondary" />
                      )}
                    </TableCell>
                    <TableCell align="right">
                      <Tooltip title={t('edit')}>
                        <IconButton
                          size="small"
                          onClick={() => handleEditRole(role)}
                          disabled={role.is_system_role}
                        >
                          <Edit />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title={t('delete')}>
                        <IconButton
                          size="small"
                          onClick={() => handleDeleteRole(role.role_key)}
                          disabled={role.is_system_role}
                          color="error"
                        >
                          <Delete />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* User Roles Tab */}
        <TabPanel value={tabValue} index={1}>
          <Typography variant="h6" sx={{ mb: 2 }}>
            {t('rbac.manageUserRoles')}
          </Typography>

          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('username')}</TableCell>
                  <TableCell>{t('email')}</TableCell>
                  <TableCell>{t('role')}</TableCell>
                  <TableCell>{t('status')}</TableCell>
                  <TableCell align="right">{t('actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {users.map((u) => (
                  <TableRow key={u.id}>
                    <TableCell>{u.username}</TableCell>
                    <TableCell>{u.email}</TableCell>
                    <TableCell>
                      <Chip
                        label={u.role}
                        color={getRoleColor(u.role)}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>
                      {u.is_active ? (
                        <Chip
                          label={t('active')}
                          color="success"
                          size="small"
                          icon={<CheckCircle />}
                        />
                      ) : (
                        <Chip
                          label={t('inactive')}
                          color="default"
                          size="small"
                          icon={<Block />}
                        />
                      )}
                    </TableCell>
                    <TableCell align="right">
                      <Button
                        size="small"
                        variant="outlined"
                        onClick={() => handleAssignRole(u)}
                        disabled={u.id === user?.id}
                      >
                        {t('rbac.changeRole')}
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Audit Log Tab */}
        <TabPanel value={tabValue} index={2}>
          <Typography variant="h6" sx={{ mb: 2 }}>
            {t('rbac.permissionAuditLog')}
          </Typography>

          <Grid container spacing={2} sx={{ mb: 3 }}>
            <Grid item xs={12} md={4}>
              <FormControl fullWidth size="small">
                <InputLabel>{t('rbac.filterByAction')}</InputLabel>
                <Select
                  value={auditFilters.action}
                  onChange={(e) => setAuditFilters({ ...auditFilters, action: e.target.value })}
                >
                  <MenuItem value="">{t('all')}</MenuItem>
                  <MenuItem value="role_created">{t('rbac.roleCreated')}</MenuItem>
                  <MenuItem value="role_updated">{t('rbac.roleUpdated')}</MenuItem>
                  <MenuItem value="role_deleted">{t('rbac.roleDeleted')}</MenuItem>
                  <MenuItem value="role_assigned">{t('rbac.roleAssigned')}</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={4}>
              <Button
                variant="contained"
                fullWidth
                onClick={loadAuditLog}
              >
                {t('apply')}
              </Button>
            </Grid>
          </Grid>

          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>{t('timestamp')}</TableCell>
                  <TableCell>{t('user')}</TableCell>
                  <TableCell>{t('action')}</TableCell>
                  <TableCell>{t('rbac.target')}</TableCell>
                  <TableCell>{t('rbac.changes')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {auditLogs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell>
                      {new Date(log.created_at).toLocaleString()}
                    </TableCell>
                    <TableCell>{log.username}</TableCell>
                    <TableCell>
                      <Chip label={log.action} size="small" />
                    </TableCell>
                    <TableCell>
                      {log.target_type} #{log.target_id}
                    </TableCell>
                    <TableCell>
                      <Tooltip title={JSON.stringify({ old: log.old_value, new: log.new_value }, null, 2)}>
                        <IconButton size="small">
                          <Info />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Statistics Tab */}
        <TabPanel value={tabValue} index={3}>
          <Typography variant="h6" sx={{ mb: 3 }}>
            {t('rbac.rbacStatistics')}
          </Typography>

          {stats && (
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <Card>
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      {t('rbac.roleDistribution')}
                    </Typography>
                    <List>
                      {Array.isArray(stats.role_distribution) && stats.role_distribution.map((role) => (
                        <ListItem key={role.role_key}>
                          <ListItemText
                            primary={role.name}
                            secondary={`${role.user_count} ${t('users')}`}
                          />
                          <Chip
                            label={role.user_count}
                            color={getRoleColor(role.role_key)}
                          />
                        </ListItem>
                      ))}
                    </List>
                  </CardContent>
                </Card>
              </Grid>

              <Grid item xs={12} md={6}>
                <Card>
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      {t('rbac.recentActions')}
                    </Typography>
                    <List>
                      {Array.isArray(stats.recent_actions) && stats.recent_actions.map((action, idx) => (
                        <ListItem key={idx}>
                          <ListItemText
                            primary={action.action}
                            secondary={`${action.count} ${t('rbac.times')}`}
                          />
                          <Badge badgeContent={action.count} color="primary" />
                        </ListItem>
                      ))}
                    </List>
                  </CardContent>
                </Card>
              </Grid>

              <Grid item xs={12}>
                <Alert severity="info">
                  <Typography>
                    {t('rbac.totalPermissions')}: <strong>{stats.total_permissions}</strong> | 
                    {t('rbac.totalRoles')}: <strong>{stats.total_roles}</strong>
                  </Typography>
                </Alert>
              </Grid>
            </Grid>
          )}
        </TabPanel>

        {/* My Permissions Tab */}
        <TabPanel value={tabValue} index={4}>
          <Typography variant="h6" sx={{ mb: 3 }}>
            {t('rbac.yourPermissions')}
          </Typography>

          {myPermissions && (
            <>
              <Card sx={{ mb: 3 }}>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    {t('rbac.yourRole')}
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                    <Chip
                      label={myPermissions.role_name}
                      color={getRoleColor(myPermissions.role)}
                      size="large"
                    />
                    <Typography color="text.secondary">
                      {myPermissions.role_description}
                    </Typography>
                  </Box>
                  <Typography variant="body2" color="text.secondary">
                    {t('rbac.permissionsGranted')}: <strong>{myPermissions.permissions.length}</strong>
                  </Typography>
                </CardContent>
              </Card>

              <Typography variant="h6" sx={{ mb: 2 }}>
                {t('rbac.permissionsList')}
              </Typography>

              {Object.entries(permissionCategories).map(([category, perms]) => {
                const userPerms = Array.isArray(perms) ? perms.filter(p => 
                  Array.isArray(myPermissions?.permissions) && myPermissions.permissions.includes(p)
                ) : [];
                if (userPerms.length === 0) return null;

                return (
                  <Card key={category} sx={{ mb: 2 }}>
                    <CardContent>
                      <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                        {getCategoryIcon(category)}
                        <Typography variant="h6" sx={{ ml: 1 }}>
                          {category}
                        </Typography>
                        <Chip
                          label={`${userPerms.length}/${perms.length}`}
                          size="small"
                          sx={{ ml: 'auto' }}
                        />
                      </Box>
                      <Grid container spacing={1}>
                        {userPerms.map((perm) => {
                          const permDetail = myPermissions.permission_details.find(p => p.key === perm);
                          return (
                            <Grid item xs={12} sm={6} key={perm}>
                              <Chip
                                label={permDetail?.key || perm}
                                size="small"
                                color="success"
                                icon={<CheckCircle />}
                                sx={{ width: '100%', justifyContent: 'flex-start' }}
                              />
                            </Grid>
                          );
                        })}
                      </Grid>
                    </CardContent>
                  </Card>
                );
              })}
            </>
          )}
        </TabPanel>
      </Paper>

      {/* Role Create/Edit Dialog */}
      <Dialog
        open={roleDialog}
        onClose={() => setRoleDialog(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {selectedRole ? t('rbac.editRole') : t('rbac.createRole')}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <TextField
              fullWidth
              label={t('rbac.roleKey')}
              value={roleFormData.role_key}
              onChange={(e) => setRoleFormData({ ...roleFormData, role_key: e.target.value })}
              disabled={!!selectedRole}
              sx={{ mb: 2 }}
              helperText={t('rbac.roleKeyHelp')}
            />
            <TextField
              fullWidth
              label={t('rbac.roleName')}
              value={roleFormData.name}
              onChange={(e) => setRoleFormData({ ...roleFormData, name: e.target.value })}
              sx={{ mb: 2 }}
            />
            <TextField
              fullWidth
              multiline
              rows={2}
              label={t('rbac.description')}
              value={roleFormData.description}
              onChange={(e) => setRoleFormData({ ...roleFormData, description: e.target.value })}
              sx={{ mb: 3 }}
            />

            <Typography variant="h6" sx={{ mb: 2 }}>
              {t('rbac.selectPermissions')} ({roleFormData.permissions.length} {t('rbac.selected')})
            </Typography>

            {Object.entries(permissionCategories).map(([category, perms]) => (
              <Box key={category} sx={{ mb: 3 }}>
                <Typography variant="subtitle1" sx={{ mb: 1, display: 'flex', alignItems: 'center' }}>
                  {getCategoryIcon(category)}
                  <span style={{ marginLeft: 8 }}>{category}</span>
                </Typography>
                <FormGroup>
                  {perms.map((perm) => {
                    const permDetail = permissions.find(p => p.key === perm);
                    return (
                      <FormControlLabel
                        key={perm}
                        control={
                          <Checkbox
                            checked={roleFormData.permissions.includes(perm)}
                            onChange={() => handleTogglePermission(perm)}
                          />
                        }
                        label={
                          <Box>
                            <Typography variant="body2">{perm}</Typography>
                            <Typography variant="caption" color="text.secondary">
                              {permDetail?.description}
                            </Typography>
                          </Box>
                        }
                      />
                    );
                  })}
                </FormGroup>
                <Divider sx={{ mt: 2 }} />
              </Box>
            ))}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRoleDialog(false)}>{t('cancel')}</Button>
          <Button
            variant="contained"
            onClick={handleSaveRole}
            disabled={!roleFormData.role_key || !roleFormData.name}
          >
            {selectedRole ? t('save') : t('create')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* User Role Assignment Dialog */}
      <Dialog
        open={userRoleDialog}
        onClose={() => setUserRoleDialog(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>{t('rbac.assignRole')}</DialogTitle>
        <DialogContent>
          {selectedUser && (
            <Box sx={{ mt: 2 }}>
              <Typography variant="body2" sx={{ mb: 2 }}>
                {t('rbac.assigningRoleTo')}: <strong>{selectedUser.username}</strong>
              </Typography>
              <FormControl fullWidth>
                <InputLabel>{t('role')}</InputLabel>
                <Select
                  value={newUserRole}
                  onChange={(e) => setNewUserRole(e.target.value)}
                >
                  {roles.map((role) => (
                    <MenuItem key={role.role_key} value={role.role_key}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Chip
                          label={role.name}
                          size="small"
                          color={getRoleColor(role.role_key)}
                        />
                        <Typography variant="caption" color="text.secondary">
                          {role.permissions.length} {t('rbac.permissions')}
                        </Typography>
                      </Box>
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setUserRoleDialog(false)}>{t('cancel')}</Button>
          <Button variant="contained" onClick={handleSaveUserRole}>
            {t('assign')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default RBACDashboard;
