import {useNavigation} from '@react-navigation/native';
import React, {useRef, useState, useEffect} from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  SafeAreaView,
  ScrollView,
  FlatList,
  Image,
  Animated,
  Dimensions,
  TextInput,
} from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Ionicons from 'react-native-vector-icons/Ionicons';

const {width} = Dimensions.get('window');

const originalImages = [
  {id: '01', image: require('../../assets/images/banners/banner1.jpg')},
  {id: '02', image: require('../../assets/images/banners/banner2.jpg')},
  {id: '03', image: require('../../assets/images/banners/banner3.jpg')},
  {id: '04', image: require('../../assets/images/banners/banner4.jpg')},
  {id: '05', image: require('../../assets/images/banners/banner5.jpg')},
  {id: '06', image: require('../../assets/images/banners/banner6.jpg')},
  {id: '07', image: require('../../assets/images/banners/banner7.jpg')},
  {id: '08', image: require('../../assets/images/banners/banner8.jpg')},
  {id: '09', image: require('../../assets/images/banners/banner9.jpg')},
  {id: '10', image: require('../../assets/images/banners/banner10.jpg')},
];

const images = [
  originalImages[originalImages.length - 1],
  ...originalImages,
  originalImages[0],
];

const categories = [
  {
    id: '1',
    title: 'Paintings',
    image: require('../../assets/images/category/1.jpg'),
    description:
      'Original artworks from various periods and styles including oil, acrylic, and watercolor paintings. Explore masterpieces from Renaissance to Contemporary art, featuring landscapes, portraits, and abstract compositions by renowned and emerging artists.',
  },
  {
    id: '2',
    title: 'Post Cards',
    image: require('../../assets/images/category/2.jpg'),
    description:
      'Vintage and collectible postcards featuring historical scenes, artwork, and cultural memorabilia. Discover rare editions from the Golden Age of postcards (1890-1915), including travel souvenirs, holiday greetings, and advertising postcards with exquisite lithography.',
  },
  {
    id: '3',
    title: 'Collectibles',
    image: require('../../assets/images/category/3.jpg'),
    description:
      'Rare and unique collectible items including memorabilia, limited editions, and special artifacts. From sports memorabilia and pop culture items to historical curiosities and autographed collectibles - each piece tells a fascinating story.',
  },
  {
    id: '4',
    title: 'Sculptures',
    image: require('../../assets/images/category/4.jpg'),
    description:
      'Three-dimensional artworks crafted from various materials like marble, bronze, and wood. Browse figurative and abstract sculptures spanning classical antiquity to modern installations, including works by famous sculptors and emerging talents.',
  },
  {
    id: '5',
    title: 'Antiquities',
    image: require('../../assets/images/category/5.jpg'),
    description:
      'Ancient artifacts and historical objects from early civilizations and archaeological finds. Authentic pieces from Egyptian, Greek, Roman, Near Eastern, and other ancient cultures, including pottery, tools, jewelry, and religious artifacts with proper provenance.',
  },
  {
    id: '6',
    title: 'Textiles',
    image: require('../../assets/images/category/6.jpg'),
    description:
      'Historical and artistic fabrics including tapestries, embroideries, and traditional weavings. Explore exquisite textile arts from around the world - from medieval European tapestries to Asian silk embroideries and Pre-Columbian woven masterpieces.',
  },
  {
    id: '7',
    title: 'Photography',
    image: require('../../assets/images/category/7.jpg'),
    description:
      'Vintage and contemporary photographic works from renowned artists and historical collections. Includes early daguerreotypes, classic black-and-white prints, photojournalism, and modern conceptual photography, often with artist signatures or limited editions.',
  },
  {
    id: '8',
    title: 'Ceramics',
    image: require('../../assets/images/category/8.jpg'),
    description:
      'Artistic pottery and porcelain pieces ranging from ancient to modern studio ceramics. Discover Chinese porcelain, European majolica, Art Nouveau vases, Japanese raku ware, and contemporary ceramic art by leading studio potters.',
  },
  {
    id: '9',
    title: 'Jewelry',
    image: require('../../assets/images/category/9.jpg'),
    description:
      'Fine and antique jewelry pieces including rings, necklaces, and brooches from various eras. From Georgian mourning jewelry to Art Deco platinum pieces and modernist designs, each item reflects the craftsmanship and style of its period.',
  },
  {
    id: '10',
    title: 'Manuscripts',
    image: require('../../assets/images/category/10.jpg'),
    description:
      'Historical documents, handwritten letters, and rare literary manuscripts from important figures. Includes medieval illuminated manuscripts, author draft scientific notebook and correspondence offering intimate glimpses into history.',
  },
  {
    id: '11',
    title: 'Prints',
    image: require('../../assets/images/category/1.jpg'),
    description:
      'Limited edition prints including etchings, lithographs, and screenprints by notable artists. Collect works from Old Master prints to modern limited editions, with attention to printing techniques, paper quality, and authenticity certifications.',
  },
  {
    id: '12',
    title: 'Coins',
    image: require('../../assets/images/category/2.jpg'),
    description:
      'Numismatic collections featuring rare coins, medals, and currency from around the world. Includes ancient Greek and Roman coins, medieval currency, error coins, and modern commemorative issues, all graded for condition and rarity.',
  },
  {
    id: '13',
    title: 'Furniture',
    image: require('../../assets/images/category/3.jpg'),
    description:
      'Antique and designer furniture pieces representing different historical periods and styles. From Chippendale chairs to Eames loungers, each piece showcases the design evolution and craftsmanship techniques of its era, with proper restoration documentation.',
  },
  {
    id: '14',
    title: 'Glassware',
    image: require('../../assets/images/category/4.jpg'),
    description:
      'Artistic glass objects including stained glass, art glass, and historical glass vessels. Features Tiffany lamps, Murano glass sculptures, ancient Roman vessels, and studio glass art demonstrating various glassblowing and decorative techniques.',
  },
  {
    id: '15',
    title: 'Watches',
    image: require('../../assets/images/category/5.jpg'),
    description:
      'Luxury and vintage timepieces from prestigious brands and independent watchmakers. Collectible mechanical watches including rare Rolex models, Patek Philippe complications, military-issued watches, and avant-garde independent horology.',
  },
  {
    id: '16',
    title: 'Books',
    image: require('../../assets/images/category/6.jpg'),
    description:
      'Rare first editions, signed copies, and historically significant literary works. Includes incunabula (pre-1501 printed books), landmark scientific works, important literary firsts, and beautifully bound private press editions with provenance.',
  },
  {
    id: '17',
    title: 'Maps',
    image: require('../../assets/images/category/7.jpg'),
    description:
      'Antique maps and cartographic works showing historical geography and exploration. From Ptolemaic maps to 19th-century atlases, these documents reveal evolving worldviews, with rare examples of sea charts, celestial maps, and urban plans.',
  },
  {
    id: '18',
    title: 'Musical Instruments',
    image: require('../../assets/images/category/8.jpg'),
    description:
      'Vintage and collectible musical instruments with historical or artistic significance. Includes Stradivari-model violins, vintage guitars, historical keyboard instruments, and ethnomusicological artifacts, often with player provenance.',
  },
  {
    id: '19',
    title: 'Arms & Armor',
    image: require('../../assets/images/category/9.jpg'),
    description:
      'Historical weapons, armor, and military artifacts from different periods and cultures. Collectible pieces include samurai swords, medieval European armor, dueling pistols, and tribal weapons, all with expert authentication of age and origin.',
  },
  {
    id: '20',
    title: 'Natural History',
    image: require('../../assets/images/category/10.jpg'),
    description:
      'Scientific specimens including fossils, minerals, and taxidermy with historical importance. Features dinosaur fossils, gem-quality mineral specimens, antique anatomical models, and Victorian-era curiosity cabinets with proper CITES documentation where applicable.',
  },
];

