import React, { useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  Modal,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  Alert,
  StatusBar,
  Platform,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import { Ionicons } from "@expo/vector-icons";
import { theme } from "../styles/theme";
import { useNotifications } from "../contexts/NotificationsContext";
import type { Notification } from "../api/notifications";
import log from "../utils/logger";

interface NotificationsModalProps {
  visible: boolean;
  onClose: () => void;
}

export function NotificationsModal({
  visible,
  onClose,
}: NotificationsModalProps) {
  const {
    notifications,
    loading,
    markNotificationAsRead,
    deleteNotificationAction,
    markAllAsReadAction,
  } = useNotifications();

  useEffect(() => {
    if (visible) {
      log.debug("NotificationsModal opened", {
        notificationCount: notifications.length,
        loading,
      });
    }
  }, [visible, notifications.length, loading]);

  const handleMarkAsRead = async (id: string) => {
    await markNotificationAsRead(id);
  };

  const handleDelete = (id: string) => {
    Alert.alert("Delete Notification", "Are you sure?", [
      { text: "Cancel", style: "cancel" },
      {
        text: "Delete",
        style: "destructive",
        onPress: () => deleteNotificationAction(id),
      },
    ]);
  };

  const handleMarkAllAsRead = () => {
    if (notifications.filter((n) => !n.read).length === 0) return;
    Alert.alert("Mark All as Read", "Mark all notifications as read?", [
      { text: "Cancel", style: "cancel" },
      {
        text: "Mark All",
        onPress: () => markAllAsReadAction(),
      },
    ]);
  };

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="fullScreen"
      onRequestClose={onClose}
      transparent={false}
      statusBarTranslucent={false}
    >
      <View style={styles.modalWrapper}>
        <StatusBar barStyle="light-content" />
        <View style={styles.container}>
          {/* Header */}
          <LinearGradient
            colors={theme.gradients.primary}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.header}
          >
            <View style={styles.headerContent}>
              <View>
                <Text style={styles.headerTitle}>Notifications</Text>
                <Text style={styles.headerSubtitle}>
                  {notifications.filter((n) => !n.read).length} unread
                </Text>
              </View>
              <TouchableOpacity onPress={onClose} style={styles.closeButton}>
                <Ionicons name="close" size={28} color="#fff" />
              </TouchableOpacity>
            </View>
          </LinearGradient>

          {/* Actions Bar */}
          {notifications.length > 0 && (
            <View style={styles.actionsBar}>
              <TouchableOpacity
                onPress={handleMarkAllAsRead}
                disabled={notifications.filter((n) => !n.read).length === 0}
              >
                <Text
                  style={[
                    styles.actionText,
                    notifications.filter((n) => !n.read).length === 0 &&
                      styles.actionTextDisabled,
                  ]}
                >
                  Mark all as read
                </Text>
              </TouchableOpacity>
            </View>
          )}

          {/* Notifications List */}
          {loading ? (
            <View style={styles.centered}>
              <ActivityIndicator size="large" color={theme.colors.primary} />
            </View>
          ) : notifications.length === 0 ? (
            <View style={styles.emptyState}>
              <LinearGradient
                colors={["rgba(59, 130, 246, 0.1)", "rgba(59, 130, 246, 0.05)"]}
                style={styles.emptyCard}
              >
                <Ionicons
                  name="notifications-off-outline"
                  size={64}
                  color={theme.colors.primary}
                />
                <Text style={styles.emptyTitle}>No Notifications</Text>
                <Text style={styles.emptyText}>
                  You're all caught up! New notifications will appear here.
                </Text>
              </LinearGradient>
            </View>
          ) : (
            <FlatList
              data={notifications}
              keyExtractor={(item) => item.id}
              renderItem={({ item }) => (
                <NotificationItem
                  notification={item}
                  onMarkAsRead={handleMarkAsRead}
                  onDelete={handleDelete}
                />
              )}
              contentContainerStyle={styles.listContent}
            />
          )}
        </View>
      </View>
    </Modal>
  );
}

interface NotificationItemProps {
  notification: Notification;
  onMarkAsRead: (id: string) => void;
  onDelete: (id: string) => void;
}

