import React, { useState, useEffect, useCallback } from 'react';
import {
  View, Text, TouchableOpacity, StyleSheet, ActivityIndicator,
  Alert, ScrollView, 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';
import * as Location from 'expo-location';

const API_URL = process.env.EXPO_PUBLIC_BACKEND_URL;

type Employee = { employee_id: string; name: string; role: string };
type AttendanceStatus = {
  date: string; has_login: boolean; has_logout: boolean;
  can_login: boolean; can_logout: boolean;
  login_time: string | null; logout_time: string | null;
  login_location: string | null; logout_location: string | null;
};

export default function DashboardScreen() {
  const router = useRouter();
  const [employee, setEmployee] = useState<Employee | null>(null);
  const [status, setStatus] = useState<AttendanceStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState('');
  const [refreshing, setRefreshing] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const timer = setInterval(() => setCurrentTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

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

  const loadData = useCallback(async () => {
    try {
      const empStr = await storage.getItemAsync('employee');
      if (!empStr) { router.replace('/'); return; }
      setEmployee(JSON.parse(empStr));

      const token = await getToken();
      const res = await fetch(`${API_URL}/api/attendance/status`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.status === 401) { await logout(); return; }
      const data = await res.json();
      setStatus(data);
    } catch (e) {
      console.error('Load error:', e);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

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

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

  const getLocation = async (): Promise<{ latitude: number; longitude: number } | null> => {
    try {
      const { status: permStatus } = await Location.requestForegroundPermissionsAsync();
      if (permStatus !== 'granted') {
        Alert.alert('Permission Required', 'Location permission is needed to mark attendance.');
        return null;
      }
      const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
      return { latitude: loc.coords.latitude, longitude: loc.coords.longitude };
    } catch (e) {
      Alert.alert('Location Error', 'Could not get your location. Please enable GPS.');
      return null;
    }
  };

  const markAttendance = async (action: 'login' | 'logout') => {
    if (actionLoading) return;
    setActionLoading(action);
    try {
      const location = await getLocation();
      if (!location) { setActionLoading(''); return; }

      const token = await getToken();
      const res = await fetch(`${API_URL}/api/attendance/${action}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(location),
      });
      const data = await res.json();
      if (!res.ok) {
        Alert.alert('Error', data.detail || `Failed to mark ${action}`);
      } else {
        Alert.alert('Success', data.message);
        await loadData();
      }
    } catch (e) {
      Alert.alert('Error', 'Network error. Please try again.');
    } finally {
      setActionLoading('');
    }
  };

  const getISTTime = () => {
    return currentTime.toLocaleString('en-IN', {
      timeZone: 'Asia/Kolkata',
      hour: '2-digit', minute: '2-digit', second: '2-digit',
      hour12: true,
    });
  };

  const getISTDate = () => {
    return currentTime.toLocaleString('en-IN', {
      timeZone: 'Asia/Kolkata',
      weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
    });
  };

  if (loading) {
    return (
      <SafeAreaView style={styles.safe}>
        <View style={styles.center}>
          <ActivityIndicator size="large" color="#00E5FF" />
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.safe}>
      <ScrollView
        contentContainerStyle={styles.scroll}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); loadData(); }} tintColor="#00E5FF" />}
      >
        {/* Header */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>Welcome,</Text>
            <Text testID="employee-name" style={styles.name}>{employee?.name}</Text>
            <Text style={styles.empId}>{employee?.employee_id}</Text>
          </View>
          <TouchableOpacity testID="logout-app-btn" onPress={logout} style={styles.logoutAppBtn}>
            <MaterialCommunityIcons name="logout" size={22} color="#FF3D00" />
          </TouchableOpacity>
        </View>

        {/* Clock */}
        <View style={styles.clockCard}>
          <Text testID="current-time" style={styles.clockTime}>{getISTTime()}</Text>
          <Text style={styles.clockDate}>{getISTDate()}</Text>
          <Text style={styles.clockTz}>IST (India Standard Time)</Text>
        </View>

        {/* Status Card */}
        <View style={styles.statusCard}>
          <Text style={styles.sectionTitle}>TODAY'S STATUS</Text>
          <View style={styles.statusRow}>
            <View style={[styles.statusItem, status?.has_login ? styles.statusActive : styles.statusInactive]}>
              <MaterialCommunityIcons
                name={status?.has_login ? 'check-circle' : 'circle-outline'}
                size={28}
                color={status?.has_login ? '#00C853' : '#475569'}
              />
              <Text style={styles.statusLabel}>Login</Text>
              <Text style={styles.statusTime}>{status?.login_time || '--:--'}</Text>
            </View>
            <View style={styles.statusDivider} />
            <View style={[styles.statusItem, status?.has_logout ? styles.statusActive : styles.statusInactive]}>
              <MaterialCommunityIcons
                name={status?.has_logout ? 'check-circle' : 'circle-outline'}
                size={28}
                color={status?.has_logout ? '#FF3D00' : '#475569'}
              />
              <Text style={styles.statusLabel}>Logout</Text>
              <Text style={styles.statusTime}>{status?.logout_time || '--:--'}</Text>
            </View>
          </View>
        </View>

        {/* Action Buttons */}
        <View style={styles.actionsContainer}>
          <TouchableOpacity
            testID="mark-login-btn"
            style={[styles.actionBtn, styles.loginActionBtn, !status?.can_login && styles.actionBtnDisabled]}
            onPress={() => markAttendance('login')}
            disabled={!status?.can_login || actionLoading !== ''}
            activeOpacity={0.7}
          >
            {actionLoading === 'login' ? (
              <ActivityIndicator color="#000" size="small" />
            ) : (
              <>
                <MaterialCommunityIcons name="login" size={32} color={status?.can_login ? '#000' : '#6E6E6E'} />
                <Text style={[styles.actionBtnText, !status?.can_login && styles.actionBtnTextDisabled]}>
                  MARK LOGIN
                </Text>
                <Text style={[styles.actionBtnSub, !status?.can_login && styles.actionBtnTextDisabled]}>
                  {status?.has_login ? 'Already logged in' : 'Tap to mark your login'}
                </Text>
              </>
            )}
          </TouchableOpacity>

          <TouchableOpacity
            testID="mark-logout-btn"
            style={[styles.actionBtn, styles.logoutActionBtn, !status?.can_logout && styles.actionBtnDisabled]}
            onPress={() => markAttendance('logout')}
            disabled={!status?.can_logout || actionLoading !== ''}
            activeOpacity={0.7}
          >
            {actionLoading === 'logout' ? (
              <ActivityIndicator color="#FFF" size="small" />
            ) : (
              <>
                <MaterialCommunityIcons name="logout" size={32} color={status?.can_logout ? '#FFF' : '#6E6E6E'} />
                <Text style={[styles.logoutBtnText, !status?.can_logout && styles.actionBtnTextDisabled]}>
                  MARK LOGOUT
                </Text>
                <Text style={[styles.logoutBtnSub, !status?.can_logout && styles.actionBtnTextDisabled]}>
                  {status?.has_logout ? 'Already logged out' : !status?.has_login ? 'Login first' : 'Tap to mark your logout'}
                </Text>
              </>
            )}
          </TouchableOpacity>
        </View>

        {/* Quick Links */}
        <View style={styles.linksRow}>
          <TouchableOpacity testID="history-link" style={styles.linkBtn} onPress={() => router.push('/history')}>
            <MaterialCommunityIcons name="history" size={20} color="#00E5FF" />
            <Text style={styles.linkText}>History</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  scroll: { padding: 20 },
  header: {
    flexDirection: 'row', justifyContent: 'space-between',
    alignItems: 'flex-start', marginBottom: 24,
  },
  greeting: { color: '#6E6E6E', fontSize: 14 },
  name: { color: '#FFF', fontSize: 24, fontWeight: '700', marginTop: 2 },
  empId: { color: '#00E5FF', fontSize: 13, marginTop: 2, letterSpacing: 1 },
  logoutAppBtn: {
    padding: 12, backgroundColor: '#1E1E1E', borderRadius: 8,
  },
  clockCard: {
    backgroundColor: '#121212', borderLeftWidth: 4, borderLeftColor: '#00E5FF',
    padding: 20, marginBottom: 20, borderRadius: 2,
    alignItems: 'center',
  },
  clockTime: { color: '#00E5FF', fontSize: 36, fontWeight: '900', letterSpacing: 2 },
  clockDate: { color: '#E5E7EB', fontSize: 15, marginTop: 6 },
  clockTz: { color: '#6E6E6E', fontSize: 12, marginTop: 4 },
  statusCard: {
    backgroundColor: '#121212', padding: 20, marginBottom: 24,
    borderRadius: 2,
  },
  sectionTitle: {
    color: '#B0B0B0', fontSize: 12, fontWeight: '700',
    letterSpacing: 2, marginBottom: 16,
  },
  statusRow: { flexDirection: 'row', alignItems: 'center' },
  statusItem: { flex: 1, alignItems: 'center', paddingVertical: 8 },
  statusActive: {},
  statusInactive: { opacity: 0.5 },
  statusDivider: { width: 1, height: 60, backgroundColor: '#333' },
  statusLabel: { color: '#E5E7EB', fontSize: 14, fontWeight: '600', marginTop: 6 },
  statusTime: { color: '#6E6E6E', fontSize: 13, marginTop: 4 },
  actionsContainer: { marginBottom: 24, gap: 16 },
  actionBtn: {
    borderRadius: 4, paddingVertical: 24, paddingHorizontal: 20,
    alignItems: 'center', justifyContent: 'center',
  },
  loginActionBtn: {
    backgroundColor: '#00E5FF',
    shadowColor: '#00E5FF', shadowOpacity: 0.3, shadowRadius: 10, elevation: 5,
  },
  logoutActionBtn: {
    backgroundColor: 'transparent', borderWidth: 2, borderColor: '#FF3D00',
  },
  actionBtnDisabled: {
    backgroundColor: '#1E1E1E', borderColor: '#333',
    shadowOpacity: 0, elevation: 0,
  },
  actionBtnText: {
    color: '#000', fontWeight: '700', fontSize: 18,
    letterSpacing: 2, marginTop: 8,
  },
  actionBtnSub: { color: '#333', fontSize: 12, marginTop: 4 },
  actionBtnTextDisabled: { color: '#6E6E6E' },
  logoutBtnText: {
    color: '#FF3D00', fontWeight: '700', fontSize: 18,
    letterSpacing: 2, marginTop: 8,
  },
  logoutBtnSub: { color: '#6E6E6E', fontSize: 12, marginTop: 4 },
  linksRow: {
    flexDirection: 'row', justifyContent: 'center', gap: 20,
  },
  linkBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6,
    backgroundColor: '#121212', paddingVertical: 12, paddingHorizontal: 24,
    borderRadius: 4,
  },
  linkText: { color: '#00E5FF', fontSize: 14, fontWeight: '600' },
});
