import { useState, useRef, useEffect } from "react";
import clsx from "clsx";
import { viralySsoUrl } from "../../utils/sso";

export type TimeframeValue =
  | "Last7Days" | "Last14Days" | "Last30Days" | "Last60Days" | "Last90Days"
  | "Last6Months" | "Last9Months" | "Last12Months" | "Last24Months"
  | "ThisWeek" | "LastWeek" | "ThisMonth" | "LastMonth" | "ThisYear" | "LastYear"
  | "Today" | "Yesterday";

interface TimeframeOption {
  value: TimeframeValue;
  label: string;
  minTier: "Free" | "Influencer" | "Business" | "Agency";
}

const OPTIONS: TimeframeOption[] = [
  { value: "Last7Days", label: "Last 7 Days", minTier: "Free" },
  { value: "Last14Days", label: "Last 14 Days", minTier: "Free" },
  { value: "ThisWeek", label: "This Week", minTier: "Free" },
  { value: "Last30Days", label: "Last 30 Days", minTier: "Influencer" },
  { value: "Last60Days", label: "Last 60 Days", minTier: "Influencer" },
  { value: "Last90Days", label: "Last 90 Days", minTier: "Influencer" },
  { value: "LastWeek", label: "Last Week", minTier: "Influencer" },
  { value: "ThisMonth", label: "This Month", minTier: "Influencer" },
  { value: "LastMonth", label: "Last Month", minTier: "Influencer" },
  { value: "Last6Months", label: "Last 6 Months", minTier: "Influencer" },
  { value: "Last9Months", label: "Last 9 Months", minTier: "Business" },
  { value: "Last12Months", label: "Last 12 Months", minTier: "Business" },
  { value: "Last24Months", label: "Last 24 Months", minTier: "Agency" },
  { value: "ThisYear", label: "This Year", minTier: "Agency" },
  { value: "LastYear", label: "Last Year", minTier: "Agency" },
];

const TIER_ORDER: Record<string, number> = { Free: 0, Influencer: 1, Business: 2, Agency: 3, Enterprise: 4 };

interface Props {
  value: TimeframeValue;
  onChange: (value: TimeframeValue) => void;
  planTier?: string;
}

export default function TimeframePicker({ value, onChange, planTier = "Free" }: Props) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const tierLevel = TIER_ORDER[planTier] ?? 0;

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const currentLabel = OPTIONS.find((o) => o.value === value)?.label || value;

  return (
    <div ref={ref} className="vr-relative">
      <button
        onClick={() => setOpen(!open)}
        className="vr-inline-flex vr-items-center vr-gap-2 vr-px-3 vr-py-1.5 vr-rounded-lg vr-border vr-border-gray-200 vr-bg-white vr-text-xs vr-font-medium vr-text-gray-700 hover:vr-border-gray-300 vr-transition-colors vr-cursor-pointer"
      >
        <i className="fa-solid fa-calendar" style={{ fontSize: "10px", color: "#9ca3af" }} />
        {currentLabel}
        <i className={`fa-solid fa-chevron-${open ? "up" : "down"}`} style={{ fontSize: "8px", color: "#9ca3af" }} />
      </button>

      {open && (
        <div className="vr-absolute vr-right-0 vr-mt-1 vr-w-52 vr-bg-white vr-border vr-border-gray-200 vr-rounded-lg vr-shadow-lg vr-z-50 vr-py-1 vr-max-h-72 vr-overflow-y-auto">
          {OPTIONS.map((opt) => {
            const locked = TIER_ORDER[opt.minTier] > tierLevel;
            return (
              <button
                key={opt.value}
                onClick={() => {
                  if (!locked) {
                    onChange(opt.value);
                    setOpen(false);
                  }
                }}
                disabled={locked}
                className={clsx(
                  "vr-w-full vr-text-left vr-px-3 vr-py-2 vr-text-xs vr-border-0 vr-transition-colors",
                  locked
                    ? "vr-text-gray-300 vr-cursor-not-allowed"
                    : value === opt.value
                      ? "vr-bg-primary-50 vr-text-primary-600 vr-font-semibold"
                      : "vr-text-gray-700 hover:vr-bg-gray-50 vr-cursor-pointer vr-bg-transparent"
                )}
              >
                <span className="vr-flex vr-items-center vr-justify-between">
                  {opt.label}
                  {locked && <i className="fa-solid fa-lock vr-text-gray-300" style={{ fontSize: "8px" }} />}
                  {value === opt.value && !locked && <i className="fa-solid fa-check vr-text-primary-600" style={{ fontSize: "9px" }} />}
                </span>
              </button>
            );
          })}
          {tierLevel < 3 && (
            <a
              href={viralySsoUrl("/settings/subscription")}
              target="_blank"
              className="vr-block vr-px-3 vr-py-2 vr-text-xs vr-text-amber-600 vr-font-medium vr-border-t vr-border-gray-100 vr-mt-1 hover:vr-bg-amber-50 vr-no-underline"
            >
              <i className="fa-solid fa-bolt vr-mr-1" style={{ fontSize: "8px" }} />
              Upgrade to unlock more
            </a>
          )}
        </div>
      )}
    </div>
  );
}
