import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { router } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import { api } from '@/services/api';
import { useAuth } from '@/contexts/AuthContext';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
import { FullScreenError } from '@/components/ui/ErrorMessage';
import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme';
import type { Patient } from '@/types';

export default function PatientsListScreen() {
  const { user } = useAuth();
  const [patients, setPatients] = useState<Patient[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadPatients = useCallback(async (showLoading = true) => {
    if (showLoading) setIsLoading(true);
    setError(null);

    try {
      const response = await api.getPatients();

      if (response.ok && response.data) {
        setPatients(response.data.patients);
      } else {
        setError(response.error?.message || 'Failed to load patients');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, []);

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

  const handleRefresh = useCallback(() => {
    setIsRefreshing(true);
    loadPatients(false);
  }, [loadPatients]);

  const handlePatientPress = (patient: Patient) => {
    router.push(`/patients/${patient.id}`);
  };

  const renderPatientCard = ({ item }: { item: Patient }) => (
    <TouchableOpacity
      style={styles.patientCard}
      onPress={() => handlePatientPress(item)}
      activeOpacity={0.7}
    >
      <View style={styles.patientInfo}>
        <View style={styles.avatarContainer}>
          <Text style={styles.avatarText}>
            {item.name.charAt(0).toUpperCase()}
          </Text>
          <View
            style={[
              styles.statusIndicator,
              item.status === 'online' ? styles.online : styles.offline,
            ]}
          />
        </View>

        <View style={styles.patientDetails}>
          <Text style={styles.patientName}>{item.name}</Text>
          <Text style={styles.patientRelationship}>{item.relationship}</Text>
          <Text style={styles.lastActivity}>
            <Ionicons name="time-outline" size={12} color={AppColors.textMuted} />{' '}
            {item.last_activity}
          </Text>
        </View>
      </View>

      {item.health_data && (
        <View style={styles.healthStats}>
          <View style={styles.statItem}>
            <Ionicons name="heart-outline" size={16} color={AppColors.error} />
            <Text style={styles.statValue}>{item.health_data.heart_rate}</Text>
            <Text style={styles.statLabel}>BPM</Text>
          </View>
          <View style={styles.statItem}>
            <Ionicons name="footsteps-outline" size={16} color={AppColors.primary} />
            <Text style={styles.statValue}>{item.health_data.steps?.toLocaleString()}</Text>
            <Text style={styles.statLabel}>Steps</Text>
          </View>
          <View style={styles.statItem}>
            <Ionicons name="moon-outline" size={16} color={AppColors.primaryDark} />
            <Text style={styles.statValue}>{item.health_data.sleep_hours}h</Text>
            <Text style={styles.statLabel}>Sleep</Text>
          </View>
        </View>
      )}

      <Ionicons
        name="chevron-forward"
        size={20}
        color={AppColors.textMuted}
        style={styles.chevron}
      />
    </TouchableOpacity>
  );

  if (isLoading) {
    return <LoadingSpinner fullScreen message="Loading patients..." />;
  }

  if (error) {
    return <FullScreenError message={error} onRetry={() => loadPatients()} />;
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <View>
          <Text style={styles.greeting}>
            Hello, {user?.user_name || 'User'}
          </Text>
          <Text style={styles.headerTitle}>Your Patients</Text>
        </View>
        <TouchableOpacity style={styles.addButton}>
          <Ionicons name="add" size={24} color={AppColors.white} />
        </TouchableOpacity>
      </View>

      {/* Patient List */}
      <FlatList
        data={patients}
        keyExtractor={(item) => item.id.toString()}
        renderItem={renderPatientCard}
        contentContainerStyle={styles.listContent}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor={AppColors.primary}
          />
        }
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Ionicons name="people-outline" size={64} color={AppColors.textMuted} />
            <Text style={styles.emptyTitle}>No patients yet</Text>
            <Text style={styles.emptyText}>
              Add your first patient to start monitoring
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.surface,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.md,
    backgroundColor: AppColors.background,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  greeting: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
  },
  headerTitle: {
    fontSize: FontSizes.xl,
    fontWeight: '700',
    color: AppColors.textPrimary,
  },
  addButton: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContent: {
    padding: Spacing.md,
  },
  patientCard: {
    backgroundColor: AppColors.background,
    borderRadius: BorderRadius.lg,
    padding: Spacing.md,
    marginBottom: Spacing.md,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  patientInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: Spacing.md,
  },
  avatarContainer: {
    width: 56,
    height: 56,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.md,
  },
  avatarText: {
    fontSize: FontSizes.xl,
    fontWeight: '600',
    color: AppColors.white,
  },
  statusIndicator: {
    position: 'absolute',
    bottom: 2,
    right: 2,
    width: 14,
    height: 14,
    borderRadius: BorderRadius.full,
    borderWidth: 2,
    borderColor: AppColors.background,
  },
  online: {
    backgroundColor: AppColors.online,
  },
  offline: {
    backgroundColor: AppColors.offline,
  },
  patientDetails: {
    flex: 1,
  },
  patientName: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  patientRelationship: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    marginTop: 2,
  },
  lastActivity: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginTop: 4,
  },
  healthStats: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingTop: Spacing.md,
    borderTopWidth: 1,
    borderTopColor: AppColors.border,
  },
  statItem: {
    alignItems: 'center',
  },
  statValue: {
    fontSize: FontSizes.base,
    fontWeight: '600',
    color: AppColors.textPrimary,
    marginTop: Spacing.xs,
  },
  statLabel: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
  },
  chevron: {
    position: 'absolute',
    top: Spacing.md,
    right: Spacing.md,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Spacing.xxl * 2,
  },
  emptyTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
    marginTop: Spacing.md,
  },
  emptyText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    marginTop: Spacing.xs,
  },
});
