import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import type { MeetingStatus } from "@/types";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function formatDuration(seconds: number): string {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

export function formatDate(date: string | Date): string {
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(date));
}

export function getInitials(name: string): string {
  return name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
}

export function getTimeBasedGreeting(displayName?: string): string {
  const now = new Date();
  const hour = now.getHours();
  const minute = now.getMinutes();
  const time = hour + minute / 60; // e.g. 9.5 = 9:30
  const firstName = displayName?.split(" ")[0];
  const pick = (messages: string[]) => messages[(now.getDate() + hour) % messages.length];

  let greeting: string;

  if (time < 8.5)
    greeting = pick([
      "Early start today — ease in with a calm mind 🌅",
      "You are ahead of the day — nice quiet runway ☕",
      "Fresh morning, clean slate, let's begin gently 🌤️",
    ]);

  else if (time < 9.65)
    greeting = pick([
      "Almost office time — settle in and take it steady ☕",
      "Warming up for the day — no rush, just rhythm 🌤️",
      "Pre-work quiet mode — line up the first win 🎯",
    ]);

  else if (time < 10)
    greeting = pick([
      "Good morning — just reached office, let's get rolling 🚀",
      "Office mode on — start light, then build momentum 💻",
      "You are in right on time — let's make today smooth ✨",
    ]);

  else if (time < 10.85)
    greeting = pick([
      "Morning momentum is building — pick the most important thing first 🎯",
      "Good start — clear the small stuff before tea time ⚡",
      "First focus block of the day — make it count 🚀",
    ]);

  else if (time < 11.25)
    greeting = pick([
      "Morning tea time — quick sip, quick reset ☕",
      "Tea break checkpoint — breathe, stretch, continue 🍵",
      "Tiny pause, better focus — enjoy the tea ☕",
    ]);

  else if (time < 12.75)
    greeting = pick([
      "Late morning focus — this is prime work time 🎯",
      "Tea is done, focus is back — let's move cleanly ⚡",
      "Good window for deep work — one solid task at a time 💻",
    ]);

  else if (time < 13.5)
    greeting = pick([
      "Lunch is close — finish one clean checkpoint first 🍱",
      "Almost lunch time — land the current task smoothly ✅",
      "Pre-lunch push — small win, then food 😄",
    ]);

  else if (time < 14.5)
    greeting = pick([
      "Lunch time — recharge properly 🍱",
      "Good pause for lunch — step away and refuel 🥗",
      "Lunch break mode — you have earned the reset 🍽️",
    ]);

  else if (time < 15.75)
    greeting = pick([
      "Back from lunch — slow start, steady finish 💪",
      "Post-lunch restart — keep it simple and moving 🌤️",
      "Afternoon engine warming up — one task at a time ⚙️",
    ]);

  else if (time < 16.25)
    greeting = pick([
      "Coffee time — perfect moment for a quick reset ☕",
      "Four o'clock coffee checkpoint — refuel and resume ☕",
      "Coffee break energy — then one more strong block ⚡",
    ]);

  else if (time < 18.25)
    greeting = pick([
      "Evening focus block — finish the important bits cleanly 🔥",
      "Coffee has entered the chat — close the day strong 💪",
      "Late afternoon push — tidy progress beats noisy progress ✅",
    ]);

  else if (time < 19.5)
    greeting = pick([
      "Wrap-up window — note the loose ends and land softly 🌇",
      "Day is winding down — clean handoff to tomorrow ✅",
      "Almost done — close the loop on today's work 🧭",
    ]);

  else if (time < 20)
    greeting = pick([
      "Office time is ending — good work today 🌆",
      "Time to call it a day soon — you did enough for today 👏",
      "End-of-day mode — save, sync, and breathe 🌙",
    ]);

  else if (time < 22)
    greeting = pick([
      "Still working late — keep it light and protect your energy 🌙",
      "After-hours mode — only the important things now 🧘",
      "Long day, still steady — wrap soon if you can ✨",
    ]);

  else
    greeting = pick([
      "Late night check-in — get some rest soon 😴",
      "That is enough for today — sleep will help more now 🌙",
      "Very late, brave soul — tomorrow needs you rested 💤",
    ]);

  return firstName ? `${greeting}, ${firstName} 👋` : greeting;
}

