import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
import { useResponsive } from '../../hooks/useResponsive';
import { useToast } from '../../context/ToastContext';
import { adminService } from '../../services/adminService';
import { Role, Permission } from '../../types';
import { colors, spacing, radii } from '../../theme';

const MODULE_ICONS: Record<string, keyof typeof Ionicons.glyphMap> = {
  job: 'briefcase-outline', user: 'people-outline', material: 'cube-outline',
  geofence: 'location-outline', location: 'navigate-outline', report: 'bar-chart-outline',
};

const MODULE_COLORS: Record<string, string> = {
  job: colors.primary[600], user: colors.info[600], material: colors.success[600],
  geofence: colors.warning[600], location: colors.danger[600], report: colors.gray[600],
};

function groupPermissions(perms: Permission[]) {
  const map = new Map<string, Permission[]>();
  for (const p of perms) {
    const mod = p.permission_key.split('.')[0];
    if (!map.has(mod)) map.set(mod, []);
    map.get(mod)!.push(p);
  }
  return Array.from(map.entries()).sort(([a], [b]) => a.localeCompare(b));
}

export default function RoleListScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();
  const [roles, setRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Role | null>(null);

  const loadData = async () => {
    try {
      const [rolesData, permsData] = await Promise.all([
        adminService.roles(),
        adminService.permissions(),
      ]);
      setRoles(rolesData);
      setPermissions(permsData);
    } catch (error) {
      console.error('Failed to load roles:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { loadData(); }, []));

  const onRefresh = () => { setRefreshing(true); loadData(); };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await adminService.deleteRole(deleteTarget.id);
      toast('Role deleted', 'success');
      setDeleteTarget(null);
      loadData();
    } catch (error: any) {
      toast(error.response?.data?.message || 'Failed to delete role', 'error');
    }
  };

  const permGroups = groupPermissions(permissions);

  return (
    <ScreenContainer
      title="Roles & Permissions"
      subtitle={`${roles.length} roles, ${permissions.length} permissions`}
      onBack={() => navigation.goBack()}
      loading={loading}
      refreshing={refreshing}
      onRefresh={onRefresh}
      scroll={true}
      contentPadding={contentPadding}
      rightAction={{ icon: 'add-circle-outline', onPress: () => navigation.navigate('RoleCreate') }}
    >
      <Text style={[styles.sectionLabel, { fontSize: fontSize.caption, marginBottom: spacing.md }]}>Roles ({roles.length})</Text>
      {roles.length > 0 ? (
        roles.map((role, index) => (
          <AnimatedCard key={`role-${role.id}`} delay={index * 60} style={{ marginBottom: spacing.sm }}>
            <View style={[styles.row, { gap: spacing.md }]}>
              <View style={[styles.iconContainer, { backgroundColor: colors.primary[50] }]}>
                <Ionicons name="shield-checkmark-outline" size={20} color={colors.primary[600]} />
              </View>
              <View style={styles.info}>
                <Text style={[styles.name, { fontSize: fontSize.body }]}>{role.name}</Text>
                {role.description && <Text style={[styles.desc, { fontSize: fontSize.bodySmall, marginTop: spacing.xs }]}>{role.description}</Text>}
              </View>
              <TouchableOpacity
                onPress={() => navigation.navigate('RoleEdit', { roleId: role.id, roleName: role.name })}
                style={[styles.actionBtn, { backgroundColor: colors.primary[50] }]}
              >
                <Ionicons name="create-outline" size={18} color={colors.primary[600]} />
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => setDeleteTarget(role)}
                style={[styles.actionBtn, { backgroundColor: colors.danger[50] }]}
              >
                <Ionicons name="trash-outline" size={18} color={colors.danger[600]} />
              </TouchableOpacity>
            </View>
          </AnimatedCard>
        ))
      ) : (
        <EmptyState icon="shield-checkmark-outline" title="No roles" description="Create your first role to get started" />
      )}

      <Text style={[styles.sectionLabel, { fontSize: fontSize.caption, marginTop: spacing.xxl, marginBottom: spacing.md }]}>Permission Modules ({permGroups.length})</Text>
      {permGroups.map(([mod, perms], gi) => {
        const modColor = MODULE_COLORS[mod] || colors.gray[600];
        return (
          <AnimatedCard key={mod} delay={gi * 40} style={{ marginBottom: spacing.sm }}>
            <View style={[styles.row, { gap: spacing.md, marginBottom: spacing.sm }]}>
              <View style={[styles.iconContainer, { backgroundColor: `${modColor}12` }]}>
                <Ionicons name={(MODULE_ICONS[mod] || 'key-outline') as any} size={18} color={modColor} />
              </View>
              <Text style={[styles.name, { fontSize: fontSize.body, flex: 1 }]}>{mod.charAt(0).toUpperCase() + mod.slice(1)}</Text>
              <Text style={[styles.desc, { fontSize: fontSize.caption }]}>{perms.length} perms</Text>
            </View>
            <View style={[styles.permChips, { gap: spacing.xs }]}>
              {perms.map(p => {
                const action = p.permission_key.split('.')[1];
                const label = action ? action.charAt(0).toUpperCase() + action.slice(1) : p.permission_key;
                return (
                  <View key={p.id} style={[styles.permChip, { borderColor: `${modColor}30` }]}>
                    <Text style={[styles.permChipText, { fontSize: fontSize.caption, color: modColor }]}>{label}</Text>
                  </View>
                );
              })}
            </View>
          </AnimatedCard>
        );
      })}

      <ConfirmDialog
        visible={!!deleteTarget}
        title="Delete Role"
        message={`Are you sure you want to delete "${deleteTarget?.name}"? This action cannot be undone.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
        danger
      />
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  sectionLabel: { fontWeight: '600', color: colors.gray[500], textTransform: 'uppercase', letterSpacing: 0.5 },
  row: { flexDirection: 'row', alignItems: 'center' },
  iconContainer: { width: 36, height: 36, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' },
  info: { flex: 1 },
  name: { fontWeight: '600', color: colors.gray[900] },
  desc: { color: colors.gray[500] },
  actionBtn: { width: 36, height: 36, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center' },
  permChips: { flexDirection: 'row', flexWrap: 'wrap' },
  permChip: { paddingHorizontal: spacing.sm, paddingVertical: spacing.xs, borderRadius: radii.md, borderWidth: 1, backgroundColor: colors.white },
  permChipText: { fontWeight: '500' },
});