function NotificationItem({
  notification,
  onMarkAsRead,
  onDelete,
}: NotificationItemProps) {
  const getIcon = (type: Notification["type"]) => {
    switch (type) {
      case "payment_reminder":
        return "card-outline";
      case "attendance":
        return "checkmark-circle-outline";
      case "promotion":
        return "megaphone-outline";
      case "system":
      default:
        return "information-circle-outline";
    }
  };

  const getIconColor = (type: Notification["type"]) => {
    switch (type) {
      case "payment_reminder":
        return theme.colors.warning;
      case "attendance":
        return theme.colors.success;
      case "promotion":
        return theme.colors.purple;
      case "system":
      default:
        return theme.colors.primary;
    }
  };

  const formatTime = (date: Date) => {
    const now = new Date();
    const diff = now.getTime() - new Date(date).getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (minutes < 1) return "Just now";
    if (minutes < 60) return `${minutes}m ago`;
    if (hours < 24) return `${hours}h ago`;
    if (days < 7) return `${days}d ago`;
    return new Date(date).toLocaleDateString();
  };

  return (
    <TouchableOpacity
      onPress={() => !notification.read && onMarkAsRead(notification.id)}
      activeOpacity={0.7}
    >
      <View
        style={[styles.notificationCard, !notification.read && styles.unread]}
      >
        <View style={styles.notificationContent}>
          {/* Icon */}
          <View
            style={[
              styles.iconCircle,
              { backgroundColor: `${getIconColor(notification.type)}20` },
            ]}
          >
            <Ionicons
              name={getIcon(notification.type)}
              size={24}
              color={getIconColor(notification.type)}
            />
          </View>

          {/* Content */}
          <View style={styles.textContent}>
            <Text
              style={[
                styles.notificationTitle,
                !notification.read && styles.notificationTitleUnread,
              ]}
            >
              {notification.title}
            </Text>
            <Text style={styles.notificationMessage}>
              {notification.message}
            </Text>
            <Text style={styles.notificationTime}>
              {formatTime(notification.createdAt)}
            </Text>
          </View>

          {/* Actions */}
          <TouchableOpacity
            onPress={() => onDelete(notification.id)}
            style={styles.deleteButton}
          >
            <Ionicons
              name="trash-outline"
              size={20}
              color={theme.colors.gray400}
            />
          </TouchableOpacity>
        </View>

        {/* Unread Indicator */}
        {!notification.read && <View style={styles.unreadDot} />}
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  modalWrapper: {
    flex: 1,
    width: "100%",
    height: "100%",
  },
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
    margin: 0,
    padding: 0,
  },
  header: {
    paddingTop: Platform.OS === "android" ? 50 : 60,
    paddingBottom: 20,
    paddingHorizontal: 20,
    borderBottomLeftRadius: theme.borderRadius.xl,
    borderBottomRightRadius: theme.borderRadius.xl,
  },
  headerContent: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  headerTitle: {
    fontSize: theme.typography.fontSize["3xl"],
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.white,
  },
  headerSubtitle: {
    fontSize: theme.typography.fontSize.base,
    color: "rgba(255, 255, 255, 0.9)",
    marginTop: 4,
  },
  closeButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    justifyContent: "center",
    alignItems: "center",
  },
  actionsBar: {
    flexDirection: "row",
    justifyContent: "flex-end",
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.gray200,
  },
  actionText: {
    fontSize: theme.typography.fontSize.sm,
    fontWeight: theme.typography.fontWeight.semibold,
    color: theme.colors.primary,
  },
  actionTextDisabled: {
    color: theme.colors.gray400,
  },
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  emptyState: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 40,
  },
  emptyCard: {
    borderRadius: theme.borderRadius["2xl"],
    padding: 40,
    alignItems: "center",
    width: "100%",
  },
  emptyTitle: {
    fontSize: theme.typography.fontSize.xl,
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.gray700,
    marginTop: 16,
    marginBottom: 8,
  },
  emptyText: {
    fontSize: theme.typography.fontSize.base,
    color: theme.colors.gray500,
    textAlign: "center",
    lineHeight: 24,
  },
  listContent: {
    paddingHorizontal: 20,
    paddingVertical: 12,
  },
  notificationCard: {
    backgroundColor: theme.colors.white,
    borderRadius: theme.borderRadius.xl,
    padding: 16,
    marginBottom: 12,
    position: "relative",
    ...theme.shadows.subtle,
  },
  unread: {
    backgroundColor: "rgba(59, 130, 246, 0.05)",
    borderLeftWidth: 3,
    borderLeftColor: theme.colors.primary,
  },
  notificationContent: {
    flexDirection: "row",
    alignItems: "flex-start",
  },
  iconCircle: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  textContent: {
    flex: 1,
    marginRight: 8,
  },
  notificationTitle: {
    fontSize: theme.typography.fontSize.base,
    fontWeight: theme.typography.fontWeight.semibold,
    color: theme.colors.gray700,
    marginBottom: 4,
  },
  notificationTitleUnread: {
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.gray900,
  },
  notificationMessage: {
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.gray600,
    lineHeight: 20,
    marginBottom: 6,
  },
  notificationTime: {
    fontSize: theme.typography.fontSize.xs,
    color: theme.colors.gray400,
  },
  deleteButton: {
    padding: 4,
  },
  unreadDot: {
    position: "absolute",
    top: 16,
    right: 16,
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: theme.colors.primary,
  },
});
