import { useState } from "react";
import { Button, OptionList, Popover } from "@shopify/polaris";
import { CalendarIcon } from "@shopify/polaris-icons";

// ---- Types ----
export interface DateRangePeriod {
  since: string | null;
  until: string | null;
}

export interface DateRangeOption {
  title: string;
  alias: string;
  period: DateRangePeriod | null;
}

export interface DateRangePickerProps {
  /** List of available ranges */
  options: DateRangeOption[];
  /** Currently selected alias (controlled from parent) */
  selectedAlias: string;
  /** Callback when a range changes */
  onChange: (range: DateRangeOption) => void;
  /** Optional custom label instead of range title */
  buttonLabel?: string;
}

export function DateRangePicker({
  options,
  selectedAlias,
  onChange,
  buttonLabel,
}: DateRangePickerProps) {
  const [popoverActive, setPopoverActive] = useState(false);

  const selectedRange =
    options.find((option) => option.alias === selectedAlias) || options[0];

  const handleSelect = (selectedValue: string[]) => {
    const newSelection = options.find((opt) => opt.alias === selectedValue[0]);
    if (newSelection) onChange(newSelection);
    setPopoverActive(false);
  };

  return (
    <Popover
      active={popoverActive}
      autofocusTarget="none"
      preferredAlignment="left"
      preferredPosition="below"
      onClose={() => setPopoverActive(false)}
      activator={
        <Button
          onClick={() => setPopoverActive((prev) => !prev)}
          icon={CalendarIcon}
        >
          {buttonLabel || selectedRange?.title || "Select date"}
        </Button>
      }
    >
      <OptionList
        options={options.map((opt) => ({
          value: opt.alias,
          label: opt.title,
        }))}
        selected={[selectedRange?.alias || ""]}
        onChange={handleSelect}
      />
    </Popover>
  );
}

export default DateRangePicker;
