import { useState, useEffect } from "react";
import Grid from "@mui/material/Grid2";
import {
  Box,
  Button,
  TextField,
  InputAdornment,
  Typography,
  Card,
  CardContent,
  CardMedia,
} from "@mui/material";
import { useSelector } from "react-redux";

function doesSubstringExistInArray(array, substring) {
    
    if(array?.length == 0 || !array) return

    // Convert substring to lowercase for case-insensitive matching
    const lowerCaseSubstring = substring.toLowerCase();
    // Check each element in the array
    return array.some(element => element.toLowerCase().includes(lowerCaseSubstring));
}

const SearchProduct = ({ onClose }) => {
  const products = useSelector((state) => state.products.products.data);
  const [searchedProducts, setSearchedProducts] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");

  const filterProduct = function () {

    if(searchQuery?.length < 2) return

    let filteredProducts = products.filter((product) => {

      let title = product?.title?.toLowerCase();
      let search = searchQuery.toLowerCase();
      return title?.includes(search) || doesSubstringExistInArray(product?.tags, search);
    });

    setSearchedProducts(filteredProducts);
  };

  return (
    <Box
      className="animate__animated animate__fadeIn"
      sx={{
        position: "fixed",
        width: "100%",
        height: "100%",
        backgroundColor: "rgba(255,255,255,0.8)",
        top: 0,
        left: 0,
        py: 2,
        zIndex: 999,
        backdropFilter: "blur(10px)",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      {/* Search Box */}
      <Box
        sx={{
          backgroundColor: "rgba(0,0,0,0)",
          borderRadius: 2,
          padding: 2,
          width: "90%",
          marginBottom: 4,
        }}
      >
        <Grid container spacing={2}>
          <Grid size={12}>
            <TextField
              fullWidth
              placeholder="Search Products Name or Tags..."
              variant="outlined"
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                if (!searchQuery || searchQuery.trim() === "") {
                  setSearchedProducts([]);
                } else {
                  filterProduct();
                }
              }}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <Button
                      variant="contained"
                      color="primary"
                      sx={{ height: "100%" }}
                      onClick={onClose}
                    >
                      Cancel
                    </Button>
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
        </Grid>
      </Box>

      {/* Product List */}
      <Grid container sx={{ width: "100%", overflowY:"scroll" }} columns={12}>
        {searchedProducts.length > 0 ? (
          searchedProducts.map((product) => {

            return (
              <Grid
                className="animate__animated animate__fadeIn"
                item
                size={12}
              >
                <Card
                  key={product.id}
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    py: 2,
                    px: 2,
                    width: "100%",
                    cursor: "pointer",
                    backgroundColor: "rgba(255,255,255,0.2)",
                    boxShadow: "none",
                    borderBottom: "1px solid rgba(0,0,0,0.2)",
                    transition: "all 0.3s ease-in-out",
                    ":hover": {
                      backgroundColor: "#95AAC5",
                    },
                  }}
                  onClick={() => {
                    window.location.href = `/products/${product?.handle}`;
                  }}
                >
                  <CardMedia
                    component="img"
                    sx={{
                      width: 100,
                      height: 100,
                      borderRadius: 1,
                      marginRight: 2,
                    }}
                    image={product?.images[0]?.url}
                    alt={product?.title}
                  />
                  <CardContent>
                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: "100",
                        fontSize: {
                          xs: "0.875rem",
                          sm: "0.875rem",
                          md: "1.1rem",
                        },
                      }}
                    >
                      {`${product?.collections[0]?.title}`}
                    </Typography>
                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: "400",
                        fontSize: {
                          xs: "0.875rem",
                          sm: "0.875rem",
                          md: "1.1rem",
                        },
                      }}
                    >
                      {product?.title}
                    </Typography>
                    
                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: "400",
                        fontSize: {
                          xs: "0.875rem",
                          sm: "0.875rem",
                          md: "1.1rem",
                        },
                      }}
                    >
                      {"Tags: "} {product?.tags?.map((tag) => <span>{`${tag} | `}</span> )}
                    </Typography>

                    <Typography
                      variant="body2"
                      sx={{
                        fontWeight: "100",
                        fontSize: {
                          xs: "0.875rem",
                          sm: "0.875rem",
                          md: "1.1rem",
                        },
                      }}
                    >
                      {`${product?.minVariantPrice?.currencyCode} ${parseFloat(
                        product?.minVariantPrice?.amount
                      ).toFixed(2)}`}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
            );
          })
        ) : (
          <Typography variant="body1" color="text.secondary" sx={{px:2}}>
            No products found. Please search
          </Typography>
        )}
      </Grid>
    </Box>
  );
};

export default SearchProduct;
