import { View, Text, SafeAreaView, ScrollView, Image, TouchableOpacity, Dimensions } from "react-native";
import React, { useEffect, useState, useRef } from "react";
import { useLocalSearchParams, router } from "expo-router";
import icons from "@/constants/icons";
import { getCar } from "@/lib/database";
import { useGlobalContext } from '@/lib/globalProvider';
import Carousel, { ICarouselInstance } from 'react-native-reanimated-carousel';

const CarDetails = () => {
  const { id } = useLocalSearchParams();
  const [carData, setCarData] = useState<any>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const { user } = useGlobalContext();
  const width = Dimensions.get('window').width;
  const carouselRef = useRef<ICarouselInstance>(null);

  useEffect(() => {
    const fetchCar = async () => {
      try {
        const car = await getCar(id as string);
        setCarData(car);
      } catch (error) {
        console.error('Error fetching car:', error);
      }
    };

    fetchCar();
  }, [id]);

  if (!carData) return null;

  return (
    <SafeAreaView className="bg-white flex-1">
      <ScrollView 
        showsVerticalScrollIndicator={false}
        contentContainerClassName="pb-32"
      >
        {/* Header */}
        <View className="relative h-72">
          <Carousel
            ref={carouselRef}
            loop
            width={width}
            height={288}
            data={carData.images || []}
            scrollAnimationDuration={1000}
            onProgressChange={(_, absoluteProgress) => {
              setActiveIndex(Math.round(absoluteProgress));
            }}
            renderItem={({ item }) => (
              <Image 
                source={{ uri: item as string }} 
                className="w-full h-full"
                resizeMode="cover"
              />
            )}
          />
          
          {/* Navigation Arrows */}
          {carData.images?.length > 1 && (
            <>
              <TouchableOpacity 
                onPress={() => carouselRef.current?.scrollTo ({ index: activeIndex - 1 })}
                className="absolute left-4 top-1/2 -translate-y-1/2 bg-black/50 rounded-full p-2 z-10"
              >
                <Image 
                  source={icons.backArrow} 
                  className="w-6 h-6"
                  tintColor="white"
                />
              </TouchableOpacity>
              
              <TouchableOpacity 
                onPress={() => carouselRef.current?.scrollTo({ index: activeIndex + 1 })}
                className="absolute right-4 top-1/2 -translate-y-1/2 bg-black/50 rounded-full p-2 z-10"
              >
                <Image 
                  source={icons.backArrow} 
                  className="w-6 h-6 rotate-180"
                  tintColor="white"
                />
              </TouchableOpacity>
            </>
          )}

          {/* Back Button */}
          <TouchableOpacity 
            onPress={() => router.back()}
            className="absolute top-5 left-5 bg-white/90 p-2 rounded-full z-10"
          >
            <Image source={icons.backArrow} className="size-6" />
          </TouchableOpacity>

          {/* Favorite Button */}
          <TouchableOpacity 
            className="absolute top-5 right-5 bg-white/90 p-2 rounded-full z-10"
          >
            <Image source={icons.heart} className="size-6" />
          </TouchableOpacity>
        </View>

        {/* Content */}
        <View className="px-5 mt-5">
          {/* Title and Rating */}
          <View className="flex-row justify-between items-center">
            <Text className="text-2xl font-bold">{carData.title}</Text>
            <View className="flex-row items-center bg-white px-3 py-1.5 rounded-full border border-gray-200">
              <Image source={icons.star} className="size-4" />
              <Text className="ml-1">{carData.rating}</Text>
            </View>
          </View>

          {/* Location */}
          <View className="flex-row items-center mt-2">
            <Image source={icons.location} className="size-5" />
            <Text className="ml-2 text-gray-500">{carData.location}</Text>
          </View>

          {/* Price */}
          <Text className="text-2xl font-bold text-blue-500 mt-4">€{carData.price}</Text>

          {/* Details */}
          <View className="mt-6">
            <Text className="text-lg font-bold mb-3">Car Details</Text>
            <View className="flex-row flex-wrap gap-4">
              <View className="bg-gray-100 px-4 py-2 rounded-lg">
                <Text>{carData.year}</Text>
              </View>
              <View className="bg-gray-100 px-4 py-2 rounded-lg">
                <Text>{carData.fuelType}</Text>
              </View>
              <View className="bg-gray-100 px-4 py-2 rounded-lg">
                <Text>{carData.transmission}</Text>
              </View>
              <View className="bg-gray-100 px-4 py-2 rounded-lg">
                <Text>{carData.mileage} km</Text>
              </View>
            </View>
          </View>

          {/* Description */}
          <View className="mt-6">
            <Text className="text-lg font-bold mb-3">Description</Text>
            <Text className="text-gray-600 leading-5">
              {carData.description}
            </Text>
          </View>
        </View>
      </ScrollView>

      {/* Bottom Actions */}
      <View className="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-5 flex-row justify-between">
        <TouchableOpacity className="flex-1 mr-2 bg-white border border-blue-500 rounded-full py-3 items-center">
          <Text className="text-blue-500 font-semibold">Message</Text>
        </TouchableOpacity>
        <TouchableOpacity className="flex-1 ml-2 bg-blue-500 rounded-full py-3 items-center">
          <Text className="text-white font-semibold">Call</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default CarDetails;