const RAW_STATUS_TO_MEETING_STATUS: Record<string, MeetingStatus> = {
  // ── active statuses ──────────────────────────────────────────────────────
  "pending": "pending",
  "live": "live",
  "processing": "processing",
  "bot.joining_call": "bot_created",
  "bot.in_waiting_room": "in_lobby",
  "bot.in_call_not_recording": "live",
  "bot.in_call_recording": "live",
  "recording.done": "processing",
  "transcript.processing": "processing",

  // ── failed statuses ──────────────────────────────────────────────────────
  "abort": "abort",
  "not_admitted": "not_admitted",
  "too_short": "too_short",
  "bot.fatal": "failed",
  "recording.failed": "failed",
  "transcript.failed": "failed",

  // ── completed statuses ───────────────────────────────────────────────────
  "completed": "completed",
  "bot.call_ended": "completed",
  "bot.done": "completed",
  "transcript.done": "completed",

  // ── scheduled ────────────────────────────────────────────────────────────
  "scheduled": "scheduled",
  "recurring.waiting_for_app_confirmation": "scheduled",
  "recurring.waiting_for_calendar_yes": "scheduled",


  // ── legacy / internal ────────────────────────────────────────────────────
  "bot_created": "bot_created",
  "in_lobby": "in_lobby",
  "failed": "failed",
};

const STATUS_LABELS: Record<MeetingStatus, string> = {
  pending: "Pending",
  bot_created: "Bot Created",
  in_lobby: "In Lobby",
  live: "Live",
  not_admitted: "Not Admitted",
  processing: "Processing",
  completed: "Completed",
  too_short: "Too Short",
  abort: "Aborted",
  failed: "Failed",
  scheduled: "Scheduled",
};

const STATUS_API_FILTERS: Partial<Record<MeetingStatus, string>> = {
  bot_created: "bot.joining_call",
  in_lobby: "bot.in_waiting_room",
  live: "bot.in_call_recording",
  processing: "transcript.processing",
  completed: "bot.done",
  failed: "bot.fatal",
  scheduled: "scheduled,recurring.waiting_for_app_confirmation,recurring.waiting_for_calendar_yes",
  not_admitted: "not_admitted",
  too_short: "too_short",
  abort: "abort",
  pending: "pending",
};

export const MEETING_STATUS_FILTER_OPTIONS: Array<{ value: "all" | MeetingStatus; label: string }> = [
  { value: "all", label: "All Status" },
  { value: "pending", label: "Pending" },
  { value: "bot_created", label: "Bot Created" },
  { value: "scheduled", label: "Scheduled" },
  { value: "live", label: "Live" },
  { value: "in_lobby", label: "In Lobby" },
  { value: "not_admitted", label: "Not Admitted" },
  { value: "processing", label: "Transcribing" },
  { value: "completed", label: "Completed" },
  { value: "too_short", label: "Too Short" },
  { value: "abort", label: "Aborted" },
  { value: "failed", label: "Failed" },
];

export function normalizeMeetingStatus(status?: string | null): MeetingStatus {
  if (!status) return "processing";
  return RAW_STATUS_TO_MEETING_STATUS[status] ?? "processing";
}

export function getMeetingStatusApiFilter(status: string): string {
  if (status === "all") return status;
  return STATUS_API_FILTERS[normalizeMeetingStatus(status)] ?? status;
}

export function meetingMatchesStatusFilter(status: string, filter: string): boolean {
  return filter === "all" || normalizeMeetingStatus(status) === normalizeMeetingStatus(filter);
}

