import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert, useWindowDimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useThemeContext } from '../../components/ThemeProvider';
import { useAuth } from '../../hooks/useAuth';
import { spacing, borderRadius, shadows } from '../../constants/theme';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import api from '../../services/api';

const TABLET_MIN_WIDTH = 768;

interface NotificationItem {
  scope: string;
  id: number;
  medicine_name?: string;
  medicine_nregistro?: string;
  pharmacy_name?: string;
  pharmacy_id?: number;
  pharmacy_address?: string;
  created_at?: string;
}

export default function AlertsScreen() {
  const router = useRouter();
  const { width } = useWindowDimensions();
  const isTablet = width >= TABLET_MIN_WIDTH;
  const { colors } = useThemeContext();
  const { isAuthenticated, isLoading: authLoading } = useAuth();
  const [items, setItems] = useState<NotificationItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  useEffect(() => {
    if (!authLoading && isAuthenticated) {
      loadNotifications();
    } else if (!authLoading && !isAuthenticated) {
      setIsLoading(false);
    }
  }, [authLoading, isAuthenticated]);

  async function loadNotifications() {
    setIsLoading(true);
    setError(null);
    try {
      const res = await api.get('/notifications/mine');
      const data = res.data;
      const merged = [
        ...(data.pharmacy || []),
        ...(data.global || []),
      ].sort((a: NotificationItem, b: NotificationItem) =>
        (b.created_at || '').localeCompare(a.created_at || '')
      );
      setItems(merged);
    } catch (err: any) {
      setError(err.message || 'No se pudieron cargar las notificaciones');
    } finally {
      setIsLoading(false);
    }
  }

  async function handleDelete(item: NotificationItem) {
    const key = `${item.scope}:${item.id}`;
    Alert.alert(
      'Eliminar notificación',
      `¿Eliminar la notificación de ${item.medicine_name || item.medicine_nregistro}?`,
      [
        { text: 'Cancelar', style: 'cancel' },
        {
          text: 'Eliminar',
          style: 'destructive',
          onPress: async () => {
            setDeletingId(key);
            try {
              await api.delete('/notifications/mine', {
                data: { scope: item.scope, id: item.id },
              });
              setItems(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
            } catch (err: any) {
              Alert.alert('Error', err.message || 'No se pudo eliminar');
            } finally {
              setDeletingId(null);
            }
          },
        },
      ]
    );
  }

  function renderItem({ item }: { item: NotificationItem }) {
    const key = `${item.scope}:${item.id}`;
    return (
      <View style={[styles.item, { backgroundColor: colors.card }]}>
        <View style={styles.itemContent}>
          <Text style={[styles.itemName, { color: colors.text }]} numberOfLines={2}>
            {item.medicine_name || item.medicine_nregistro}
          </Text>
          <View style={styles.itemMeta}>
            <View style={[styles.chip, { backgroundColor: colors.primaryContainer }]}>
              <Ionicons
                name={item.scope === 'pharmacy' ? 'medical' : 'globe'}
                size={12}
                color={colors.primary}
              />
              <Text style={[styles.chipText, { color: colors.onPrimaryContainer }]}>
                {item.scope === 'pharmacy'
                  ? item.pharmacy_name || `Farmacia #${item.pharmacy_id}`
                  : 'Cualquier farmacia'}
              </Text>
            </View>
            {item.pharmacy_address && (
              <Text style={[styles.itemAddress, { color: colors.textSecondary }]} numberOfLines={1}>
                {item.pharmacy_address}
              </Text>
            )}
          </View>
        </View>
        <TouchableOpacity
          style={[styles.deleteButton, { backgroundColor: colors.dangerContainer }]}
          onPress={() => handleDelete(item)}
          disabled={deletingId === key}
        >
          {deletingId === key ? (
            <Ionicons name="hourglass" size={18} color={colors.danger} />
          ) : (
            <Ionicons name="trash-outline" size={18} color={colors.danger} />
          )}
        </TouchableOpacity>
      </View>
    );
  }

  if (isLoading || authLoading) {
    return <LoadingSpinner message="Cargando notificaciones..." />;
  }

  if (!isAuthenticated) {
    return (
      <View style={[styles.container, styles.centered, { backgroundColor: colors.background }]}>
        <Ionicons name="lock-closed-outline" size={64} color={colors.border} />
        <Text style={[styles.loginTitle, { color: colors.text }]}>Inicia sesión para continuar</Text>
        <Text style={[styles.loginSubtitle, { color: colors.textSecondary }]}>
          Necesitas estar autenticado para ver tus notificaciones
        </Text>
        <TouchableOpacity
          style={[styles.loginButton, { backgroundColor: colors.primary }]}
          onPress={() => router.push('/auth/login')}
        >
          <Text style={[styles.loginButtonText, { color: colors.onPrimaryContainer }]}>Iniciar Sesión</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={[styles.header, isTablet && styles.headerTablet]}>
        <Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Notificaciones Guardadas</Text>
        <Text style={[styles.subtitle, isTablet && styles.subtitleTablet, { color: colors.textSecondary }]}>
          Recibe avisos cuando medicamentos sin stock se repongan
        </Text>
      </View>

      {error && (
        <View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
          <Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
          <TouchableOpacity onPress={loadNotifications} style={styles.retryButton}>
            <Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
          </TouchableOpacity>
        </View>
      )}

      {!error && items.length === 0 && (
        <View style={styles.emptyContainer}>
          <Ionicons name="notifications-off-outline" size={isTablet ? 80 : 64} color={colors.border} />
          <Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet, { color: colors.text }]}>Sin notificaciones</Text>
          <Text style={[styles.emptyText, isTablet && styles.emptyTextTablet, { color: colors.textSecondary }]}>
            Toca la campana en una farmacia sin stock para recibir notificaciones cuando se reponga.
          </Text>
        </View>
      )}

      {!error && items.length > 0 && (
        <FlatList
          data={items}
          keyExtractor={(item) => `${item.scope}:${item.id}`}
          renderItem={renderItem}
          contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
          showsVerticalScrollIndicator={false}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  centered: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing.xl,
    gap: spacing.md,
  },
  loginTitle: {
    fontSize: 20,
    fontWeight: '600',
    textAlign: 'center',
  },
  loginSubtitle: {
    fontSize: 14,
    textAlign: 'center',
    lineHeight: 20,
  },
  loginButton: {
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    borderRadius: borderRadius.lg,
    marginTop: spacing.sm,
  },
  loginButtonText: {
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.md,
  },
  headerTablet: {
    maxWidth: 700,
    alignSelf: 'center',
    width: '100%',
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  titleTablet: {
    fontSize: 28,
  },
  subtitle: {
    fontSize: 14,
    marginTop: spacing.xs,
    lineHeight: 20,
  },
  subtitleTablet: {
    fontSize: 16,
    lineHeight: 24,
  },
  list: {
    paddingHorizontal: spacing.lg,
    paddingBottom: spacing.xl,
    gap: spacing.sm,
  },
  listTablet: {
    maxWidth: 700,
    alignSelf: 'center',
    width: '100%',
  },
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: borderRadius.lg,
    padding: spacing.md,
    ...shadows.card,
  },
  itemContent: {
    flex: 1,
    gap: spacing.xs,
  },
  itemName: {
    fontSize: 16,
    fontWeight: '600',
    lineHeight: 22,
  },
  itemMeta: {
    gap: spacing.xs,
  },
  chip: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
    borderRadius: borderRadius.full,
    paddingHorizontal: spacing.sm,
    paddingVertical: 3,
    alignSelf: 'flex-start',
  },
  chipText: {
    fontSize: 12,
    fontWeight: '600',
  },
  itemAddress: {
    fontSize: 12,
  },
  deleteButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: spacing.sm,
  },
  errorContainer: {
    margin: spacing.lg,
    padding: spacing.md,
    borderRadius: borderRadius.lg,
    alignItems: 'center',
    gap: spacing.sm,
  },
  errorContainerTablet: {
    maxWidth: 700,
    alignSelf: 'center',
  },
  errorText: {
    fontSize: 14,
    textAlign: 'center',
  },
  retryButton: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
  },
  retryText: {
    fontSize: 14,
    fontWeight: '600',
  },
  emptyContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing.xl,
    gap: spacing.md,
  },
  emptyTitle: {
    fontSize: 18,
    fontWeight: '600',
  },
  emptyTitleTablet: {
    fontSize: 24,
  },
  emptyText: {
    fontSize: 14,
    textAlign: 'center',
    lineHeight: 20,
  },
  emptyTextTablet: {
    fontSize: 16,
    maxWidth: 400,
    lineHeight: 24,
  },
});
