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

interface PermGroup {
  module: string;
  icon: keyof typeof Ionicons.glyphMap;
  color: string;
  bgColor: string;
  permissions: { key: string; label: string; id: number }[];
}

const MODULE_MAP: Record<string, { icon: keyof typeof Ionicons.glyphMap; color: string; bgColor: string }> = {
  job: { icon: 'briefcase-outline', color: colors.primary[600], bgColor: colors.primary[50] },
  user: { icon: 'people-outline', color: colors.info[600], bgColor: colors.info[50] },
  material: { icon: 'cube-outline', color: colors.success[600], bgColor: colors.success[50] },
  geofence: { icon: 'location-outline', color: colors.warning[600], bgColor: colors.warning[50] },
  location: { icon: 'navigate-outline', color: colors.danger[600], bgColor: colors.danger[50] },
  report: { icon: 'bar-chart-outline', color: colors.gray[600], bgColor: colors.gray[100] },
};

function buildGroups(perms: Permission[]): PermGroup[] {
  const map = new Map<string, PermGroup>();
  for (const p of perms) {
    const parts = p.permission_key.split('.');
    const mod = parts[0];
    const action = parts[1] || parts[0];
    if (!map.has(mod)) {
      const cfg = MODULE_MAP[mod] || { icon: 'key-outline', color: colors.gray[600], bgColor: colors.gray[100] };
      map.set(mod, { module: mod, icon: cfg.icon, color: cfg.color, bgColor: cfg.bgColor, permissions: [] });
    }
    map.get(mod)!.permissions.push({ key: p.permission_key, label: action.charAt(0).toUpperCase() + action.slice(1), id: p.id });
  }
  return Array.from(map.values()).sort((a, b) => a.module.localeCompare(b.module));
}