const popularProducts = [
  {
    id: '1',
    title: 'Vintage Painting',
    image: require('../../assets/images/category/1.jpg'),
    description:
      'A 19th-century oil painting depicting a serene countryside landscape, with delicate brushstrokes capturing the golden hour light. Framed in an ornate gilded wood frame.',
  },
  {
    id: '2',
    title: 'Ancient Sculpture',
    image: require('../../assets/images/category/2.jpg'),
    description:
      'Roman marble statue from the 2nd century AD, representing a draped goddess. Recovered from an archaeological site near Naples, Italy.',
  },
  {
    id: '3',
    title: 'Handmade Jewelry',
    image: require('../../assets/images/category/3.jpg'),
    description:
      'Art Deco-inspired brooch crafted in 1920s Paris, featuring platinum, diamonds, and sapphires. Signed by renowned jeweler Georges Fouquet.',
  },
  {
    id: '4',
    title: 'Rare Postcard',
    image: require('../../assets/images/category/4.jpg'),
    description:
      'Limited-edition 1905 postcard of the Eiffel Tower, printed during the Exposition Universelle. One of only 50 known surviving copies.',
  },
  {
    id: '5',
    title: 'Antique Vase',
    image: require('../../assets/images/category/5.jpg'),
    description:
      'Ming Dynasty porcelain vase (circa 1500s) with cobalt-blue dragon motifs. A prime example of imperial kiln craftsmanship from the Jiajing period.',
  },
];

