import React from "react";
import { FormElementProps, FormElementRegistration } from "@vertigis/workflow";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import ListItemText from '@mui/material/ListItemText';
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import Select from "@mui/material/Select";
import OutlinedInput from "@mui/material/OutlinedInput";
import {useEffect} from "react"

interface Option {
  label: string;
  value?: any;
}

interface DropDownMenuProps extends FormElementProps<any> {
  options: Option[];
  variant: "standard" | "outlined" | "filled";
  defaultLabel: string;
  multiple: boolean;
  nullable: boolean;
  initialValue: any[];
}


const theme = createTheme({
  components: {
    MuiInputLabel: {
      styleOverrides: {
        root: {
          color: 'var(--primaryForeground)',
          fontSize: '1.2rem',
          '&.Mui-focused': {
            color: 'var(--primaryForeground)',
          },
        },
      },
    },
    MuiSelect: {
      styleOverrides: {
        root: {
          color: 'var(--primaryForeground)',
          backgroundColor: 'var(--primaryBackground)',
        },
        icon: {
          color: 'var(--primaryForeground)',
        },
      },
    },
    MuiMenuItem: {
      styleOverrides: {
        root: {
          color: 'var(--primaryForeground)',
          backgroundColor: 'var(--primaryBackground)',
          fontSize: '1.2rem',
          '&:hover': {
            backgroundColor: 'var(--buttonBackground)',
          },
          '&.Mui-selected': {
            backgroundColor: 'var(--buttonBackground)',
            '&:hover': {
              backgroundColor: 'var(--buttonBackground)',
            },
          },
        },
      },
    },
    MuiCheckbox: {
      styleOverrides: {
        root: {
          color: 'var(--primaryForeground)',
          '&.Mui-checked': {
            color: 'var(--primaryForeground)',
          },
        },
      },
    },
    MuiPaper: {
      styleOverrides: {
        root: {
          backgroundColor: 'var(--primaryBackground)',
          color: 'var(--primaryForeground)',
        },
      },
    },
    MuiListItemText: {
      styleOverrides: {
        primary: {
          color: 'var(--primaryForeground)',
          fontSize: '1.2rem',
        },
      },
    },
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          color: 'var(--primaryForeground)',
        },
        input: {
          color: 'var(--primaryForeground)',
          fontSize: '1.2rem',
        },
      },
    },
    MuiAutocomplete: {
      styleOverrides: {
        root: {
          backgroundColor: 'var(--primaryBackground)',
        },
        listbox: {
          fontSize: '1.2rem',
          color: 'var(--secondaryForeground)',
          backgroundColor: 'var(--primaryBackground)',
        },
        endAdornment: {
          color: 'var(--primaryForeground)',
        },
        popupIndicator: {
          color: 'var(--primaryForeground)',
          backgroundColor: 'var(--primaryBackground)',
        },
        clearIndicator: {
          color: 'var(--primaryForeground)',
          '&:hover': {
            color: 'var(--secondaryForeground)',
          },
        },
        paper: {
          backgroundColor: 'var(--primaryBackground)',
          color: 'var(--primaryForeground)',
        },
        inputRoot: {
          color: 'var(--primaryForeground)',
          '& .MuiOutlinedInput-root': {
            border: '1px solid var(--primaryForeground)',
          },
          '& .MuiChip-root': {
            fontSize: '1.2rem',
            backgroundColor: 'var(--buttonBackground)',
            color: 'var(--buttonForeground)',
            border: '1px solid var(--buttonBorder)',
            '& .MuiChip-deleteIcon': {
              color: 'var(--buttonForeground)',
              '&:hover': {
                color: 'var(--buttonForeground)',
              },
            },
          },
        },
      },
    },
    MuiFormControl: {
      styleOverrides: {
        root: {
          '& .MuiInputBase-root': {
            backgroundColor: 'var(--primaryBackground)',
          },
        },
      },
    },
  },
  typography: {
    fontFamily: 'inherit',
  },
  palette: {
    mode: 'light',
  },
});

/**
 * A Workflow element built using React.
 * @displayName Drop Down Menu
 * @description Drop Down Menu v1.9
 * @param props The props that will be provided by the Workflow runtime.
 */

function DropDownMenu(props: DropDownMenuProps): React.ReactElement {
  const { variant, defaultLabel, options, multiple,initialValue,setValue } = props;
  useEffect(() => {
    if (initialValue !== undefined) {
      setValue(initialValue);
    }
  }, []);
 
  const [selectedValues, setSelectedValues] = React.useState<any>(initialValue);
  const [isDataSelected, setIsDataSelected] = React.useState<boolean>(!!initialValue);
  
  // Update the internal state and call setValue when selection changes
  const handleChange = (event: any) => {
    const newValue = event.target.value;

    if (newValue.length === 0 && !props.nullable) {
      return;
    }
    setIsDataSelected(newValue.length > 0);
    setSelectedValues(newValue);
    if (setValue) {
      console.log(newValue);
      setValue(newValue);
    }
  };

  // Render the selected values
  const renderValue = (selected: any) => {
    if (!selected) return '';
    if (multiple) {
      if (Array.isArray(selected)) {
        return selected
          .map(val => options.find(opt => opt.value === val)?.label)
          .filter(Boolean)
          .join(', ');
      }
    }
    const selectedOption = options.find(opt => opt.value === selected);
    return selectedOption ? selectedOption.label : '';
  };

  return (
    <ThemeProvider theme={theme}>
      <FormControl sx={{
         width: '100%', mt: 1, mb: 1}} size="small">
        {!isDataSelected && <InputLabel id="dropdown-menu-label">{defaultLabel}</InputLabel>}
        <Select
          variant={variant}
          notched={false}
          labelId="dropdown-menu-label"
          id="dropdown-menu"
          multiple={multiple}
          value={selectedValues}
          onChange={handleChange}
          input={<OutlinedInput label={defaultLabel} />}
          renderValue={renderValue}
          sx={{ border: '0.1rem solid var(--primaryForeground)'}}
          MenuProps={{
            PaperProps: {
              style: {
                maxHeight: 300,
              },
            },
          }}
        >
          {options.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {multiple && (
                <Checkbox
                  checked={Array.isArray(selectedValues)
                    ? selectedValues.includes(option.value)
                    : selectedValues === option.value
                  }
                />
              )}
              <ListItemText primary={option.label} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </ThemeProvider>
  );
}

const DropDownMenuElementRegistration: FormElementRegistration<DropDownMenuProps> = {
  component: DropDownMenu,
  getInitialProperties: () => ({
    defaultLabel: "Default Label", // Provide a default label here
    variant: "outlined", // Provide a default variant here
    autocompleteType: "autoComplete", // Provide a default autocomplete type here
    options: [
      { label: "Option 1", value: 1},
      { label: "Option 2", value: 2 },
      { label: "Option 3", value: 3 },
      { label: "Option 4", value: 4 },
    ], // Sample options
    multiple: true,
    nullable: false,
    initialValue: [1, 2],
  }),
  id: "DropDownMenu",
};

export default DropDownMenuElementRegistration;