export function getMeetingStatusLabel(status: string): string {
  switch (status) {
    case "bot.joining_call": return "Joining";
    case "bot_created": return "Bot Created";
    case "bot.in_waiting_room": return "In Lobby";
    case "bot.in_call_not_recording": return "In Call";
    case "bot.in_call_recording": return "Recording";
    case "bot.call_ended": return "Processing";
    case "recording.done": return "Recording Ready";
    case "transcript.processing": return "Transcribing";
    case "transcript.done": return "Completed";
    case "bot.done": return "Completed";
    case "bot.fatal": return "Failed";
    case "recording.failed": return "Failed";
    case "transcript.failed": return "Failed";
    case "recurring.waiting_for_app_confirmation": return "Scheduled";
    case "recurring.waiting_for_calendar_yes": return "Awaiting RSVP";

    // Fallback for old/internal statuses
    case "pending":
    case "in_lobby":
    case "live":
    case "not_admitted":
    case "processing":
    case "completed":
    case "too_short":
    case "abort":
    case "failed":
    case "scheduled":
    case "bot_created":
      return STATUS_LABELS[normalizeMeetingStatus(status)];

    default: return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
  }
}

export const PLATFORM_ALIASES: Record<string, string> = {
  "google meet": "google_meet",
  "google_meet": "google_meet",
  "googlemeet": "google_meet",
  "microsoft teams": "microsoft_teams",
  "microsoft_teams": "microsoft_teams",
  "microsoftteams": "microsoft_teams",
  "teams": "microsoft_teams",
  "zoom": "zoom",
  "jitsi": "jitsi",
};

export const TYPE_ALIASES: Record<string, string> = {
  "recurring": "recurring",
  "one time": "one_time",
  "one_time": "one_time",
  "onetime": "one_time",
  "one-time": "one_time",
};

export const TIME_ALIASES: Record<string, string> = {
  "today": "today",
  "yesterday": "yesterday",
  "last 7days": "last_7days",
  "last 7 days": "last_7days",
  "last_7days": "last_7days",
  "last7days": "last_7days",
  "last 30days": "last_30days",
  "last 30 days": "last_30days",
  "last_30days": "last_30days",
  "last30days": "last_30days",
};

export const SORT_ALIASES: Record<string, string> = {
  "newest first": "newest_first",
  "newest_first": "newest_first",
  "oldest first": "oldest_first",
  "oldest_first": "oldest_first",
  "title(a-z)": "title_asc",
  "title (a-z)": "title_asc",
  "title_asc": "title_asc",
  "longest first": "longest_first",
  "longest_first": "longest_first",
};

export function getPlatformValue(platform: string): string | undefined {
  if (!platform || platform === "all") return undefined;
  const key = platform.toLowerCase().trim();
  return PLATFORM_ALIASES[key] ?? platform;
}

export function getTypeValue(type: string): string | undefined {
  if (!type || type === "all") return undefined;
  const key = type.toLowerCase().trim();
  return TYPE_ALIASES[key] ?? type;
}

export function getTimeValue(time: string): string | undefined {
  if (!time || time === "all") return undefined;
  const key = time.toLowerCase().trim();
  // Map formats like "7days" to "last 7days" before lookup if needed
  let lookupKey = key;
  if (key === "7days") lookupKey = "last 7days";
  if (key === "30days") lookupKey = "last 30days";
  return TIME_ALIASES[lookupKey] ?? time;
}

export function getSortValue(sort: string): string | undefined {
  if (!sort || sort === "all") return undefined;
  const key = sort.toLowerCase().trim();
  // Map formats like "newest" or "duration_desc"
  let lookupKey = key;
  if (key === "newest") lookupKey = "newest first";
  if (key === "oldest") lookupKey = "oldest first";
  if (key === "duration_desc") lookupKey = "longest first";
  return SORT_ALIASES[lookupKey] ?? sort;
}

export function getAuthToken(): string | null {
  if (typeof window === "undefined") return null;
  let token = sessionStorage.getItem("auth_token");
  if (!token) {
    const match = document.cookie.match(/(^|;\s*)auth_token=([^;]*)/);
    token = match ? decodeURIComponent(match[2]) : null;
    if (token) {
      sessionStorage.setItem("auth_token", token);
    }
  }
  return token;
}

