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

export default function PatientDashboardScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [patient, setPatient] = useState<Patient | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadPatient = useCallback(async (showLoading = true) => {
    if (!id) return;

    if (showLoading) setIsLoading(true);
    setError(null);

    try {
      const response = await api.getPatient(parseInt(id, 10));

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

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

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

  const handleChatPress = () => {
    router.push('/(tabs)/chat');
  };

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

  if (error || !patient) {
    return (
      <FullScreenError
        message={error || 'Patient not found'}
        onRetry={() => loadPatient()}
      />
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => router.back()}
        >
          <Ionicons name="arrow-back" size={24} color={AppColors.textPrimary} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>{patient.name}</Text>
        <TouchableOpacity style={styles.menuButton}>
          <Ionicons name="ellipsis-vertical" size={24} color={AppColors.textPrimary} />
        </TouchableOpacity>
      </View>

      <ScrollView
        style={styles.content}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor={AppColors.primary}
          />
        }
      >
        {/* Patient Info Card */}
        <View style={styles.infoCard}>
          <View style={styles.avatarContainer}>
            <Text style={styles.avatarText}>
              {patient.name.charAt(0).toUpperCase()}
            </Text>
            <View
              style={[
                styles.statusBadge,
                patient.status === 'online' ? styles.onlineBadge : styles.offlineBadge,
              ]}
            >
              <Text style={styles.statusText}>
                {patient.status === 'online' ? 'Online' : 'Offline'}
              </Text>
            </View>
          </View>

          <Text style={styles.patientName}>{patient.name}</Text>
          <Text style={styles.relationship}>{patient.relationship}</Text>
          <Text style={styles.lastSeen}>
            Last activity: {patient.last_activity}
          </Text>
        </View>

        {/* Health Stats */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Health Overview</Text>

          <View style={styles.statsGrid}>
            <View style={styles.statCard}>
              <View style={[styles.statIcon, { backgroundColor: '#FEE2E2' }]}>
                <Ionicons name="heart" size={24} color={AppColors.error} />
              </View>
              <Text style={styles.statValue}>
                {patient.health_data?.heart_rate || '--'}
              </Text>
              <Text style={styles.statLabel}>Heart Rate</Text>
              <Text style={styles.statUnit}>BPM</Text>
            </View>

            <View style={styles.statCard}>
              <View style={[styles.statIcon, { backgroundColor: '#DBEAFE' }]}>
                <Ionicons name="footsteps" size={24} color={AppColors.primary} />
              </View>
              <Text style={styles.statValue}>
                {patient.health_data?.steps?.toLocaleString() || '--'}
              </Text>
              <Text style={styles.statLabel}>Steps Today</Text>
              <Text style={styles.statUnit}>steps</Text>
            </View>

            <View style={styles.statCard}>
              <View style={[styles.statIcon, { backgroundColor: '#E0E7FF' }]}>
                <Ionicons name="moon" size={24} color={AppColors.primaryDark} />
              </View>
              <Text style={styles.statValue}>
                {patient.health_data?.sleep_hours || '--'}
              </Text>
              <Text style={styles.statLabel}>Sleep</Text>
              <Text style={styles.statUnit}>hours</Text>
            </View>
          </View>
        </View>

        {/* Quick Actions */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Actions</Text>

          <View style={styles.actionsGrid}>
            <TouchableOpacity style={styles.actionCard} onPress={handleChatPress}>
              <View style={[styles.actionIcon, { backgroundColor: '#D1FAE5' }]}>
                <Ionicons name="chatbubble-ellipses" size={24} color={AppColors.success} />
              </View>
              <Text style={styles.actionLabel}>Chat with Julia</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.actionCard}>
              <View style={[styles.actionIcon, { backgroundColor: '#FEF3C7' }]}>
                <Ionicons name="notifications" size={24} color={AppColors.warning} />
              </View>
              <Text style={styles.actionLabel}>Set Reminder</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.actionCard}>
              <View style={[styles.actionIcon, { backgroundColor: '#DBEAFE' }]}>
                <Ionicons name="call" size={24} color={AppColors.primary} />
              </View>
              <Text style={styles.actionLabel}>Video Call</Text>
            </TouchableOpacity>

            <TouchableOpacity style={styles.actionCard}>
              <View style={[styles.actionIcon, { backgroundColor: '#F3E8FF' }]}>
                <Ionicons name="medkit" size={24} color="#9333EA" />
              </View>
              <Text style={styles.actionLabel}>Medications</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Chat with Julia Button */}
        <View style={styles.chatButtonContainer}>
          <Button
            title="Chat with Julia AI"
            onPress={handleChatPress}
            fullWidth
            size="lg"
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.surface,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    backgroundColor: AppColors.background,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  backButton: {
    padding: Spacing.xs,
  },
  headerTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  menuButton: {
    padding: Spacing.xs,
  },
  content: {
    flex: 1,
  },
  infoCard: {
    backgroundColor: AppColors.background,
    padding: Spacing.xl,
    alignItems: 'center',
    marginBottom: Spacing.md,
  },
  avatarContainer: {
    width: 100,
    height: 100,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.md,
  },
  avatarText: {
    fontSize: FontSizes['3xl'],
    fontWeight: '600',
    color: AppColors.white,
  },
  statusBadge: {
    position: 'absolute',
    bottom: 0,
    paddingHorizontal: Spacing.sm,
    paddingVertical: Spacing.xs,
    borderRadius: BorderRadius.full,
  },
  onlineBadge: {
    backgroundColor: AppColors.success,
  },
  offlineBadge: {
    backgroundColor: AppColors.offline,
  },
  statusText: {
    fontSize: FontSizes.xs,
    fontWeight: '500',
    color: AppColors.white,
  },
  patientName: {
    fontSize: FontSizes['2xl'],
    fontWeight: '700',
    color: AppColors.textPrimary,
  },
  relationship: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    marginTop: Spacing.xs,
  },
  lastSeen: {
    fontSize: FontSizes.sm,
    color: AppColors.textMuted,
    marginTop: Spacing.sm,
  },
  section: {
    backgroundColor: AppColors.background,
    padding: Spacing.lg,
    marginBottom: Spacing.md,
  },
  sectionTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
    marginBottom: Spacing.md,
  },
  statsGrid: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  statCard: {
    flex: 1,
    alignItems: 'center',
    padding: Spacing.sm,
  },
  statIcon: {
    width: 48,
    height: 48,
    borderRadius: BorderRadius.lg,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.sm,
  },
  statValue: {
    fontSize: FontSizes.xl,
    fontWeight: '700',
    color: AppColors.textPrimary,
  },
  statLabel: {
    fontSize: FontSizes.xs,
    color: AppColors.textSecondary,
    marginTop: Spacing.xs,
  },
  statUnit: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
  },
  actionsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  actionCard: {
    width: '48%',
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.lg,
    padding: Spacing.md,
    alignItems: 'center',
    marginBottom: Spacing.md,
  },
  actionIcon: {
    width: 48,
    height: 48,
    borderRadius: BorderRadius.lg,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.sm,
  },
  actionLabel: {
    fontSize: FontSizes.sm,
    fontWeight: '500',
    color: AppColors.textPrimary,
    textAlign: 'center',
  },
  chatButtonContainer: {
    padding: Spacing.lg,
    paddingBottom: Spacing.xxl,
  },
});
