import { Colors } from "@/constants/Colors";
import { getDateTimeScope, getRoomTypePermission } from "@/services/dimension";
import { useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    Dimensions,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const { width: SCREEN_WIDTH } = Dimensions.get("window");

export default function DimensionScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [showSection, setShowSection] = useState(false);
  const [startTime, setStartTime] = useState("");
  const [endTime, setEndTime] = useState("");
  const [wishSwitch, setWishSwitch] = useState(false);
  const [roomSwitch, setRoomSwitch] = useState(false);

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

  const loadConfig = async () => {
    try {
      const timeRes = await getDateTimeScope();
      if (timeRes && timeRes.startTime && timeRes.endTime) {
        setStartTime(timeRes.startTime.substring(0, 10));
        setEndTime(timeRes.endTime.substring(0, 10));
        setShowSection(true);
      }

      const permission = await getRoomTypePermission();
      setRoomSwitch(permission?.roomConfig !== 0);
      setWishSwitch(true);
    } catch (error) {
      console.error("加载次元配置失败:", error);
    }
  };

  const toRouter = (path: string) => {
    router.push(path as any); // Type assertion for dynamic routes
  };

  // Cyberpunk Card Component
  const CyberCard = ({ title, subtitle, color, onPress, children }: any) => (
    <TouchableOpacity
      style={[styles.card, { borderColor: color, shadowColor: color }]}
      activeOpacity={0.8}
      onPress={onPress}
    >
      <View style={[styles.cardHeader, { borderBottomColor: color }]}>
        <Text
          style={[styles.cardTitle, { color: color, textShadowColor: color }]}
        >
          {title}
        </Text>
        <View style={[styles.statusDot, { backgroundColor: color }]} />
      </View>
      <View style={styles.cardBody}>
        <Text style={styles.cardSubtitle}>{subtitle}</Text>
        {children}
      </View>
      {/* Decorative corners */}
      <View style={[styles.corner, styles.cornerTL, { borderColor: color }]} />
      <View style={[styles.corner, styles.cornerTR, { borderColor: color }]} />
      <View style={[styles.corner, styles.cornerBL, { borderColor: color }]} />
      <View style={[styles.corner, styles.cornerBR, { borderColor: color }]} />
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />

      {/* 顶部标题栏 */}
      <View style={[styles.header, { paddingTop: insets.top + 10 }]}>
        <View style={styles.headerContent}>
          <Text style={styles.headerTitle}>DIMENSION</Text>
          <Text style={styles.headerSubtitle}>次元领域 // ACCESS GRANTED</Text>
        </View>
        <View style={styles.headerLine} />
      </View>

      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        {showSection && (
          <View style={styles.grid}>
            {roomSwitch && (
              <CyberCard
                title="每日补给"
                subtitle="DAILY SUPPLY"
                color={Colors.neonBlue}
                onPress={() => toRouter("/dimension/room")}
              >
                <View style={styles.timeTag}>
                  <Text style={styles.timeText}>
                    OPEN: {startTime} - {endTime}
                  </Text>
                </View>
              </CyberCard>
            )}

            <CyberCard
              title="量子抓取"
              subtitle="QUANTUM CLAW"
              color={Colors.neonPink}
              onPress={() => toRouter("/dimension/catchDoll")}
            >
              <View style={styles.timeTag}>
                <Text style={styles.timeText}>
                  OPEN: {startTime} - {endTime}
                </Text>
              </View>
            </CyberCard>

            {wishSwitch && (
              <CyberCard
                title="命运节点"
                subtitle="FATE NODE"
                color="#FFD700" // Gold
                onPress={() => toRouter("/dimension/wish")}
              >
                <View style={styles.timeTag}>
                  <Text style={styles.timeText}>
                    OPEN: {startTime} - {endTime}
                  </Text>
                </View>
              </CyberCard>
            )}
          </View>
        )}

        <View style={styles.footerInfo}>
          <Text style={styles.footerText}>SYSTEM ONLINE</Text>
          <Text style={styles.footerText}>V.20.77</Text>
        </View>

        <View style={{ height: 100 }} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.darkBg,
  },
  header: {
    paddingHorizontal: 20,
    paddingBottom: 20,
    backgroundColor: Colors.darkBg,
    zIndex: 10,
  },
  headerContent: {
    marginBottom: 10,
  },
  headerTitle: {
    fontSize: 32,
    fontWeight: "bold",
    color: "#fff",
    fontStyle: "italic",
    letterSpacing: 2,
    textShadowColor: Colors.neonBlue,
    textShadowOffset: { width: 0, height: 0 },
    textShadowRadius: 10,
  },
  headerSubtitle: {
    fontSize: 12,
    color: Colors.neonBlue,
    marginTop: 5,
    letterSpacing: 1,
  },
  headerLine: {
    height: 2,
    backgroundColor: Colors.neonBlue,
    width: "60%",
    shadowColor: Colors.neonBlue,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 1,
    shadowRadius: 5,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  grid: {
    gap: 20,
  },
  // Card Styles
  card: {
    backgroundColor: Colors.darkCard,
    borderRadius: 4,
    borderWidth: 1,
    padding: 1, // Inner spacing for border
    marginBottom: 20,
    minHeight: 120,
    position: "relative",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 10,
    elevation: 5,
  },
  cardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderBottomWidth: 1,
    backgroundColor: "rgba(255, 255, 255, 0.03)",
  },
  cardTitle: {
    fontSize: 20,
    fontWeight: "bold",
    textShadowRadius: 5,
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    shadowOpacity: 1,
    shadowRadius: 5,
  },
  cardBody: {
    padding: 15,
    justifyContent: "center",
  },
  cardSubtitle: {
    color: Colors.textSecondary,
    fontSize: 14,
    letterSpacing: 2,
    marginBottom: 10,
    fontWeight: "600",
  },
  timeTag: {
    backgroundColor: "rgba(0, 0, 0, 0.3)",
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 2,
    alignSelf: "flex-start",
    borderLeftWidth: 2,
    borderLeftColor: Colors.textTertiary,
  },
  timeText: {
    color: Colors.textTertiary,
    fontSize: 10,
    fontFamily: "Courier", // Monospace font if available
  },
  // Decoration Corners
  corner: {
    position: "absolute",
    width: 10,
    height: 10,
    borderWidth: 2,
  },
  cornerTL: { top: -1, left: -1, borderBottomWidth: 0, borderRightWidth: 0 },
  cornerTR: { top: -1, right: -1, borderBottomWidth: 0, borderLeftWidth: 0 },
  cornerBL: { bottom: -1, left: -1, borderTopWidth: 0, borderRightWidth: 0 },
  cornerBR: { bottom: -1, right: -1, borderTopWidth: 0, borderLeftWidth: 0 },

  footerInfo: {
    marginTop: 40,
    alignItems: "center",
    opacity: 0.5,
  },
  footerText: {
    color: Colors.textTertiary,
    fontSize: 10,
    letterSpacing: 2,
    marginBottom: 4,
  },
});
