import React, { useEffect } from "react";
import {
  View,
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import widthUtils from "../utils/widthUtils";
import fontSize from "../utils/fontsizeUtils";
import CloseIcon from "../components/CloseIcon";
import {
  ProductDetailParams,
  ProductGroupList,
  SkuAttribute,
} from "../services/api/productApi";
import { useState } from "react";
interface ProductCardProps {
  onClose: () => void;
  product: ProductDetailParams;
  groupList: ProductGroupList[];
}

const ProductCard: React.FC<ProductCardProps> = ({
  onClose,
  product: localProduct,
  groupList: localGroupList,
}: {
  onClose: () => void;
  product: ProductDetailParams;
  groupList: ProductGroupList[];
}) => {
  const [groupList, setGroupList] =
    useState<ProductGroupList[]>(localGroupList);
  const [product, setProduct] = useState<ProductDetailParams>(localProduct);
  const [imgTitle, setImgTitle] = useState<string>("");

  useEffect(() => {
    const item = groupList.filter((item) => item.has_image);
    item.forEach((item) => {
      const colorItem = item.attributes.filter(
        (attribute) => attribute.has_color
      );
      if (colorItem.length > 0) {
        setImgTitle(colorItem[0].sku_image_url);
      }
    });
    if (item.length === 0) {
      setImgTitle(product.product_image_urls[0]);
    }
    
    if(item.length === 1){
        console.log(item);
        
    }
    

  });
  const handleColorSelect = (colorId: string, index: number) => {
    const newGroupList = [...groupList];
    const attributeIndex = newGroupList[index]?.attributes.findIndex(
      (item) => item.value === colorId
    );
    if (attributeIndex !== -1) {
      newGroupList[index].attributes = newGroupList[index].attributes.map(
        (item, i) => {
          if (i === attributeIndex) {
            return { ...item, has_color: true };
          }
          return { ...item, has_color: false };
        }
      );
      setGroupList(newGroupList);
    }

    const selectedSku: SkuAttribute[] = [];
    groupList.forEach((item) => {
      item.attributes.forEach((attribute) => {
        if (attribute.has_color) {
          selectedSku.push(attribute);
        }
      });
    });

    let price = 0;
    product?.skus.forEach((item) => {
      const values1 = item.attributes.map((item) => item.value).sort();
      const values2 = selectedSku.map((item) => item.value).sort();

      if (values1.every((val, index) => val === values2[index])) {
        if (item.offer_price) {
          price = item.offer_price;
        } else {
          price =
            product.sale_info.price_range_list[
              product.sale_info.price_range_list.length - 1
            ].price;
        }
      }
    });
    if (product) {
      setProduct({
        ...product,
        price: price === 0 ? "无货" : price,
      });
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.productCardContainer3}>
        <View style={styles.pricingCard}>
          <View style={styles.flexRowAlignedEndFullWidth}>
            <View style={styles.productCardContainer}>
              <View style={styles.cardContainer}>
                <View style={styles.flexColumnEndAlign2}>
                  <Image
                    source={{ uri: imgTitle }}
                    style={styles.flexColumnImg}
                  />
                  {/* SVG commented out as requested */}
                  {/* <View style={styles.svgContainer}>
                    <svg viewBox="0 0 24 24" x="0" y="0" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <g id="look" xmlns="http://www.w3.org/2000/svg">
                        <path id="Rectangle 653" d="M1,1h17c2.7614,0 5,2.239 5,5v17h-17c-2.7614,0 -5,-2.239 -5,-5z" fill="#5B5B5B" fill-opacity="0.7" />
                        <path id="Vector 12" d="M12,6h6v6" stroke="white" stroke-linecap="round" stroke-linejoin="round" />
                        <path id="Vector 13" d="M12,18h-6v-6" stroke="white" stroke-linecap="round" stroke-linejoin="round" />
                      </g>
                    </svg>
                  </View> */}
                </View>
              </View>
            </View>
            <View style={styles.productCardContainer2}>
              <View style={styles.productCardContainer1}>
                <View style={styles.priceInfoContainer1}>
                  <Text style={styles.highlightedText}>{product.price}</Text>
                  <View style={styles.priceInfoContainer2}>
                    <Text style={styles.orangeHeading}>FCFA</Text>
                    <View style={styles.percentageChangeContainer}>
                      <Text style={styles.discountPercentageTextStyle}>
                        -5%
                      </Text>
                      {/* SVG commented out as requested */}
                      {/* <View style={styles.svgContainer1}>
                        <svg viewBox="0 0 32 32" x="0" y="0" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <defs>
                            <linearGradient id="paint5_linear_128_1116" x1="7.443999999999988" y1="7.443999999999988" x2="12.580000000000013" y2="29.312000000000012" gradientUnits="userSpaceOnUse" xmlns="http://www.w3.org/2000/svg">
                              <stop stop-color="#FFE5AD" />
                              <stop offset="1" stop-color="#F9AE46" />
                            </linearGradient>
                            <linearGradient id="paint6_linear_128_1116" x1="16" y1="2" x2="16" y2="30" gradientUnits="userSpaceOnUse" xmlns="http://www.w3.org/2000/svg">
                              <stop stop-color="white" />
                              <stop offset="1" stop-color="#FFD180" />
                            </linearGradient>
                          </defs>
                          <path id="Star 1_2" d="M14.621,3.313c0.772,-0.735 1.986,-0.735 2.758,0l1.401,1.334c0.439,0.418 1.043,0.615 1.644,0.534l1.917,-0.255c1.057,-0.141 2.039,0.572 2.232,1.621l0.349,1.903c0.109,0.596 0.483,1.11 1.016,1.398l1.701,0.92c0.939,0.507 1.314,1.661 0.853,2.623l-0.836,1.745c-0.262,0.546 -0.262,1.182 0,1.728l0.836,1.745c0.461,0.962 0.086,2.116 -0.853,2.623l-1.701,0.92c-0.533,0.288 -0.907,0.802 -1.016,1.398l-0.349,1.903c-0.193,1.049 -1.175,1.762 -2.232,1.621l-1.917,-0.255c-0.601,-0.081 -1.205,0.116 -1.644,0.534l-1.401,1.334c-0.772,0.735 -1.986,0.735 -2.758,0l-1.401,-1.334c-0.439,-0.418 -1.043,-0.615 -1.644,-0.534l-1.917,0.255c-1.057,0.141 -2.039,-0.572 -2.232,-1.621l-0.349,-1.903c-0.109,-0.596 -0.483,-1.11 -1.016,-1.398l-1.701,-0.92c-0.939,-0.507 -1.314,-1.661 -0.853,-2.623l0.836,-1.745c0.262,-0.546 0.262,-1.182 0,-1.728l-0.836,-1.745c-0.461,-0.962 -0.086,-2.116 0.853,-2.623l1.701,-0.92c0.533,-0.288 0.907,-0.802 1.016,-1.398l0.349,-1.903c0.193,-1.049 1.175,-1.762 2.232,-1.621l1.917,0.255c0.601,0.081 1.205,-0.116 1.644,-0.534z" fill="url(#paint5_linear_128_1116)" stroke="url(#paint6_linear_128_1116)" xmlns="http://www.w3.org/2000/svg" />
                        </svg>
                      </View> */}
                    </View>
                  </View>
                </View>
                <View style={styles.vipButtonContainer}>
                  <View style={styles.vipButton}>
                    <Text style={styles.italicBoldSegoeVip}>VIP</Text>
                  </View>
                </View>
              </View>
              <View style={styles.pricingCardContainer}>
                <View style={styles.pricingCard}>
                  <View style={styles.priceInfoContainer}>
                    <Text style={styles.priceHighlightedText}>3072</Text>
                    <Text style={styles.priceTagBold}>FCFA</Text>
                  </View>
                  <Text style={styles.productPriceTier}>≥2 Pièces</Text>
                </View>
                <View style={styles.pricingCard}>
                  <View style={styles.priceInfoContainer}>
                    <Text style={styles.priceHighlightedText}>2500</Text>
                    <Text style={styles.priceTagBold}>FCFA</Text>
                  </View>
                  <Text style={styles.productPriceTier}>≥50 Pièces</Text>
                </View>
                <View style={styles.pricingCard}>
                  <View style={styles.priceInfoContainer}>
                    <Text style={styles.priceHighlightedText}>2099</Text>
                    <Text style={styles.priceTagBold}>FCFA</Text>
                  </View>
                  <Text style={styles.productPriceTier}>≥100 Pièces</Text>
                </View>
              </View>
            </View>
          </View>
          <View style={styles.productDetailsContainer}>
            {groupList.map((item, index1) => (
              <React.Fragment key={item.attribute_name + index1}>
                {item.has_image && groupList.length > 1 && (
                  <View>
                    <Text style={styles.primaryTextHeading}>Couleur：Noir</Text>
                    <ScrollView
                      horizontal
                      showsHorizontalScrollIndicator={false}
                      key={item.attribute_name + index1}
                    >
                      <View
                        style={{ flexDirection: "row", gap: 12, width: "100%" }}
                      >
                        {item.attributes.map((attribute, index) => (
                          <TouchableOpacity
                            key={attribute.value + index}
                            onPress={() =>
                              handleColorSelect(attribute.value, index1)
                            }
                          >
                            <View
                              style={[
                                styles.colorPaletteContainer1,
                                attribute.has_color &&
                                  styles.selectedColorImageContainer,
                              ]}
                            >
                              <View
                                key={attribute.value}
                                style={styles.cardContainerWithTitle}
                              >
                                <View style={styles.cardContainerWithImage}>
                                  <Image
                                    source={{ uri: attribute.sku_image_url }}
                                    style={styles.imageContainer}
                                  />
                                </View>
                                <Text style={styles.profileCard}>
                                  {attribute.value}
                                </Text>
                              </View>
                            </View>
                          </TouchableOpacity>
                        ))}
                      </View>
                    </ScrollView>
                  </View>
                )}
                {!item.has_image && (
                  <View style={styles.productStockInfoContainer}>
                    <Text style={styles.primaryTextHeading}>Taille</Text>
                    <ScrollView showsVerticalScrollIndicator={false}>
                      {item.attributes.map((attribute) => (
                        <View
                          style={styles.productStockDisplayWidget}
                          key={attribute.value + index1}
                        >
                          <View style={styles.stockAvailabilityDisplayWidget}>
                            <View
                              style={[
                                styles.stockInfoDisplayContainer,
                                styles.stockAvailabilityDisplay,
                              ]}
                            >
                              <View style={styles.pricingCard}>
                                <Text
                                  style={[
                                    styles.stockAvailabilityInfoStyle,
                                    { fontWeight: "400" },
                                  ]}
                                >
                                  {attribute.value}
                                </Text>
                                <Text style={styles.stockStatusInfoTextStyle}>
                                  En stock 231
                                </Text>
                              </View>
                              <View style={styles.stockInfoContainer}>
                                <View
                                  style={styles.stockCountDisplayStyleContainer}
                                ></View>
                                <Text
                                  style={
                                    styles.stockCountDisplayStyleContainer1
                                  }
                                >
                                  0
                                </Text>
                                <Text
                                  style={{ fontSize: 16, fontWeight: "400" }}
                                >
                                  +
                                </Text>
                              </View>
                            </View>
                          </View>
                        </View>
                      ))}
                    </ScrollView>
                  </View>
                )}
                {item.has_image && groupList.length === 1 && (
                  <View style={{ flex: 1, height: "100%" }}>
                    <ScrollView style={{ flex: 1 }}>
                      {item.attributes.map((attribute, index) => (
                        <View
                          key={attribute.value + index1}
                          style={{
                            flexDirection: "row",
                            alignItems: "center",
                            justifyContent: "space-between",
                            marginBottom: 10,
                          }}
                        >
                          <View style={{ width: 50, height: 50 }}>
                            <Image
                              source={{ uri: attribute.sku_image_url }}
                              style={{
                                width: "100%",
                                height: "100%",
                                borderRadius: 5,
                              }}
                            />
                          </View>
                          <View style={{width:widthUtils(200,200).width}}>
                            <Text 
                              style={{textAlign:'left',alignSelf:'center',width:'100%'}}
                              numberOfLines={1}
                              ellipsizeMode="tail"
                            >
                              {attribute.value}
                            </Text>
                          </View>
                          <View style={styles.stockInfoContainer}>
                            <View
                              style={styles.stockCountDisplayStyleContainer}
                            ></View>
                            <Text
                              style={styles.stockCountDisplayStyleContainer1}
                            >
                              0
                            </Text>
                            <Text style={{ fontSize: 16, fontWeight: "400" }}>
                              +
                            </Text>
                          </View>
                        </View>
                      ))}
                    </ScrollView>
                  </View>
                )}
              </React.Fragment>
            ))}
          </View>
        </View>
      </View>
      <View style={styles.closeIconContainer}>
        <TouchableOpacity onPress={onClose}>
          <CloseIcon size={18} />
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: "100%",
    backgroundColor: "white",
  },
  productCardContainer3: {
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "flex-start",
    width: "100%",
    paddingTop: 15,
    paddingRight: 17,
    paddingLeft: 19,
  },
  pricingCard: {
    paddingTop: 5,
    paddingBottom: 5,
  },
  flexRowAlignedEndFullWidth: {
    flexDirection: "row",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    width: "100%",
  },
  productCardContainer: {
    flexBasis: widthUtils(80, 80).width,
    paddingTop: 5,
  },
  cardContainer: {
    width: "100%",
    backgroundColor: "#e0e0e0",
    borderRadius: 5,
  },
  flexColumnEndAlign2: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    width: "100%",
    height: widthUtils(80, 80).height,
    borderRadius: 5,
  },
  flexColumnImg: {
    width: "100%",
    height: "100%",
    borderRadius: 5,
  },
  svgContainer: {
    width: widthUtils(24, 24).width,
    height: widthUtils(24, 24).height,
  },
  productCardContainer2: {
    flexBasis: widthUtils(295, 295).width,
    marginLeft: 15,
  },
  productCardContainer1: {
    flexDirection: "row",
    alignItems: "flex-end",
    justifyContent: "flex-start",
  },
  priceInfoContainer1: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-start",
  },
  highlightedText: {
    padding: 0,
    margin: 0,
    fontWeight: "700",
    fontSize: fontSize(30),
    fontFamily: "Segoe UI",
    color: "#ff5100",
  },
  priceInfoContainer2: {
    flexDirection: "row",
    alignItems: "flex-start",
    justifyContent: "flex-start",
    marginLeft: 1,
  },
  orangeHeading: {
    padding: 0,
    paddingBottom: 14,
    margin: 0,
    fontWeight: "700",
    fontSize: 14,
    fontFamily: "Segoe UI",
    color: "#ff5100",
  },
  percentageChangeContainer: {
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "flex-start",
    marginLeft: 14.5,
  },
  discountPercentageTextStyle: {
    padding: 0,
    margin: 0,
    fontStyle: "italic",
    fontWeight: "900",
    fontSize: 11,
    fontFamily: "Segoe UI",
    color: "#4e2000",
  },
  svgContainer1: {
    width: 32,
    height: 32,
    marginTop: -26,
  },
  vipButtonContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-start",
    marginLeft: 1.25,
  },
  svgContainer2: {
    width: 10,
    height: 10,
    color: "#3b3b3b",
  },
  vipButton: {
    width: 55,
    minWidth: 55,
    height: 21,
    marginLeft: -2.5,
    backgroundColor: "#3b3b3b",
    borderWidth: 0,
    borderRadius: 5,
    borderBottomLeftRadius: 0,
  },
  italicBoldSegoeVip: {
    fontStyle: "italic",
    fontWeight: "900",
    fontSize: 14,
    fontFamily: "Segoe UI",
  },
  royalBadge: {
    fontStyle: "italic",
    fontWeight: "900",
    fontSize: fontSize(14),
    fontFamily: "Segoe UI",
    letterSpacing: -2,
  },
  pricingCardContainer: {
    flexDirection: "row",
    gap: widthUtils(29.5, 29.5).width,
    alignItems: "flex-start",
    justifyContent: "space-between",
    width: "100%",
    paddingRight: 15,
    paddingBottom: 3,
    paddingLeft: 11,
    marginTop: 7,
    backgroundColor: "#f3f4f8",
    borderRadius: 5,
  },
  priceInfoContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-start",
  },
  priceHighlightedText: {
    padding: 0,
    margin: 0,
    fontWeight: "700",
    fontSize: fontSize(16),
    fontFamily: "Segoe UI",
    color: "#373737",
  },
  priceTagBold: {
    padding: 0,
    margin: 0,
    fontWeight: "700",
    fontSize: fontSize(11),
    fontFamily: "Segoe UI",
    color: "#373737",
  },
  productPriceTier: {
    padding: 0,
    margin: 0,
    marginTop: -4,
    fontWeight: "400",
    fontSize: fontSize(12),
    fontFamily: "PingFang SC",
    color: "#373737",
  },
  productDetailsContainer: {
    width: "100%",
    marginTop: 24,
    height: "100%",
  },
  primaryTextHeading: {
    padding: 0,
    margin: 0,
    fontWeight: "600",
    fontSize: 16,
    lineHeight: 20,
    fontFamily: "Segoe UI",
    color: "black",
  },
  colorPaletteContainer1: {
    marginTop: 12,
  },
  colorPaletteContainer: {
    flexDirection: "row",
    gap: 10,
    alignItems: "flex-start",
    justifyContent: "flex-start",
    width: "100%",
  },
  cardContainerWithTitleAndIcon: {
    flex: 1,
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "flex-start",
    paddingBottom: 5,
    backgroundColor: "#fff5f0",
    borderWidth: 1,
    borderColor: "#ff5100",
    borderRadius: 5,
  },
  cardContainer1: {
    backgroundColor: "#e0e0e0",
    borderRadius: 5,
  },
  flexColumnEndAlign: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    width: "100%",
    height: 90,
    borderRadius: 5,
  },
  uniqueTextStyler: {
    alignSelf: "center",
    padding: 0,
    margin: 0,
    marginTop: 1,
    fontWeight: "600",
    fontSize: 16,
    lineHeight: 20,
    fontFamily: "Segoe UI",
    color: "#ff5100",
  },
  cardContainer2: {
    flex: 1,
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "flex-start",
    paddingBottom: 5,
    backgroundColor: "#f4f4f4",
    borderRadius: 5,
    width: 90,
    height: 116,
  },
  flexColumnEndAlign1: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    width: "100%",
    height: 90,
    borderRadius: 5,
  },
  profileCard: {
    alignSelf: "center",
    padding: 0,
    margin: 0,
    marginTop: 1,
    fontWeight: "400",
    fontFamily: "Segoe UI",
    color: "black",
    height: 26,
    textAlign: "center",
    width: 90,
    fontSize: fontSize(18),
  },
  beigeContainer: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    height: 90,
    backgroundColor: "#e0e0e0",
    borderRadius: 5,
  },
  colorPaletteWidget: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "flex-start",
    height: 90,
    borderRadius: 5,
  },
  cardContainerWithTitle: {
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "flex-start",
    width: 90,
    height: 116,
    paddingBottom: 5,
    backgroundColor: "#f4f4f4",
    borderRadius: 5,
  },
  cardContainerWithImage: {
    flexDirection: "row",
    alignItems: "flex-start",
    justifyContent: "flex-start",
    borderRadius: 5,
    width: 90,
    height: 90,
  },
  imageContainer: {
    width: "100%",
    height: "100%",
    borderWidth: 0,
    resizeMode: "cover",
  },
  svgContainer3: {
    width: "100%",
    height: "100%",
  },
  productStockInfoContainer: {
    marginTop: 24,
  },
  productStockDisplayWidget: {
    width: "100%",
    marginTop: 8,
  },
  stockAvailabilityDisplayWidget: {
    width: "100%",
  },
  stockInfoDisplayContainer: {
    flexDirection: "row",
    gap: 8,
    alignItems: "center",
    justifyContent: "space-between",
    width: "100%",
  },
  stockAvailabilityDisplay: {
    marginTop: 10,
  },
  stockAvailabilityInfoStyle: {
    padding: 0,
    margin: 0,
    fontSize: 16,
    lineHeight: 20,
    fontFamily: "Segoe UI",
    color: "black",
  },
  stockStatusInfoTextStyle: {
    padding: 0,
    margin: 0,
    fontWeight: "400",
    fontSize: 12,
    fontFamily: "Segoe UI",
    color: "#7c7c7c",
  },
  stockInfoContainer: {
    flexDirection: "row",
    gap: 7.5,
    alignItems: "center",
    justifyContent: "flex-start",
  },
  stockCountDisplayStyleContainer: {
    width: 9,
    borderTopWidth: 1,
    borderTopColor: "black",
  },
  stockCountDisplayStyleContainer1: {
    alignItems: "center",
    justifyContent: "center",
    height: 24,
    paddingHorizontal: 15,
    fontWeight: "400",
    fontSize: 14,
    fontFamily: "Segoe UI",
    color: "black",
    backgroundColor: "#f4f4f4",
    borderWidth: 0,
    borderRadius: 5,
  },
  svgContainer4: {
    width: 8,
    height: 8,
  },
  verticalFlexContainer: {
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "flex-start",
    width: "100%",
    marginTop: 10,
  },
  numberTextContainer: {
    padding: 0,
    margin: 0,
    fontWeight: "400",
    fontSize: 16,
    lineHeight: 20,
    fontFamily: "Segoe UI",
    color: "black",
  },
  verticalAlignBottom: {
    flexDirection: "column",
    alignItems: "flex-end",
    justifyContent: "center",
    marginTop: -4,
  },
  verticalAlignContainer: {
    alignSelf: "flex-start",
    paddingRight: 33,
    paddingLeft: 322,
    marginTop: -4.5,
  },
  borderBoxedWidthBlackTopLine: {
    width: 9,
    borderTopWidth: 1,
    borderTopColor: "black",
  },
  closeIconContainer: {
    position: "absolute",
    top: 15,
    right: 15,
    zIndex: 1,
  },
  selectedColorImageContainer: {
    borderWidth: 1,
    borderColor: "#ff5217",
  },
});

export default ProductCard;
