import React, { useEffect, useState, useRef } from 'react';
import { View, Text, Image, TouchableOpacity, SafeAreaView, Dimensions, StyleSheet } from 'react-native';
import { Video, ResizeMode, AVPlaybackStatus } from 'expo-av';
import MapView, { Marker, Polyline } from 'react-native-maps';
import Svg, { Polyline as SvgPolyline, Circle as SvgCircle } from 'react-native-svg';
import { Trackpoint, MediaAttachment } from '@/types/workout.types';
import { useWorkoutStore } from '@/store/useWorkoutStore';
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams } from 'expo-router';

export default function ReplayScreen() {
  const { id } = useLocalSearchParams();
  const [points, setPoints] = useState<Trackpoint[]>([]);
  const [media, setMedia] = useState<MediaAttachment[]>([]);
  const [currentIdx, setCurrentIdx] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [activeMedia, setActiveMedia] = useState<MediaAttachment | null>(null);
  
  // Video playback progress (0 to 1) to animate the mini tracklog indicator
  const [videoProgress, setVideoProgress] = useState(0);
  const [mediaCountdown, setMediaCountdown] = useState(6);

  const mapRef = useRef<MapView | null>(null);
  const videoRef = useRef<Video | null>(null);
  const timerRef = useRef<any>(null);

  useEffect(() => {
    // Tải dữ liệu mẫu từ workout đang ghi nhận
    const activeRoute = useWorkoutStore.getState().routePoints;
    const activeMedia = useWorkoutStore.getState().mediaAttachments;
    setPoints(activeRoute);
    setMedia(activeMedia);
  }, [id]);

  useEffect(() => {
    if (isPlaying && !activeMedia) {
      timerRef.current = setInterval(() => {
        setCurrentIdx((prev) => {
          const next = prev + 1;
          if (next >= points.length) {
            setIsPlaying(false);
            clearInterval(timerRef.current);
            return prev;
          }
          
          const curPt = points[next];
          mapRef.current?.animateToRegion({
            latitude: curPt.lat,
            longitude: curPt.lng,
            latitudeDelta: 0.005,
            longitudeDelta: 0.005
          }, 300);

          const attachedMedia = media.find(m => Math.abs(m.lat - curPt.lat) < 0.0001);
          if (attachedMedia) {
            triggerMediaReplay(attachedMedia);
          }

          return next;
        });
      }, 300);
    } else {
      clearInterval(timerRef.current);
    }
    return () => clearInterval(timerRef.current);
  }, [isPlaying, activeMedia, points]);

  const triggerMediaReplay = (item: MediaAttachment) => {
    setActiveMedia(item);
    setIsPlaying(false);
    setVideoProgress(0);
    
    if (item.type === 'IMAGE') {
      setMediaCountdown(6);
      const counter = setInterval(() => {
        setMediaCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(counter);
            closeMediaShow();
          }
          return prev - 1;
        });
      }, 1000);
    }
  };

  const closeMediaShow = () => {
    setActiveMedia(null);
    setIsPlaying(true);
  };

  const handleVideoPlaybackUpdate = (status: AVPlaybackStatus) => {
    if (!status.isLoaded) return;
    if (status.durationMillis && status.positionMillis) {
      setVideoProgress(status.positionMillis / status.durationMillis);
    }
    if (status.didJustFinish) {
      closeMediaShow();
    }
  };

  // Helper chuyển đổi hệ tọa độ điểm thực sang khung vẽ phẳng SVG của Mini Tracklog
  const getSvgCoordinates = () => {
    if (points.length === 0) return { pointsStr: '', activePt: { x: 40, y: 40 } };
    
    const lats = points.map(p => p.lat);
    const lngs = points.map(p => p.lng);
    const minLat = Math.min(...lats);
    const maxLat = Math.max(...lats);
    const minLng = Math.min(...lngs);
    const maxLng = Math.max(...lngs);

    const latRange = maxLat - minLat || 0.0001;
    const lngRange = maxLng - minLng || 0.0001;

    const width = 80;
    const height = 80;
    const padding = 8;

    const scaleX = (width - padding * 2) / lngRange;
    const scaleY = (height - padding * 2) / latRange;
    const scale = Math.min(scaleX, scaleY);

    const offsetX = (width - lngRange * scale) / 2;
    const offsetY = (height - latRange * scale) / 2;

    const mappedStr = points.map(p => {
      const x = offsetX + (p.lng - minLng) * scale;
      const y = height - (offsetY + (p.lat - minLat) * scale);
      return `${x.toFixed(1)},${y.toFixed(1)}`;
    }).join(' ');

    // Tìm tọa độ chấm xanh động dựa trên tiến độ video
    const startWindowIdx = Math.max(0, currentIdx - 4);
    const endWindowIdx = Math.min(points.length - 1, currentIdx + 4);
    const localRange = endWindowIdx - startWindowIdx;
    const targetFloatIdx = startWindowIdx + (localRange * videoProgress);
    const baseIdx = Math.floor(targetFloatIdx);
    const fraction = targetFloatIdx - baseIdx;

    let activeLat = points[currentIdx]?.lat || 16.0684;
    let activeLng = points[currentIdx]?.lng || 108.2460;

    if (baseIdx < points.length - 1) {
      const pA = points[baseIdx];
      const pB = points[baseIdx + 1];
      activeLat = pA.lat + (pB.lat - pA.lat) * fraction;
      activeLng = pA.lng + (pB.lng - pA.lng) * fraction;
    }

    const activeX = offsetX + (activeLng - minLng) * scale;
    const activeY = height - (offsetY + (activeLat - minLat) * scale);

    return { pointsStr: mappedStr, activePt: { x: activeX, y: activeY } };
  };

  const { pointsStr, activePt } = getSvgCoordinates();

  return (
    <View className="flex-1 bg-[#050811]">
      <MapView
        ref={mapRef}
        className="flex-1"
        initialRegion={{
          latitude: points[0]?.lat || 16.0684,
          longitude: points[0]?.lng || 108.2460,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        }}
      >
        {points.length > 0 && (
          <Polyline coordinates={points.map(p => ({ latitude: p.lat, longitude: p.lng }))} strokeColor="#4f46e5" strokeWidth={6} />
        )}
        
        {points[currentIdx] && (
          <Marker coordinate={{ latitude: points[currentIdx].lat, longitude: points[currentIdx].lng }}>
            <View className="w-8 h-8 rounded-full bg-indigo-500 border-2 border-white items-center justify-center shadow-lg">
              <Ionicons name="bicycle-outline" size={16} color="white" />
            </View>
          </Marker>
        )}
      </MapView>

      {/* REPLAY CONTROLLER HUD */}
      <SafeAreaView className="absolute top-20 left-4 right-4 z-10 bg-slate-950/95 border border-slate-800/80 rounded-2xl p-4">
        <View className="flex-row justify-between items-center mb-3">
          <Text className="text-[10px] font-extrabold text-slate-400 uppercase tracking-widest">Hành trình đang tái hiện</Text>
          <TouchableOpacity onPress={() => setIsPlaying(!isPlaying)} className="bg-indigo-600 px-4 py-2 rounded-xl">
            <Text className="text-[11px] font-black text-white">{isPlaying ? 'TẠM DỪNG' : 'TIẾP TỤC'}</Text>
          </TouchableOpacity>
        </View>
        <View className="w-full bg-slate-800 h-1 rounded-full overflow-hidden">
          <View style={{ width: `${(currentIdx / (points.length || 1)) * 100}%` }} className="bg-indigo-500 h-full" />
        </View>
      </SafeAreaView>

      {/* FULLSCREEN POPUP HIỂN THỊ ĐA PHƯƠNG TIỆN CINEMATIC */}
      {activeMedia && (
        <View className="absolute inset-0 bg-slate-950/98 z-50 justify-between p-6">
          <View className="flex-row justify-between items-center">
            <View>
              <Text className="text-[9px] text-amber-400 font-extrabold uppercase">Địa danh dừng chân</Text>
              <Text className="text-sm font-bold text-white mt-1">{activeMedia.caption}</Text>
            </View>
            <TouchableOpacity onPress={closeMediaShow} className="bg-slate-900 border border-slate-800 px-4 py-2 rounded-xl">
              <Text className="text-xs text-white font-bold">Bỏ qua ({mediaCountdown}s)</Text>
            </TouchableOpacity>
          </View>

          {/* CHẤT LIỆU MEDIA HIỂN THỊ CHUYÊN SÂU */}
          <View className="flex-1 items-center justify-center my-4 relative">
            {activeMedia.type === 'IMAGE' ? (
              <View className="w-full relative rounded-2xl overflow-hidden border border-slate-800 bg-slate-900">
                <Image source={{ uri: activeMedia.uri }} className="w-full h-[50vh]" resizeMode="contain" />
                
                {/* LỚP PHỦ ẢNH HUD CHỮ VÀNG PHÁT SÁNG (GLOWING YELLOW TEXT OVERLAY) */}
                <View className="absolute bottom-4 left-4 right-4 bg-slate-950/90 border border-slate-800/80 p-3.5 rounded-xl shadow-2xl">
                  <Text style={styles.glowTextYellow} className="text-sm font-extrabold tracking-wide uppercase">
                    <Ionicons name="location" size={13} color="#facc15" /> {activeMedia.caption || "Mốc kỷ niệm"}
                  </Text>
                  <View className="flex-row justify-between items-center mt-2 pt-2 border-t border-yellow-500/15">
                    <Text style={styles.glowTextYellowSub} className="text-[9px] font-mono">
                      GPS: {activeMedia.lat.toFixed(5)}, {activeMedia.lng.toFixed(5)}
                    </Text>
                    <Text style={styles.glowTextYellowSub} className="text-[9px]">
                      {new Date().toLocaleString('vi-VN')}
                    </Text>
                  </View>
                </View>
              </View>
            ) : (
              <View className="w-full relative rounded-2xl overflow-hidden border border-slate-800 bg-slate-900">
                <Video
                  ref={videoRef}
                  source={{ uri: activeMedia.uri }}
                  resizeMode={ResizeMode.CONTAIN}
                  shouldPlay
                  useNativeControls
                  onPlaybackStatusUpdate={handleVideoPlaybackUpdate}
                  className="w-full h-[50vh]"
                />
                
                {/* LỚP PHỦ LỘ TRÌNH THU NHỎ TRÊN VIDEO (RED PATH & PULSING GREEN TRACKLOG DOT) */}
                <View className="absolute top-4 left-4 w-20 h-20 bg-slate-950/90 border border-slate-800/80 rounded-xl p-1 shadow-2xl items-center justify-center">
                  <Svg width="100%" height="100%" viewBox="0 0 80 80">
                    {/* Vẽ đường đi toàn lộ trình bằng màu đỏ rực */}
                    <SvgPolyline
                      points={pointsStr}
                      fill="none"
                      stroke="#ef4444"
                      strokeWidth="3"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                    {/* Vòng tròn neon xanh lá cây nhấp nháy */}
                    <SvgCircle
                      cx={activePt.x}
                      cy={activePt.y}
                      r="7"
                      fill="rgba(16, 185, 129, 0.4)"
                    />
                    {/* Chấm định vị GPS trung tâm */}
                    <SvgCircle
                      cx={activePt.x}
                      cy={activePt.y}
                      r="3.5"
                      fill="#10b981"
                      stroke="#ffffff"
                      strokeWidth="1"
                    />
                  </Svg>
                </View>
              </View>
            )}
          </View>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  glowTextYellow: {
    color: '#facc15',
    fontWeight: '800',
    textShadowColor: 'rgba(250, 204, 21, 0.75)',
    textShadowOffset: { width: 0, height: 0 },
    textShadowRadius: 8,
  },
  glowTextYellowSub: {
    color: '#fef08a',
    fontWeight: '600',
    textShadowColor: 'rgba(250, 204, 21, 0.4)',
    textShadowOffset: { width: 0, height: 0 },
    textShadowRadius: 3,
  }
});
