import { useState, useMemo } from "react";
import {
  Stack,
  Text,
  Group,
  Button,
  Box,
  Popover,
  UnstyledButton,
  useMantineTheme,
} from "@mantine/core";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import CloudOutlinedIcon from "@mui/icons-material/CloudOutlined";
import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";

interface FormatOption {
  value: string;
  label: string;
  group: string;
  enabled?: boolean;
  usesCloud?: boolean;
}

interface GroupedFormatDropdownProps {
  value?: string;
  placeholder?: string;
  options: FormatOption[];
  onChange: (value: string) => void;
  disabled?: boolean;
  minWidth?: string;
  name?: string;
  withinPortal?: boolean;
  zIndex?: number;
}

const GroupedFormatDropdown = ({
  value,
  placeholder = "Select an option",
  options,
  onChange,
  disabled = false,
  minWidth = "18.75rem",
  name,
  withinPortal = true,
  zIndex = Z_INDEX_AUTOMATE_DROPDOWN,
}: GroupedFormatDropdownProps) => {
  const [dropdownOpened, setDropdownOpened] = useState(false);
  const theme = useMantineTheme();

  const groupedOptions = useMemo(() => {
    const groups: Record<string, FormatOption[]> = {};

    options.forEach((option) => {
      if (!groups[option.group]) {
        groups[option.group] = [];
      }
      groups[option.group].push(option);
    });

    return groups;
  }, [options]);

  const selectedLabel = useMemo(() => {
    if (!value) return placeholder;
    const selected = options.find((opt) => opt.value === value);
    return selected
      ? `${selected.group} (${selected.label})`
      : value.toUpperCase();
  }, [value, options, placeholder]);

  const handleOptionSelect = (selectedValue: string) => {
    onChange(selectedValue);
    setDropdownOpened(false);
  };

  return (
    <Popover
      opened={dropdownOpened}
      onDismiss={() => setDropdownOpened(false)}
      position="bottom-start"
      withArrow
      shadow="sm"
      disabled={disabled}
      closeOnEscape={true}
      trapFocus
      withinPortal={withinPortal}
      zIndex={zIndex}
    >
      <Popover.Target>
        <UnstyledButton
          name={name}
          data-testid={name}
          onClick={() => setDropdownOpened(!dropdownOpened)}
          disabled={disabled}
          style={{
            padding: "0.5rem 0.75rem",
            border: `0.0625rem solid ${theme.colors.gray[4]}`,
            borderRadius: theme.radius.sm,
            backgroundColor: disabled
              ? theme.colors.gray[1]
              : "var(--dropdown-trigger-bg)",
            cursor: disabled ? "not-allowed" : "pointer",
            width: "100%",
            color: disabled
              ? "var(--dropdown-trigger-text-disabled)"
              : "var(--dropdown-trigger-text)",
          }}
        >
          <Group justify="space-between">
            <Text size="sm" c={value ? undefined : "dimmed"}>
              {selectedLabel}
            </Text>
            <KeyboardArrowDownIcon
              style={{
                fontSize: "1rem",
                transform: dropdownOpened ? "rotate(180deg)" : "rotate(0deg)",
                transition: "transform 0.2s ease",
                color: "var(--dropdown-trigger-icon)",
              }}
            />
          </Group>
        </UnstyledButton>
      </Popover.Target>
      <Popover.Dropdown
        style={{
          minWidth: Math.min(350, parseInt(minWidth.replace("rem", "")) * 16),
          maxWidth: "90vw",
          maxHeight: "40vh",
          overflow: "auto",
          backgroundColor: "var(--dropdown-panel-bg)",
          border: `0.0625rem solid var(--dropdown-panel-border)`,
        }}
      >
        <Stack gap="md">
          {Object.entries(groupedOptions).map(([groupName, groupOptions]) => (
            <Box key={groupName}>
              <Text
                size="sm"
                fw={600}
                mb="xs"
                style={{ color: "var(--dropdown-group-label)" }}
              >
                {groupName}
              </Text>
              <Group gap="xs" style={{ flexWrap: "wrap" }}>
                {groupOptions.map((option) => (
                  <Button
                    key={option.value}
                    data-testid={`format-option-${option.value}`}
                    variant={value === option.value ? "filled" : "outline"}
                    size="sm"
                    onClick={() => handleOptionSelect(option.value)}
                    disabled={option.enabled === false}
                    style={{
                      fontSize: "0.75rem",
                      height: "2rem",
                      padding: "0 0.75rem",
                      flexShrink: 0,
                      position: "relative",
                    }}
                  >
                    {option.label}
                    {option.usesCloud && (
                      <CloudOutlinedIcon
                        style={{
                          fontSize: "0.625rem",
                          marginLeft: "0.25rem",
                          opacity: 0.7,
                        }}
                      />
                    )}
                  </Button>
                ))}
              </Group>
            </Box>
          ))}
        </Stack>
      </Popover.Dropdown>
    </Popover>
  );
};

export default GroupedFormatDropdown;
