import React, { useState } from "react";
import { Decorator, Meta, StoryFn } from "@storybook/react";
import {
  ThemeProviderWithStyledEngine,
  Autocomplete,
  Typography,
  SelectOption,
  Input,
  UserAvatar,
} from "..";

const disabled = {
  table: {
    disable: true,
  },
};

const decorator: Decorator<unknown> = (Story) => (
  <ThemeProviderWithStyledEngine>
    <div style={{ padding: "1em" }}>{Story()}</div>
  </ThemeProviderWithStyledEngine>
);

const meta = {
  title: "Components/Inputs/Autocomplete",
  component: Autocomplete,
  decorators: [decorator],
  argTypes: {
    multiple: disabled,
    value: disabled,
    filterSelectedOptions: disabled,
    NoOptionFindComponent: disabled,
    onInputChange: disabled,
    onChange: disabled,
    height: {
      control: {
        type: "radio",
      },
      options: ["32", "40"],
    },
    error: {
      type: "boolean",
    },
    errorText: {
      type: "string",
    },
  },
} satisfies Meta<typeof Autocomplete>;

export default meta;

const validateEmail = (email: string) => {
  return String(email)
    .toLowerCase()
    .match(
      /* eslint-disable-next-line max-len */
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

const CreateNewEmail = (props: { value: string }) => {
  if (validateEmail(props.value)) {
    return (
      <Typography size="200" weight="regular">
        <div onClick={() => alert("Invite sent")}>
          Send invite to: {props.value}
        </div>
      </Typography>
    );
  }

  return (
    <Typography size="200" weight="regular">
      No users
    </Typography>
  );
};

const Template: StoryFn<typeof Autocomplete> = (args) => {
  const [selected, setSelected] = useState<SelectOption | null>(null);

  return (
    <Autocomplete
      {...args}
      id="please-specify-the-id-when-youre-using-this-component"
      value={selected}
      onChange={(e, selected) => setSelected(selected as SelectOption)}
    />
  );
};

const MultipleSelectTemplate: StoryFn<typeof Autocomplete> = ({
  label,
  ...args
}) => {
  const [selected, setSelected] = React.useState<SelectOption[]>([]);
  const [inputText, setInputText] = useState("");

  return (
    <Autocomplete
      {...args}
      id="please-specify-the-id-when-youre-using-this-component"
      label={
        <Input.Label
          htmlFor="please-specify-the-id-when-youre-using-this-component"
          icon="question-mark-circle-fill"
          iconTooltipProps={{ tooltip: "Pick everything!" }}
        >
          {label}
        </Input.Label>
      }
      value={selected}
      onChange={(e, selected) => setSelected(selected as SelectOption[])}
      onInputChange={(e, value) => setInputText(value)}
      NoOptionFindComponent={<CreateNewEmail value={inputText} />}
    />
  );
};

const options = [
  {
    value: "1",
    label: "Option 1",
  },
  {
    value: "2",
    label: "Option 2",
    icon: "minus",
    showIconInChip: true,
  },
  {
    value: "3",
    label: "Option 3",
    icon: <UserAvatar id={String(Math.random() * 100)} name="Jane" online />,
    showIconInChip: true,
  },
  {
    value: "4",
    label: "Disabled",
    disabled: true,
  },
] as SelectOption[];

const groupedOptions = [
  {
    value: "0",
    label: "Option without group label",
    groupLabel: "",
  },
  {
    value: "1",
    label: "Option 1",
    groupLabel: "Group 1",
  },
  {
    value: "2",
    label: "Option 2",
    icon: "minus",
    showIconInChip: true,
    groupLabel: "Group 1",
  },
  {
    value: "3",
    label: "Another option without group label",
    groupLabel: "",
  },
  {
    value: "4",
    label: "Option 4",
    icon: <UserAvatar id={String(Math.random() * 100)} name="Jane" online />,
    showIconInChip: true,
    groupLabel: "Group 2",
  },
  {
    value: "5",
    label: "Disabled",
    disabled: true,
    groupLabel: "Group 2",
  },
] as SelectOption[];

export const Default: StoryFn<typeof Autocomplete> = Template.bind({});
export const MultiSelect: StoryFn<typeof Autocomplete> =
  MultipleSelectTemplate.bind({});
export const MultiSelectSmall: StoryFn<typeof Autocomplete> =
  MultipleSelectTemplate.bind({});
export const Grouped: StoryFn<typeof Autocomplete> = Default.bind({});
export const MultiGrouped: StoryFn<typeof Autocomplete> =
  MultipleSelectTemplate.bind({});

Default.args = {
  options,
  height: "40",
  label: "Invite Users",
  fullWidth: true,
  required: false,
  multiple: false,
  error: false,
  errorText: "Required",
  placeholder: "Placeholder",
};

MultiSelect.args = {
  ...Default.args,
  label: "Autocomplete (Multiple)",
  multiple: true,
};

MultiSelectSmall.args = {
  ...Default.args,
  label: "Autocomplete small (Multiple)",
  multiple: true,
  height: "32",
};

Grouped.args = {
  ...Default.args,
  label: "Autocomplete (Grouped)",
  grouped: true,
  options: groupedOptions,
};

MultiGrouped.args = {
  ...Default.args,
  label: "Autocomplete (Multiple + Grouped)",
  grouped: true,
  multiple: true,
  options: groupedOptions,
};
