"use client";

import { useState, useEffect } from "react";
import { Clock, Flame, Zap, Check } from "lucide-react";
import type { ContentTrack, Region } from "@/lib/types";
import {
  type TimeSlot,
  type SlotRank,
  getSuggestedSlots,
  getNextOccurrence,
  formatDateInput,
  formatTimeInput,
} from "@/lib/time-slots";

interface TrackConfig {
  track: ContentTrack;
  bestWindows: { day: string; hour: number }[];
  regionBestWindows?: string | null;
}

interface TimeSlotPickerProps {
  selectedTrack: ContentTrack | null;
  region?: Region | "";
  scheduleDate: string;
  scheduleTime: string;
  onDateChange: (date: string) => void;
  onTimeChange: (time: string) => void;
}

const RANK_STYLES: Record<SlotRank, { bg: string; border: string; badge: string; badgeBg: string }> = {
  best: {
    bg: "bg-orange-50 hover:bg-orange-100",
    border: "border-orange-300",
    badge: "text-orange-700",
    badgeBg: "bg-orange-100",
  },
  good: {
    bg: "bg-blue-50 hover:bg-blue-100",
    border: "border-blue-300",
    badge: "text-blue-700",
    badgeBg: "bg-blue-100",
  },
  ok: {
    bg: "bg-gray-50 hover:bg-gray-100",
    border: "border-gray-300",
    badge: "text-gray-600",
    badgeBg: "bg-gray-100",
  },
};

const RANK_ICONS: Record<SlotRank, typeof Flame> = {
  best: Flame,
  good: Zap,
  ok: Check,
};

const RANK_LABELS: Record<SlotRank, string> = {
  best: "Best",
  good: "Good",
  ok: "OK",
};

function isSlotSelected(slot: TimeSlot, scheduleDate: string, scheduleTime: string): boolean {
  if (!scheduleDate || !scheduleTime) return false;
  const occurrence = getNextOccurrence(slot.day, slot.hour, slot.minute);
  return (
    formatDateInput(occurrence) === scheduleDate &&
    formatTimeInput(slot.hour, slot.minute) === scheduleTime
  );
}

export function TimeSlotPicker({
  selectedTrack,
  region,
  scheduleDate,
  scheduleTime,
  onDateChange,
  onTimeChange,
}: TimeSlotPickerProps) {
  const [configs, setConfigs] = useState<TrackConfig[]>([]);
  const [showCustom, setShowCustom] = useState(false);

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

  // Get bestWindows for selected track, preferring region-specific windows
  const trackConfig = configs.find((c) => c.track === selectedTrack);
  let effectiveWindows = trackConfig?.bestWindows;
  if (region && region !== "GLOBAL" && trackConfig?.regionBestWindows) {
    try {
      const parsed = typeof trackConfig.regionBestWindows === "string"
        ? JSON.parse(trackConfig.regionBestWindows)
        : trackConfig.regionBestWindows;
      if (parsed[region] && Array.isArray(parsed[region]) && parsed[region].length > 0) {
        effectiveWindows = parsed[region];
      }
    } catch { /* fallback to default bestWindows */ }
  }
  const slots = getSuggestedSlots(effectiveWindows, 3);

  const handleSelectSlot = (slot: TimeSlot) => {
    const occurrence = getNextOccurrence(slot.day, slot.hour, slot.minute);
    onDateChange(formatDateInput(occurrence));
    onTimeChange(formatTimeInput(slot.hour, slot.minute));
    setShowCustom(false);
  };

  const handleCustom = () => {
    setShowCustom(true);
  };

  // Check if current date/time matches any slot
  const anySlotSelected = slots.some((s) => isSlotSelected(s, scheduleDate, scheduleTime));
  const customActive = showCustom || (scheduleDate && !anySlotSelected);

  // Show user's timezone, or the region timezone when a non-GLOBAL region is selected
  const REGION_TZ: Record<string, string> = { APAC: "Asia/Kolkata", NA: "America/Los_Angeles", LATAM: "America/Sao_Paulo", EMEA: "Europe/Berlin" };
  const activeTz = region && region !== "GLOBAL" && REGION_TZ[region]
    ? REGION_TZ[region]
    : Intl.DateTimeFormat().resolvedOptions().timeZone;
  const tzLabel = activeTz;
  const tzAbbr = new Date().toLocaleTimeString("en-US", { timeZone: activeTz, timeZoneName: "short" }).split(" ").pop();

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-1.5">
        <Clock className="h-3.5 w-3.5 text-gray-400" />
        <span className="text-xs font-medium text-gray-500">Suggested times</span>
        <span className="text-[10px] text-gray-400 ml-auto" title={tzLabel}>
          {tzAbbr}
        </span>
      </div>

      {/* Slot cards: 3 in a row on desktop, stack on mobile */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
        {slots.map((slot) => {
          const selected = isSlotSelected(slot, scheduleDate, scheduleTime);
          const style = RANK_STYLES[slot.rank];
          const Icon = RANK_ICONS[slot.rank];

          return (
            <button
              key={`${slot.day}-${slot.hour}`}
              type="button"
              onClick={() => handleSelectSlot(slot)}
              className={`relative flex flex-col items-center gap-1.5 rounded-lg border-2 px-3 py-3 min-h-[44px] text-center transition-all ${
                selected
                  ? `${style.bg} ${style.border} ring-2 ring-offset-1 ring-gray-900/10`
                  : `${style.bg} border-transparent hover:border-gray-200`
              }`}
            >
              {/* Rank badge */}
              <span
                className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${style.badge} ${style.badgeBg}`}
              >
                <Icon className="h-3 w-3" />
                {RANK_LABELS[slot.rank]}
              </span>

              {/* Day + time */}
              <span className="text-sm font-medium text-gray-900 leading-tight">
                {slot.label}
              </span>

              {/* Next date hint */}
              <span className="text-[10px] text-gray-400">
                {formatDateInput(getNextOccurrence(slot.day, slot.hour, slot.minute))}
              </span>
            </button>
          );
        })}
      </div>

      {/* Custom time option */}
      {!customActive ? (
        <button
          type="button"
          onClick={handleCustom}
          className="text-xs font-medium text-blue-600 hover:text-blue-700 hover:underline"
        >
          Custom time...
        </button>
      ) : (
        <div className="flex flex-col sm:flex-row gap-2">
          <div className="flex-1">
            <label className="text-[10px] font-medium text-gray-400 mb-0.5 block">Date</label>
            <input
              type="date"
              value={scheduleDate}
              onChange={(e) => onDateChange(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-2.5 py-2.5 sm:py-1.5 min-h-[44px] sm:min-h-0 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
            />
          </div>
          <div className="flex-1">
            <label className="text-[10px] font-medium text-gray-400 mb-0.5 block">Time</label>
            <input
              type="time"
              value={scheduleTime}
              onChange={(e) => onTimeChange(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-2.5 py-2.5 sm:py-1.5 min-h-[44px] sm:min-h-0 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
            />
          </div>
        </div>
      )}
    </div>
  );
}
