import React, { useState } from "react";

import Autocomplete from "@mui/material/Autocomplete";
import FormHelperText from "@mui/material/FormHelperText";
import Grid from "@mui/material/Grid2";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";

import { useCardContext } from "../../contexts/CardContext";
import LabeledValue from "../LabeledValue";

import { CardFieldBaseProps, FormOption } from "./shared";

export interface CardFieldAutoCompleteProps extends CardFieldBaseProps, React.PropsWithChildren {
  fallback: string;
  isEditable?: boolean;
  type: "autocomplete";
  value: FormOption[];
  autoSelect?: boolean;
  clearOnBlur?: boolean;
  freeSolo?: boolean;
}

export const CardFieldAutoComplete: React.FC<Omit<CardFieldAutoCompleteProps, "type">> = ({
  fallback = "—",
  fallbackPredicate = (value) => value == null || (Array.isArray(value) && value.length === 0),
  formName,
  helperText,
  isEditable = true,
  isReadable = true,
  label,
  options,
  size = "grow",
  value: defaultValue,
  autoSelect = false,
  clearOnBlur = false,
  freeSolo = false,
  ...props
}) => {
  const { isCompact, isEditing } = useCardContext();

  // Manage the selected options state
  const [selectedOptions, setSelectedOptions] = useState<FormOption[]>(defaultValue ?? []);

  return (
    <Grid size={size}>
      {isEditing && isEditable ? (
        <Stack alignItems="center" justifyContent="space-between">
          <Autocomplete
            autoSelect={autoSelect}
            clearOnBlur={clearOnBlur}
            freeSolo={freeSolo}
            isOptionEqualToValue={(option: FormOption, value: FormOption) => option.id === value.id}
            multiple={true}
            options={options ?? []}
            renderInput={(props) => <TextField {...props} label={label} />}
            sx={{ width: "100%" }}
            value={selectedOptions}
            onChange={(_, value) =>
              setSelectedOptions(
                value.map((v) => (typeof v == "string" ? { id: v, label: v } : v)) as FormOption[],
              )
            }
            {...props}
          />

          {/* Render hidden inputs for form submission */}
          {selectedOptions.map((option) => (
            <input key={option.id} name={formName} type="hidden" value={option.id} />
          ))}

          {helperText != null && <FormHelperText>{helperText}</FormHelperText>}
        </Stack>
      ) : (
        isReadable && (
          <LabeledValue
            compact={isCompact}
            label={label}
            value={
              fallbackPredicate(defaultValue)
                ? fallback
                : defaultValue.map(({ label }) => label).join(", ")
            }
          />
        )
      )}
    </Grid>
  );
};

export default CardFieldAutoComplete;
