import { FC, useState, useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Grid, Box, TextField, Autocomplete } from "@mui/material";
import { searchAllAction } from "@/app/_actions/search";
import { colors } from "@link-stack/ui";

type SearchResultProps = {
  props: any;
  option: any;
};

const SearchInput = (params: any) => (
  <TextField
    {...params}
    placeholder="Search"
    sx={{
      backgroundColor: "white",
      borderRadius: 10,
      "& .MuiOutlinedInput-root": {
        borderRadius: 10,
        py: 0,
        legend: {
          marginLeft: "30px",
        },
      },
      "& .MuiAutocomplete-inputRoot": {
        paddingLeft: "20px !important",
        borderRadius: 10,
      },
      "& .MuiInputLabel-outlined": {
        paddingLeft: "20px",
      },
      "& .MuiInputLabel-shrink": {
        marginLeft: "20px",
        paddingLeft: "10px",
        paddingRight: 0,
        background: "white",
      },
    }}
  />
);

const SearchResult: FC<SearchResultProps> = ({ props, option }) => {
  const { lightGrey, mediumGray, black, white } = colors;

  return (
    <Box
      {...props}
      sx={{
        px: 2,
        py: 1.25,
        ":hover": {
          background: `${lightGrey}`,
        },
        a: {
          color: `${black} !important`,
        },
        borderBottom: `1px solid ${mediumGray}`,
      }}
    >
      <Grid container direction="column" spacing={0.1}>
        <Grid item container direction="row" justifyContent="space-between">
          <Grid item>
            <Box
              sx={{
                py: 0,
                fontSize: 13,
                fontWeight: 500,
              }}
            >
              {option.title}
            </Box>
          </Grid>
        </Grid>
        <Grid item>
          <Box sx={{ width: "100%" }}>
            <Box
              sx={{
                color: "#999",
                fontSize: 13,
                wrap: "break-word",
              }}
            >
              {option.note}
            </Box>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export const SearchBox: FC = () => {
  const [open, setOpen] = useState(false);
  const [searchResults, setSearchResults] = useState([]);
  const [selectedValue, setSelectedValue] = useState(null);
  const [searchTerms, setSearchTerms] = useState("");
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    const fetchSearchResults = async () => {
      const results = await searchAllAction(searchTerms ?? "", 50);
      setSearchResults(results);
    };

    fetchSearchResults();
  }, [searchTerms]);

  return (
    <Autocomplete
      forcePopupIcon={false}
      openOnFocus
      blurOnSelect
      value={selectedValue}
      onBlur={() => setOpen(false)}
      inputValue={searchTerms}
      onChange={(_event, option, reason) => {
        if (!option) return;
        const url = `/tickets/${option.internalId}`;
        setSelectedValue("");
        router.push(url);
      }}
      onInputChange={(_event, value) => {
        setSearchTerms(value);
      }}
      open={open}
      onOpen={() => setOpen(true)}
      noOptionsText="No results"
      options={searchResults ?? []}
      getOptionLabel={(option: any) => {
        if (option) {
          return option.title;
        } else {
          return "";
        }
      }}
      renderOption={(props, option: any) => (
        <SearchResult props={props} key={option.id} option={option} />
      )}
      sx={{ width: "100%" }}
      renderInput={(params: any) => <SearchInput {...params} />}
    />
  );
};
