import React, { useState, useEffect, useCallback } from 'react';
import {
  View, Text, TouchableOpacity, StyleSheet, FlatList, ActivityIndicator,
  TextInput, Alert, Modal, ScrollView, KeyboardAvoidingView, Platform,
  RefreshControl,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { storage } from '../utils/storage';

const API_URL = process.env.EXPO_PUBLIC_BACKEND_URL;

type Employee = {
  employee_id: string; name: string; role: string; is_active: boolean;
};

type AttendanceRecord = {
  employee_id: string; name: string; date: string; action: string;
  time: string; is_auto_logout: boolean;
};

export default function AdminScreen() {
  const router = useRouter();
  const [tab, setTab] = useState<'employees' | 'attendance'>('employees');
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [attendance, setAttendance] = useState<AttendanceRecord[]>([]);
  const [attendanceDate, setAttendanceDate] = useState('');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [selectedEmpId, setSelectedEmpId] = useState('');
  const [newEmpId, setNewEmpId] = useState('');
  const [newName, setNewName] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newRole, setNewRole] = useState('employee');
  const [changePassword, setChangePassword] = useState('');
  const [actionLoading, setActionLoading] = useState(false);
  const [adminName, setAdminName] = useState('');

  const getToken = async () => await storage.getItemAsync('token');

  const loadEmployees = useCallback(async () => {
    try {
      const token = await getToken();
      const res = await fetch(`${API_URL}/api/admin/employees`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.status === 401 || res.status === 403) { router.replace('/'); return; }
      const data = await res.json();
      setEmployees(data.employees || []);
    } catch (e) { console.error(e); }
    finally { setLoading(false); setRefreshing(false); }
  }, []);

  const loadAttendance = useCallback(async () => {
    try {
      const token = await getToken();
      const url = attendanceDate
        ? `${API_URL}/api/admin/attendance?date=${attendanceDate}`
        : `${API_URL}/api/admin/attendance`;
      const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
      const data = await res.json();
      setAttendance(data.records || []);
      if (!attendanceDate && data.date) setAttendanceDate(data.date);
    } catch (e) { console.error(e); }
    finally { setLoading(false); setRefreshing(false); }
  }, [attendanceDate]);

  useEffect(() => {
    const loadAdmin = async () => {
      const emp = await storage.getItemAsync('employee');
      if (emp) setAdminName(JSON.parse(emp).name);
    };
    loadAdmin();
  }, []);

  useEffect(() => {
    setLoading(true);
    if (tab === 'employees') loadEmployees();
    else loadAttendance();
  }, [tab, loadEmployees, loadAttendance]);

  const handleAddEmployee = async () => {
    if (!newEmpId.trim() || !newName.trim() || !newPassword.trim()) {
      Alert.alert('Error', 'All fields are required'); return;
    }
    setActionLoading(true);
    try {
      const token = await getToken();
      const res = await fetch(`${API_URL}/api/admin/employees`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          employee_id: newEmpId.trim(), name: newName.trim(),
          password: newPassword, role: newRole,
        }),
      });
      const data = await res.json();
      if (!res.ok) Alert.alert('Error', data.detail);
      else {
        Alert.alert('Success', 'Employee added');
        setShowAddModal(false);
        setNewEmpId(''); setNewName(''); setNewPassword(''); setNewRole('employee');
        loadEmployees();
      }
    } catch (e) { Alert.alert('Error', 'Network error'); }
    finally { setActionLoading(false); }
  };

  const handleDeleteEmployee = (empId: string) => {
    Alert.alert('Delete Employee', `Delete ${empId}?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete', style: 'destructive', onPress: async () => {
          const token = await getToken();
          const res = await fetch(`${API_URL}/api/admin/employees/${empId}`, {
            method: 'DELETE', headers: { Authorization: `Bearer ${token}` },
          });
          if (res.ok) loadEmployees();
          else { const d = await res.json(); Alert.alert('Error', d.detail); }
        }
      },
    ]);
  };

  const handleToggleActive = async (empId: string, currentActive: boolean) => {
    const token = await getToken();
    await fetch(`${API_URL}/api/admin/employees/${empId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ is_active: !currentActive }),
    });
    loadEmployees();
  };

  const handleChangePassword = async () => {
    if (changePassword.length < 6) { Alert.alert('Error', 'Min 6 characters'); return; }
    setActionLoading(true);
    try {
      const token = await getToken();
      const res = await fetch(`${API_URL}/api/admin/change-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ employee_id: selectedEmpId, new_password: changePassword }),
      });
      if (res.ok) {
        Alert.alert('Success', 'Password changed');
        setShowPasswordModal(false); setChangePassword('');
      } else { const d = await res.json(); Alert.alert('Error', d.detail); }
    } catch (e) { Alert.alert('Error', 'Network error'); }
    finally { setActionLoading(false); }
  };

  const handleAutoLogout = async () => {
    Alert.alert('Auto Logout', 'Run auto logout for all employees?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Run', onPress: async () => {
          const token = await getToken();
          const res = await fetch(`${API_URL}/api/attendance/auto-logout`, {
            method: 'POST', headers: { Authorization: `Bearer ${token}` },
          });
          const d = await res.json();
          Alert.alert('Result', d.message);
          if (tab === 'attendance') loadAttendance();
        }
      },
    ]);
  };

  const handleLogout = async () => {
    await storage.deleteItemAsync('token');
    await storage.deleteItemAsync('employee');
    router.replace('/');
  };

  const renderEmployee = ({ item }: { item: Employee }) => (
    <View testID={`emp-card-${item.employee_id}`} style={[styles.empCard, !item.is_active && styles.empCardInactive]}>
      <View style={styles.empInfo}>
        <Text style={styles.empName}>{item.name}</Text>
        <Text style={styles.empId}>{item.employee_id}</Text>
        <View style={styles.empTags}>
          <View style={[styles.tag, item.role === 'admin' ? styles.tagAdmin : styles.tagEmp]}>
            <Text style={styles.tagText}>{item.role.toUpperCase()}</Text>
          </View>
          <View style={[styles.tag, item.is_active ? styles.tagActive : styles.tagInactive]}>
            <Text style={styles.tagText}>{item.is_active ? 'ACTIVE' : 'INACTIVE'}</Text>
          </View>
        </View>
      </View>
      <View style={styles.empActions}>
        <TouchableOpacity
          testID={`toggle-active-${item.employee_id}`}
          onPress={() => handleToggleActive(item.employee_id, item.is_active)}
          style={styles.empActionBtn}
        >
          <MaterialCommunityIcons
            name={item.is_active ? 'account-check' : 'account-off'}
            size={20} color={item.is_active ? '#00C853' : '#FF3D00'}
          />
        </TouchableOpacity>
        <TouchableOpacity
          testID={`change-pwd-${item.employee_id}`}
          onPress={() => { setSelectedEmpId(item.employee_id); setShowPasswordModal(true); }}
          style={styles.empActionBtn}
        >
          <MaterialCommunityIcons name="key" size={20} color="#00E5FF" />
        </TouchableOpacity>
        {item.employee_id !== 'ADMIN001' && (
          <TouchableOpacity
            testID={`delete-emp-${item.employee_id}`}
            onPress={() => handleDeleteEmployee(item.employee_id)}
            style={styles.empActionBtn}
          >
            <MaterialCommunityIcons name="delete" size={20} color="#FF3D00" />
          </TouchableOpacity>
        )}
      </View>
    </View>
  );

  const renderAttendance = ({ item }: { item: AttendanceRecord }) => (
    <View style={styles.attCard}>
      <View style={styles.attHeader}>
        <Text style={styles.attName}>{item.name}</Text>
        <Text style={styles.attEmpId}>{item.employee_id}</Text>
      </View>
      <View style={styles.attBody}>
        <View style={[styles.attActionTag, item.action === 'Login' ? styles.attLogin : styles.attLogout]}>
          <Text style={styles.attActionText}>{item.action}</Text>
        </View>
        <Text style={styles.attTime}>{item.time}</Text>
        {item.is_auto_logout && (
          <View style={styles.autoTag}>
            <Text style={styles.autoTagText}>AUTO</Text>
          </View>
        )}
      </View>
    </View>
  );

  return (
    <SafeAreaView style={styles.safe}>
      {/* Header */}
      <View style={styles.header}>
        <View>
          <Text style={styles.headerTitle}>Admin Panel</Text>
          <Text style={styles.headerSub}>{adminName}</Text>
        </View>
        <View style={styles.headerActions}>
          <TouchableOpacity testID="auto-logout-btn" onPress={handleAutoLogout} style={styles.headerBtn}>
            <MaterialCommunityIcons name="clock-alert" size={20} color="#FFD600" />
          </TouchableOpacity>
          <TouchableOpacity testID="admin-logout-btn" onPress={handleLogout} style={styles.headerBtn}>
            <MaterialCommunityIcons name="logout" size={20} color="#FF3D00" />
          </TouchableOpacity>
        </View>
      </View>

      {/* Tabs */}
      <View style={styles.tabs}>
        <TouchableOpacity
          testID="tab-employees"
          style={[styles.tab, tab === 'employees' && styles.tabActive]}
          onPress={() => setTab('employees')}
        >
          <Text style={[styles.tabText, tab === 'employees' && styles.tabTextActive]}>Employees</Text>
        </TouchableOpacity>
        <TouchableOpacity
          testID="tab-attendance"
          style={[styles.tab, tab === 'attendance' && styles.tabActive]}
          onPress={() => setTab('attendance')}
        >
          <Text style={[styles.tabText, tab === 'attendance' && styles.tabTextActive]}>Attendance</Text>
        </TouchableOpacity>
      </View>

      {/* Content */}
      {loading ? (
        <View style={styles.center}><ActivityIndicator size="large" color="#00E5FF" /></View>
      ) : tab === 'employees' ? (
        <>
          <TouchableOpacity testID="add-employee-btn" style={styles.addBtn} onPress={() => setShowAddModal(true)}>
            <MaterialCommunityIcons name="account-plus" size={20} color="#000" />
            <Text style={styles.addBtnText}>ADD EMPLOYEE</Text>
          </TouchableOpacity>
          <FlatList
            data={employees}
            keyExtractor={(item) => item.employee_id}
            renderItem={renderEmployee}
            contentContainerStyle={styles.list}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); loadEmployees(); }} tintColor="#00E5FF" />}
          />
        </>
      ) : (
        <FlatList
          data={attendance}
          keyExtractor={(item, i) => `${item.employee_id}-${item.action}-${i}`}
          renderItem={renderAttendance}
          contentContainerStyle={styles.list}
          ListHeaderComponent={
            <View style={styles.dateFilter}>
              <Text style={styles.dateLabel}>Date: {attendanceDate}</Text>
            </View>
          }
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); loadAttendance(); }} tintColor="#00E5FF" />}
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>No attendance records for this date</Text>
            </View>
          }
        />
      )}

      {/* Add Employee Modal */}
      <Modal visible={showAddModal} transparent animationType="slide">
        <View style={styles.modalOverlay}>
          <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
            <View style={styles.modalContent}>
              <Text style={styles.modalTitle}>Add Employee</Text>
              <TextInput testID="new-emp-id" style={styles.modalInput} value={newEmpId} onChangeText={setNewEmpId} placeholder="Employee ID" placeholderTextColor="#6E6E6E" autoCapitalize="characters" />
              <TextInput testID="new-emp-name" style={styles.modalInput} value={newName} onChangeText={setNewName} placeholder="Full Name" placeholderTextColor="#6E6E6E" />
              <TextInput testID="new-emp-password" style={styles.modalInput} value={newPassword} onChangeText={setNewPassword} placeholder="Password" placeholderTextColor="#6E6E6E" secureTextEntry />
              <View style={styles.roleRow}>
                <TouchableOpacity
                  testID="role-employee"
                  style={[styles.roleBtn, newRole === 'employee' && styles.roleBtnActive]}
                  onPress={() => setNewRole('employee')}
                >
                  <Text style={[styles.roleBtnText, newRole === 'employee' && styles.roleBtnTextActive]}>Employee</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  testID="role-admin"
                  style={[styles.roleBtn, newRole === 'admin' && styles.roleBtnActive]}
                  onPress={() => setNewRole('admin')}
                >
                  <Text style={[styles.roleBtnText, newRole === 'admin' && styles.roleBtnTextActive]}>Admin</Text>
                </TouchableOpacity>
              </View>
              <View style={styles.modalActions}>
                <TouchableOpacity testID="cancel-add-btn" style={styles.cancelBtn} onPress={() => setShowAddModal(false)}>
                  <Text style={styles.cancelBtnText}>CANCEL</Text>
                </TouchableOpacity>
                <TouchableOpacity testID="confirm-add-btn" style={styles.confirmBtn} onPress={handleAddEmployee} disabled={actionLoading}>
                  {actionLoading ? <ActivityIndicator color="#000" /> : <Text style={styles.confirmBtnText}>ADD</Text>}
                </TouchableOpacity>
              </View>
            </View>
          </KeyboardAvoidingView>
        </View>
      </Modal>

      {/* Change Password Modal */}
      <Modal visible={showPasswordModal} transparent animationType="slide">
        <View style={styles.modalOverlay}>
          <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
            <View style={styles.modalContent}>
              <Text style={styles.modalTitle}>Change Password</Text>
              <Text style={styles.modalSub}>For: {selectedEmpId}</Text>
              <TextInput testID="change-pwd-input" style={styles.modalInput} value={changePassword} onChangeText={setChangePassword} placeholder="New password" placeholderTextColor="#6E6E6E" secureTextEntry />
              <View style={styles.modalActions}>
                <TouchableOpacity testID="cancel-pwd-btn" style={styles.cancelBtn} onPress={() => { setShowPasswordModal(false); setChangePassword(''); }}>
                  <Text style={styles.cancelBtnText}>CANCEL</Text>
                </TouchableOpacity>
                <TouchableOpacity testID="confirm-pwd-btn" style={styles.confirmBtn} onPress={handleChangePassword} disabled={actionLoading}>
                  {actionLoading ? <ActivityIndicator color="#000" /> : <Text style={styles.confirmBtnText}>CHANGE</Text>}
                </TouchableOpacity>
              </View>
            </View>
          </KeyboardAvoidingView>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: {
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
    padding: 20, borderBottomWidth: 1, borderBottomColor: '#1E1E1E',
  },
  headerTitle: { color: '#FFF', fontSize: 22, fontWeight: '700' },
  headerSub: { color: '#6E6E6E', fontSize: 13, marginTop: 2 },
  headerActions: { flexDirection: 'row', gap: 8 },
  headerBtn: { padding: 10, backgroundColor: '#1E1E1E', borderRadius: 8 },
  tabs: { flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#1E1E1E' },
  tab: { flex: 1, paddingVertical: 14, alignItems: 'center' },
  tabActive: { borderBottomWidth: 2, borderBottomColor: '#00E5FF' },
  tabText: { color: '#6E6E6E', fontSize: 14, fontWeight: '600' },
  tabTextActive: { color: '#00E5FF' },
  addBtn: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
    backgroundColor: '#00E5FF', margin: 20, marginBottom: 0,
    paddingVertical: 14, borderRadius: 4, gap: 8,
  },
  addBtnText: { color: '#000', fontWeight: '700', fontSize: 14, letterSpacing: 1 },
  list: { padding: 20 },
  empCard: {
    backgroundColor: '#121212', borderLeftWidth: 4, borderLeftColor: '#00E5FF',
    padding: 16, marginBottom: 12, borderRadius: 2,
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
  },
  empCardInactive: { borderLeftColor: '#475569', opacity: 0.6 },
  empInfo: { flex: 1 },
  empName: { color: '#FFF', fontSize: 16, fontWeight: '600' },
  empId: { color: '#B0B0B0', fontSize: 13, marginTop: 2 },
  empTags: { flexDirection: 'row', gap: 8, marginTop: 8 },
  tag: { paddingHorizontal: 8, paddingVertical: 2, borderRadius: 2 },
  tagAdmin: { backgroundColor: '#00E5FF' },
  tagEmp: { backgroundColor: '#475569' },
  tagActive: { backgroundColor: '#00C853' },
  tagInactive: { backgroundColor: '#FF3D00' },
  tagText: { color: '#000', fontSize: 10, fontWeight: '700' },
  empActions: { flexDirection: 'row', gap: 4 },
  empActionBtn: { padding: 8 },
  attCard: {
    backgroundColor: '#121212', padding: 14, marginBottom: 10, borderRadius: 2,
    borderLeftWidth: 4, borderLeftColor: '#475569',
  },
  attHeader: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 8 },
  attName: { color: '#FFF', fontSize: 14, fontWeight: '600' },
  attEmpId: { color: '#B0B0B0', fontSize: 12 },
  attBody: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  attActionTag: { paddingHorizontal: 10, paddingVertical: 3, borderRadius: 2 },
  attLogin: { backgroundColor: '#00C853' },
  attLogout: { backgroundColor: '#FF3D00' },
  attActionText: { color: '#FFF', fontSize: 12, fontWeight: '700' },
  attTime: { color: '#E5E7EB', fontSize: 13 },
  autoTag: { backgroundColor: '#FFD600', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 2 },
  autoTagText: { color: '#000', fontSize: 10, fontWeight: '700' },
  dateFilter: { marginBottom: 16 },
  dateLabel: { color: '#B0B0B0', fontSize: 14 },
  emptyContainer: { alignItems: 'center', marginTop: 40 },
  emptyText: { color: '#6E6E6E', fontSize: 14 },
  modalOverlay: {
    flex: 1, backgroundColor: 'rgba(0,0,0,0.8)',
    justifyContent: 'center', padding: 24,
  },
  modalContent: {
    backgroundColor: '#1E1E1E', borderRadius: 4, padding: 24,
    borderWidth: 1, borderColor: '#333',
  },
  modalTitle: { color: '#FFF', fontSize: 20, fontWeight: '700', marginBottom: 4 },
  modalSub: { color: '#B0B0B0', fontSize: 13, marginBottom: 20 },
  modalInput: {
    backgroundColor: '#121212', borderWidth: 1, borderColor: '#333',
    borderRadius: 4, padding: 14, color: '#FFF', fontSize: 15, marginBottom: 14,
  },
  roleRow: { flexDirection: 'row', gap: 12, marginBottom: 20 },
  roleBtn: {
    flex: 1, paddingVertical: 12, alignItems: 'center',
    borderWidth: 1, borderColor: '#475569', borderRadius: 4,
  },
  roleBtnActive: { borderColor: '#00E5FF', backgroundColor: '#00E5FF' },
  roleBtnText: { color: '#B0B0B0', fontWeight: '600' },
  roleBtnTextActive: { color: '#000' },
  modalActions: { flexDirection: 'row', gap: 12 },
  cancelBtn: {
    flex: 1, paddingVertical: 14, alignItems: 'center',
    borderWidth: 1, borderColor: '#475569', borderRadius: 4,
  },
  cancelBtnText: { color: '#B0B0B0', fontWeight: '600' },
  confirmBtn: {
    flex: 1, paddingVertical: 14, alignItems: 'center',
    backgroundColor: '#00E5FF', borderRadius: 4,
  },
  confirmBtnText: { color: '#000', fontWeight: '700' },
});