const SouvenirShop = () => {
  const navigation = useNavigation();
  const flatListRef = useRef(null);
  const scrollX = useRef(new Animated.Value(0)).current;
  const [activeIndex, setActiveIndex] = useState(1);
  const [currentTime, setCurrentTime] = useState(0);
  const [isAutoScrolling, setIsAutoScrolling] = useState(true);

  useEffect(() => {
    const listener = scrollX.addListener(({value}) => {
      const index = Math.round(value / width);
      setActiveIndex(index);
    });

    return () => {
      scrollX.removeListener(listener);
    };
  }, []);

  useEffect(() => {
    let interval;
    let startTime = Date.now();

    const updateTimer = () => {
      const elapsed = Date.now() - startTime;
      setCurrentTime(elapsed);

      if (elapsed >= 5000) {
        startTime = Date.now();
        setCurrentTime(0);
        let nextIndex = activeIndex + 1;
        if (nextIndex >= images.length) {
          nextIndex = 1;
        }
        flatListRef.current?.scrollToIndex({index: nextIndex, animated: true});
      }
    };

    if (isAutoScrolling) {
      interval = setInterval(updateTimer, 100);
    }

    return () => {
      clearInterval(interval);
    };
  }, [activeIndex, isAutoScrolling]);

  const handleMomentumScrollEnd = e => {
    const index = Math.round(e.nativeEvent.contentOffset.x / width);

    if (index === 0) {
      flatListRef.current.scrollToIndex({
        index: originalImages.length,
        animated: false,
      });
      setActiveIndex(originalImages.length);
    } else if (index === images.length - 1) {
      flatListRef.current.scrollToIndex({index: 1, animated: false});
      setActiveIndex(1);
    } else {
      setActiveIndex(index);
    }

    setCurrentTime(0);
    setIsAutoScrolling(true);
  };

  const handleTouchStart = () => setIsAutoScrolling(false);
  const handleTouchEnd = () => {
    setIsAutoScrolling(true);
    setCurrentTime(0);
  };

  const renderItem = ({item}) => (
    <Image source={item.image} style={styles.carouselImage} />
  );

  const renderProductItem = ({item}) => (
    <TouchableOpacity
      style={styles.productCard}
      onPress={() => navigation.navigate('CategoryDetails', {item})}>
      <Image source={item.image} style={styles.productImage} />
      <View style={styles.productInfo}>
        <Text style={styles.productTitle} numberOfLines={1}>
          {item.title}
        </Text>
      </View>
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <AntDesign name="arrowleft" size={28} color="#000" />
        </TouchableOpacity>

        <Text style={styles.headerTitle}>Souvenir Shop</Text>

        <TouchableOpacity>
          <Ionicons name="cart-outline" size={26} color="#000" />
        </TouchableOpacity>
      </View>

      <View style={styles.searchContainer}>
        <Ionicons
          name="search"
          size={18}
          color="#999"
          style={styles.searchIcon}
        />
        <TextInput
          placeholder="Search"
          placeholderTextColor="#999"
          style={styles.searchInput}
        />
      </View>

      <ScrollView>
        <View style={styles.carouselWrapper}>
          <Animated.FlatList
            ref={flatListRef}
            data={images}
            renderItem={renderItem}
            keyExtractor={(_, index) => index.toString()}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            onScroll={Animated.event(
              [{nativeEvent: {contentOffset: {x: scrollX}}}],
              {useNativeDriver: false},
            )}
            onMomentumScrollEnd={handleMomentumScrollEnd}
            initialScrollIndex={1}
            getItemLayout={(data, index) => ({
              length: width,
              offset: width * index,
              index,
            })}
            onTouchStart={handleTouchStart}
            onTouchEnd={handleTouchEnd}
            onScrollBeginDrag={handleTouchStart}
            onScrollEndDrag={handleTouchEnd}
          />

          <View style={styles.dotContainer}>
            {originalImages.map((_, i) => {
              const isActive = i === (activeIndex - 1) % originalImages.length;
              const progress = isActive ? currentTime / 5000 : 0;

              return (
                <View key={i} style={styles.dotWrapper}>
                  {isActive ? (
                    <View style={styles.dotTrack}>
                      <Animated.View
                        style={[styles.dotFill, {width: progress * 20}]}
                      />
                    </View>
                  ) : (
                    <View style={styles.inactiveDot} />
                  )}
                </View>
              );
            })}
          </View>
        </View>

        <View style={styles.categorySection}>
          <FlatList
            data={categories}
            keyExtractor={item => item.id}
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.categoryList}
            renderItem={({item}) => (
              <TouchableOpacity
                style={styles.categoryCard}
                onPress={() =>
                  navigation.navigate('CategoryList', {category: item})
                }>
                <Image source={item.image} style={styles.categoryImage} />
                <Text style={styles.categoryTitle}>{item.title}</Text>
              </TouchableOpacity>
            )}
          />
          <TouchableOpacity
            style={styles.viewAllBtn}
            onPress={() => navigation.navigate('ShopCategory')}>
            <Text style={styles.viewAllText}>View All Categories</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Most Popular Products</Text>
        </View>

        <FlatList
          data={popularProducts}
          renderItem={renderProductItem}
          keyExtractor={item => item.id}
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.productsList}
        />
      </ScrollView>
    </SafeAreaView>
  );
};

