import { FC, useState, useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import useSWR from "swr";
import { Grid, Box, TextField, Autocomplete } from "@mui/material";
import { searchQuery } from "@/app/_graphql/searchQuery";
import { colors } from "@/app/_styles/theme";

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 }) => {
  console.log({ 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 [selectedValue, setSelectedValue] = useState(null);
  const [searchTerms, setSearchTerms] = useState(null);
  const pathname = usePathname();
  const router = useRouter();
  const { data, error }: any = useSWR({
    document: searchQuery,
    variables: {
      search: searchTerms ?? "",
      limit: 50,
    },
    refreshInterval: 10000,
  });

  useEffect(() => {
    setOpen(false);
  }, [pathname]);

  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={data?.search ?? []}
      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} />}
    />
  );
};