export default function RoleCreateScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, fontSize } = useResponsive();
  const { toast } = useToast();

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [groups, setGroups] = useState<PermGroup[]>([]);
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const permsData = await adminService.permissions();
        setGroups(buildGroups(permsData));
      } catch (error) {
        console.error('Failed to load permissions:', error);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const togglePerm = (id: number) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const toggleModule = (mod: PermGroup) => {
    const ids = mod.permissions.map(p => p.id);
    const allSelected = ids.every(id => selectedIds.has(id));
    setSelectedIds(prev => {
      const next = new Set(prev);
      ids.forEach(id => allSelected ? next.delete(id) : next.add(id));
      return next;
    });
  };

  const toggleAll = () => {
    const allIds = groups.flatMap(g => g.permissions.map(p => p.id));
    const allSelected = allIds.every(id => selectedIds.has(id));
    setSelectedIds(allSelected ? new Set() : new Set(allIds));
  };

  const handleSave = async () => {
    if (!name.trim()) { toast('Role name is required', 'error'); return; }
    setSaving(true);
    try {
      await adminService.createRole({
        name: name.trim(),
        description: description.trim() || undefined,
        permission_ids: Array.from(selectedIds),
      });
      toast('Role created successfully', 'success');
      navigation.goBack();
    } catch (error: any) {
      toast(error.response?.data?.message || 'Failed to create role', 'error');
    } finally {
      setSaving(false);
    }
  };

  const totalPerms = groups.reduce((sum, g) => sum + g.permissions.length, 0);
  const allSelected = totalPerms > 0 && selectedIds.size === totalPerms;

  const renderCount = (group: PermGroup) => {
    const count = group.permissions.filter(p => selectedIds.has(p.id)).length;
    return count + ' / ' + group.permissions.length;
  };

  return (
    <ScreenContainer
      title="Create Role"
      onBack={() => navigation.goBack()}
      loading={loading}
      scroll={true}
      contentPadding={contentPadding}
    >
      <View style={{ marginBottom: spacing.lg }}>
        <Text style={[styles.label, { fontSize: fontSize.caption }]}>Role Name *</Text>
        <View style={[styles.input, { borderColor: colors.border }]}>
          <TextInput value={name} onChangeText={setName} placeholder="e.g. SITE_LEAD" placeholderTextColor={colors.gray[400]} style={[styles.inputText, { fontSize: fontSize.body }]} />
        </View>
      </View>

      <View style={{ marginBottom: spacing.xl }}>
        <Text style={[styles.label, { fontSize: fontSize.caption }]}>Description</Text>
        <View style={[styles.input, { borderColor: colors.border, minHeight: 70 }]}>
          <TextInput value={description} onChangeText={setDescription} placeholder="Optional description" placeholderTextColor={colors.gray[400]} multiline textAlignVertical="top" style={[styles.inputText, { fontSize: fontSize.body, paddingTop: spacing.xs }]} />
        </View>
      </View>

      <View style={[styles.permHeader, { marginBottom: spacing.md }]}>
        <Text style={[styles.sectionLabel, { fontSize: fontSize.caption }]}>Permissions ({selectedIds.size} / {totalPerms})</Text>
        <TouchableOpacity onPress={toggleAll} style={styles.toggleAllBtn}>
          <Ionicons name={allSelected ? 'checkbox' : 'square-outline'} size={18} color={allSelected ? colors.primary[600] : colors.gray[400]} />
          <Text style={[styles.toggleAllText, { fontSize: fontSize.caption, color: allSelected ? colors.primary[600] : colors.gray[500] }]}>{allSelected ? 'Deselect All' : 'Select All'}</Text>
        </TouchableOpacity>
      </View>

      {groups.map((group, gi) => {
        const moduleSelected = group.permissions.every(p => selectedIds.has(p.id));
        const moduleSome = group.permissions.some(p => selectedIds.has(p.id));
        return (
          <AnimatedCard key={group.module} delay={gi * 50} style={{ marginBottom: spacing.md }}>
            <TouchableOpacity onPress={() => toggleModule(group)} style={[styles.moduleHeader, { gap: spacing.sm }]} activeOpacity={0.7}>
              <View style={[styles.moduleIcon, { backgroundColor: group.bgColor }]}>
                <Ionicons name={group.icon} size={18} color={group.color} />
              </View>
              <Text style={[styles.moduleName, { fontSize: fontSize.body, flex: 1 }]}>{group.module.charAt(0).toUpperCase() + group.module.slice(1)}</Text>
              <Text style={{ fontSize: fontSize.caption, color: colors.gray[400] }}>{renderCount(group)}</Text>
              <View style={[styles.moduleCheckbox, moduleSelected && styles.moduleCheckboxSelected, !moduleSelected && moduleSome && styles.moduleCheckboxPartial]}>
                {moduleSelected && <Ionicons name="checkmark" size={14} color={colors.white} />}
                {!moduleSelected && moduleSome && <View style={styles.partialDot} />}
              </View>
            </TouchableOpacity>

            <View style={[styles.permGrid, { marginTop: spacing.sm, gap: spacing.xs }]}>
              {group.permissions.map(perm => {
                const sel = selectedIds.has(perm.id);
                return (
                  <TouchableOpacity
                    key={perm.key}
                    onPress={() => togglePerm(perm.id)}
                    style={[styles.permChip, sel && styles.permChipSelected, { borderColor: sel ? group.color : colors.gray[200] }]}
                    activeOpacity={0.7}
                  >
                    <Ionicons name={sel ? 'checkmark-circle' : 'ellipse-outline'} size={16} color={sel ? group.color : colors.gray[400]} />
                    <Text style={[styles.permLabel, { fontSize: fontSize.caption, color: sel ? group.color : colors.gray[600] }]}>{perm.label}</Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          </AnimatedCard>
        );
      })}

      <View style={{ marginTop: spacing.lg, marginBottom: spacing.xxl }}>
        <Button title="Create Role" onPress={handleSave} loading={saving} disabled={saving} size="lg" />
      </View>
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  label: { fontWeight: '600', color: colors.gray[700], marginBottom: spacing.xs },
  input: { borderWidth: 1, borderRadius: radii.md, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, backgroundColor: colors.white },
  inputText: { color: colors.gray[900], padding: 0 },
  permHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  sectionLabel: { fontWeight: '600', color: colors.gray[500], textTransform: 'uppercase', letterSpacing: 0.5 },
  toggleAllBtn: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  toggleAllText: { fontWeight: '500' },
  moduleHeader: { flexDirection: 'row', alignItems: 'center' },
  moduleIcon: { width: 32, height: 32, borderRadius: radii.md, justifyContent: 'center', alignItems: 'center' },
  moduleName: { fontWeight: '600', color: colors.gray[900] },
  moduleCheckbox: { width: 22, height: 22, borderRadius: radii.sm, borderWidth: 2, borderColor: colors.gray[300], justifyContent: 'center', alignItems: 'center' },
  moduleCheckboxSelected: { backgroundColor: colors.primary[600], borderColor: colors.primary[600] },
  moduleCheckboxPartial: { backgroundColor: colors.gray[200], borderColor: colors.gray[400] },
  partialDot: { width: 8, height: 8, borderRadius: 4, backgroundColor: colors.gray[600] },
  permGrid: { flexDirection: 'row', flexWrap: 'wrap' },
  permChip: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, paddingHorizontal: spacing.sm, paddingVertical: spacing.xs, borderRadius: radii.md, borderWidth: 1, backgroundColor: colors.white },
  permChipSelected: { backgroundColor: colors.primary[50] },
  permLabel: { fontWeight: '500' },
});