export default SouvenirShop;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: 15,
    paddingHorizontal: 15,
    paddingBottom: 8,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 16,
    marginTop: 10,
    marginBottom: 5,
    paddingHorizontal: 12,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#ddd',
    shadowColor: '#000',
    shadowOpacity: 0.05,
    shadowOffset: {width: 0, height: 1},
    shadowRadius: 2,
    elevation: 1,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 14,
    color: '#333',
  },
  carouselWrapper: {
    marginTop: 5,
    position: 'relative',
  },
  carouselImage: {
    width: width,
    height: 240,
    resizeMode: 'cover',
  },
  dotContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
    position: 'absolute',
    bottom: 10,
    width: '100%',
  },
  dotWrapper: {
    marginHorizontal: 4,
  },
  dotTrack: {
    width: 20,
    height: 4,
    backgroundColor: 'rgba(255,255,255,0.4)',
    borderRadius: 2,
    overflow: 'hidden',
  },
  dotFill: {
    height: 4,
    backgroundColor: '#000',
    borderRadius: 2,
  },
  inactiveDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: 'rgba(255,255,255,0.4)',
  },
  categorySection: {
    marginTop: 30,
    paddingHorizontal: 15,
  },
  categoryList: {
    paddingLeft: 10,
  },
  categoryCard: {
    alignItems: 'center',
    marginRight: 25,
    width: 90,
  },
  categoryImage: {
    width: 90,
    height: 90,
    borderRadius: 100,
    resizeMode: 'cover',
    marginBottom: 8,
    borderWidth: 1,
    borderColor: '#eee',
  },
  categoryTitle: {
    fontSize: 14,
    fontWeight: '500',
    color: '#333',
    textAlign: 'center',
  },
  viewAllBtn: {
    marginTop: 20,
    alignSelf: 'center',
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 5,
  },
  viewAllText: {
    fontSize: 14,
    fontWeight: '500',
    color: '#333',
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
    marginTop: 25,
    marginBottom: 25,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: '400',
    color: '#333',
  },
  productsList: {
    paddingLeft: 15,
    paddingBottom: 20,
  },
  productCard: {
    width: 180,
    marginRight: 15,
    backgroundColor: '#fff',
    borderRadius: 10,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  productImage: {
    width: '100%',
    height: 130,
    resizeMode: 'cover',
  },
  productInfo: {
    padding: 12,
  },
  productTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 3,
    alignSelf: 'center',
  },
});
