import { useEffect, useMemo, useRef } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { useLocation } from "wouter";
import { Sparkles, Zap, TrendingUp } from "lucide-react";
import StrategyCard from "./StrategySelectorCard";
import { GOLDEN_NIFTY_PATH, ALPHA_SHIELD_PATH } from "@/lib/routes";

type StrategySelectorModalProps = {
  open: boolean;
  onClose: () => void;
};

const focusableSelector = [
  "a[href]",
  "button:not([disabled])",
  "textarea",
  "input",
  "select",
  "[tabindex]:not([tabindex='-1'])",
].join(",");

export default function StrategySelectorModal({ open, onClose }: StrategySelectorModalProps) {
  const dialogRef = useRef<HTMLDivElement>(null);
  const [, navigate] = useLocation();

  const focusable = useMemo(() => {
    if (!dialogRef.current) return [];
    return Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector));
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const first = focusable[0];
    first?.focus();

    const handleKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onClose();
        return;
      }
      if (event.key !== "Tab") return;
      if (focusable.length === 0) return;
      const firstEl = focusable[0];
      const lastEl = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === firstEl) {
        event.preventDefault();
        lastEl?.focus();
      } else if (!event.shiftKey && document.activeElement === lastEl) {
        event.preventDefault();
        firstEl?.focus();
      }
    };

    document.addEventListener("keydown", handleKey);
    return () => document.removeEventListener("keydown", handleKey);
  }, [open, focusable, onClose]);

  const handleSelectGolden = () => {
    onClose();
    window.setTimeout(() => {
      navigate(GOLDEN_NIFTY_PATH);
    }, 200);
  };

  const handleSelectAlphaShield = () => {
    onClose();
    window.setTimeout(() => {
      navigate(ALPHA_SHIELD_PATH);
    }, 200);
  };

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          className="fixed inset-0 z-[90] flex items-end justify-center px-3 py-4 sm:items-center sm:px-6 sm:py-10"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          <motion.button
            type="button"
            aria-label="Close strategies modal"
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            onClick={onClose}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          />

          <motion.div
            ref={dialogRef}
            role="dialog"
            aria-modal="true"
            aria-labelledby="strategy-modal-title"
            aria-describedby="strategy-modal-subtitle"
            className="relative z-[91] max-h-[90vh] w-full max-w-4xl overflow-y-auto rounded-[1.75rem] border border-white/10 bg-gradient-to-br from-white/10 via-background/80 to-background/90 p-4 shadow-2xl sm:rounded-3xl sm:p-8"
            initial={{ opacity: 0, scale: 0.95, y: 16 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 16 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
            onClick={(event) => event.stopPropagation()}
          >
            <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
              <div>
                <h2 id="strategy-modal-title" className="text-2xl font-semibold text-foreground">
                  Choose Your Strategy
                </h2>
                <p id="strategy-modal-subtitle" className="mt-2 text-sm text-muted-foreground">
                  Systematic paths for long-term wealth
                </p>
              </div>
              <button
                type="button"
                onClick={onClose}
                className="rounded-full border border-white/10 bg-white/10 px-3 py-1 text-xs text-muted-foreground hover:text-foreground sm:self-start"
              >
                Close
              </button>
            </div>

            <div className="mt-6 grid gap-4 md:mt-8 md:grid-cols-3">
              <StrategyCard
                title="Golden Nifty"
                description="Balanced Nifty + Gold allocation for stability."
                status="Active"
                cta="View Strategy"
                icon={<TrendingUp className="h-5 w-5" />}
                onClick={handleSelectGolden}
              />
              <StrategyCard
                title="Alpha Shield"
                description="High-growth midcap with intelligent gold protection."
                status="Active"
                cta="View Strategy"
                icon={<Zap className="h-5 w-5" />}
                onClick={handleSelectAlphaShield}
              />
              <StrategyCard
                title="Flexi Momentum"
                description="Momentum-led allocation across caps."
                status="Coming Soon"
                disabled
                icon={<Sparkles className="h-5 w-5" />}
              />
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
