import { Fragment, useEffect, useState } from "react";

import Autocomplete from "@mui/joy/Autocomplete";
import AutocompleteOption from "@mui/joy/AutocompleteOption";
import CircularProgress from "@mui/joy/CircularProgress";
import Image from "next/image";
import ListItemContent from "@mui/joy/ListItemContent";
import ListItemDecorator from "@mui/joy/ListItemDecorator";
import Typography from "@mui/joy/Typography";
import { createFilterOptions } from "@mui/joy/Autocomplete";
import useDebounce from "~/utils/useDebounce";
import type { Asset, HandleAssetSelected } from "~/interfaces/simulator";
import useLocalization from "~/utils/useLocalization";
import { api } from "~/utils/api";

const filterOptions = createFilterOptions({
  ignoreAccents: true,
  ignoreCase: true,
  trim: true,
  stringify: (option: Asset) =>
    `${option.ticker} ${option.name ?? ""} ${option.sector ?? ""}`,
});

export default function AssetSelector({
  handleAssetSelected,
}: {
  handleAssetSelected: HandleAssetSelected;
}) {
  const { localization } = useLocalization();

  const [assetSearchTerm, setAssetSearchTerm] = useState("");

  const debouncedSearchTerm = useDebounce(assetSearchTerm, 500);

  const [loading, setLoading] = useState(false);

  const assetsQuery = api.asset.getAssets.useQuery(
    { keyword: debouncedSearchTerm },
    {
      enabled: false,
    }
  );

  useEffect(() => {
    if (debouncedSearchTerm.length >= 1) {
      void assetsQuery.refetch();
    }
  }, [debouncedSearchTerm]);

  useEffect(() => {
    setLoading(false);
  }, [assetsQuery.data]);

  return (
    <>
      <Autocomplete
        options={assetsQuery.isSuccess ? assetsQuery.data : []}
        autoHighlight
        renderOption={(props, asset: Asset) => (
          <Fragment key={asset.id}>
            <AutocompleteOption {...props}>
              <ListItemDecorator>
                <Image
                  src={asset.logo ?? ""}
                  width={30}
                  height={30}
                  alt={`${asset.id} logo`}
                />
              </ListItemDecorator>
              <ListItemContent sx={{ fontSize: "sm" }} key={`${asset.id} cont`}>
                {asset.ticker}
                <Typography level='body3'>
                  ({asset.name}) {asset.sector}
                </Typography>
              </ListItemContent>
            </AutocompleteOption>
          </Fragment>
        )}
        onClose={() => {
          setLoading(false);
        }}
        isOptionEqualToValue={(option: Asset, value: Asset) => {
          return option.id === value.id;
        }}
        onChange={(_, asset: Asset | null) => {
          if (asset !== null) {
            handleAssetSelected(asset);
          }
        }}
        onInputChange={(_, newAssetSearchTerm) => {
          if (newAssetSearchTerm.length > 1) {
            setLoading(true);
            setAssetSearchTerm(newAssetSearchTerm);
          }
        }}
        getOptionLabel={(option: Asset) => option.ticker ?? ""}
        filterOptions={filterOptions}
        placeholder={localization.body.searchAssets}
        slotProps={{
          input: {
            autoComplete: "new-password", // disable autocomplete and autofill
          },
        }}
        loading={loading}
        endDecorator={
          loading ? (
            <CircularProgress
              size='sm'
              sx={{ bgcolor: "background.surface" }}
            />
          ) : null
        }
      />
    </>
  );
}
