"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { createPortal } from "react-dom";
import { ChevronDown } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import type { ContentTrack } from "@/lib/types";
import { TRACK_LABELS, TRACK_ORDER } from "@/lib/track-display";

const TRACK_COLORS: Record<string, string> = {
  ENTERPRISE: "bg-blue-100 text-blue-700 border-blue-200",
  PRODUCT: "bg-indigo-100 text-indigo-700 border-indigo-200",
  DEVELOPER: "bg-purple-100 text-purple-700 border-purple-200",
  THOUGHT_LEADERSHIP: "bg-teal-100 text-teal-700 border-teal-200",
  EVENT: "bg-orange-100 text-orange-700 border-orange-200",
  TI_CULTURAL: "bg-pink-100 text-pink-700 border-pink-200",
};

const ALL_TRACKS: ContentTrack[] = [...TRACK_ORDER] as ContentTrack[];

interface TrackConfig {
  track: ContentTrack;
  weeklySlotCap: number;
  requiresApproval: boolean;
  bestWindows: { day: string; hour: number }[];
}

interface TrackSelectorProps {
  value: ContentTrack | null;
  onChange: (track: ContentTrack) => void;
  content: string;
}

export function TrackSelector({ value, onChange, content }: TrackSelectorProps) {
  const [open, setOpen] = useState(false);
  const [configs, setConfigs] = useState<TrackConfig[]>([]);
  const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0, width: 0 });
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    fetch("/api/v1/tracks")
      .then((r) => (r.ok ? r.json() : []))
      .then((data: TrackConfig[]) => setConfigs(data))
      .catch(() => {});
  }, []);

  // Auto-suggest on content change (debounced 600ms)
  // Skip if a track is already selected (e.g. loaded from an existing post in edit mode)
  const suggestTrack = useCallback(
    (text: string) => {
      if (value) return; // Don't overwrite an already-selected track
      if (!text || text.length < 10) return;
      if (debounceRef.current) clearTimeout(debounceRef.current);
      debounceRef.current = setTimeout(async () => {
        try {
          const res = await fetch("/api/v1/posts/suggest-track", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ content: text }),
          });
          if (res.ok) {
            const data = await res.json();
            if (data.track) onChange(data.track as ContentTrack);
          }
        } catch {
          // ignore
        }
      }, 600);
    },
    [onChange, value]
  );

  useEffect(() => {
    suggestTrack(content);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [content, suggestTrack]);

  // Close dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      const target = e.target as Node;
      if (
        dropdownRef.current && !dropdownRef.current.contains(target) &&
        triggerRef.current && !triggerRef.current.contains(target)
      ) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [open]);

  // Use API-driven track list if available, fallback to ALL_TRACKS
  const trackList: ContentTrack[] = configs.length > 0
    ? configs.map((c) => c.track)
    : ALL_TRACKS;

  const currentConfig = configs.find((c) => c.track === value);

  const ruleText = currentConfig
    ? [
        currentConfig.requiresApproval ? "Requires approval" : "Auto-queued",
        currentConfig.weeklySlotCap > 0
          ? `${currentConfig.weeklySlotCap} slots/wk`
          : "Unlimited slots",
        currentConfig.bestWindows.length > 0
          ? `Best: ${currentConfig.bestWindows[0].day} ${currentConfig.bestWindows[0].hour}am`
          : "",
      ]
        .filter(Boolean)
        .join(" \u00B7 ")
    : null;

  const handleToggle = () => {
    if (!open && triggerRef.current) {
      const rect = triggerRef.current.getBoundingClientRect();
      setDropdownPos({ top: rect.bottom + 4, left: rect.left, width: Math.max(rect.width, 260) });
    }
    setOpen(!open);
  };

  return (
    <div className="relative">
      <div className="flex items-center gap-2">
        <button
          ref={triggerRef}
          type="button"
          onClick={handleToggle}
          className="inline-flex items-center gap-1 min-h-[44px] sm:min-h-0"
        >
          {value ? (
            <Badge className={`text-xs px-2 py-0.5 rounded-full border ${TRACK_COLORS[value]}`}>
              {TRACK_LABELS[value]}
              <ChevronDown className="ml-1 h-3 w-3" />
            </Badge>
          ) : (
            <Badge className="text-xs px-2 py-0.5 rounded-full border border-gray-200 bg-gray-50 text-gray-500">
              Select track
              <ChevronDown className="ml-1 h-3 w-3" />
            </Badge>
          )}
        </button>
      </div>

      {ruleText && (
        <p className="text-[11px] text-gray-400 mt-1">{ruleText}</p>
      )}

      {open && typeof document !== "undefined" && createPortal(
        <div
          ref={dropdownRef}
          style={{ position: "fixed", top: dropdownPos.top, left: dropdownPos.left, width: dropdownPos.width }}
          className="z-[9999] max-h-64 overflow-y-auto rounded-lg border border-gray-200 bg-white shadow-lg py-1"
        >
          {trackList.map((t) => (
            <button
              key={t}
              type="button"
              onClick={() => {
                onChange(t);
                setOpen(false);
              }}
              className={`flex w-full items-center gap-2 px-3 py-2.5 sm:py-1.5 min-h-[44px] sm:min-h-0 text-sm text-left hover:bg-gray-50 ${
                value === t ? "bg-gray-50 font-medium" : ""
              }`}
            >
              <span
                className={`inline-block h-2 w-2 rounded-full ${
                  (TRACK_COLORS[t] ?? "bg-gray-100 text-gray-700 border-gray-200").split(" ")[0]
                }`}
              />
              {TRACK_LABELS[t] ?? t}
            </button>
          ))}
        </div>,
        document.body
      )}
    </div>
  );
}
