import { useState, useEffect, useMemo } from 'react';
import type { TradeEvent } from '../crm/types';

export type EventStatus = 'upcoming' | 'ongoing' | 'ended';

export interface EventCountdown {
  status: EventStatus;
  label: string;
  daysUntil: number;
  hoursUntil: number;
  currentDay: number;
  totalDays: number;
  progressPercent: number;
}

function calcCountdown(event: TradeEvent, now: Date): EventCountdown {
  const start = new Date(event.startDate);
  const end = new Date(event.endDate);

  // Normalize to start-of-day for day calculations
  const startDay = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const endDay = new Date(end.getFullYear(), end.getMonth(), end.getDate());
  endDay.setHours(23, 59, 59, 999);
  const nowDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  const msPerDay = 86_400_000;
  const totalDays = Math.round((endDay.getTime() - startDay.getTime()) / msPerDay) + 1;

  if (now < startDay) {
    // Upcoming
    const diffMs = startDay.getTime() - now.getTime();
    const daysUntil = Math.ceil(diffMs / msPerDay);
    const hoursUntil = Math.ceil(diffMs / 3_600_000);

    let label: string;
    if (daysUntil > 2) {
      label = `Noch ${daysUntil} Tage`;
    } else if (daysUntil === 2) {
      label = `Noch 2 Tage`;
    } else if (daysUntil === 1) {
      label = 'Morgen';
    } else {
      label = `Noch ${hoursUntil} Std.`;
    }

    return {
      status: 'upcoming',
      label,
      daysUntil,
      hoursUntil,
      currentDay: 0,
      totalDays,
      progressPercent: 0,
    };
  }

  if (now <= endDay) {
    // Ongoing
    const currentDay =
      Math.floor((nowDay.getTime() - startDay.getTime()) / msPerDay) + 1;
    const progressPercent = Math.min(
      100,
      Math.round((currentDay / totalDays) * 100),
    );

    return {
      status: 'ongoing',
      label: `Tag ${currentDay} von ${totalDays}`,
      daysUntil: 0,
      hoursUntil: 0,
      currentDay,
      totalDays,
      progressPercent,
    };
  }

  // Ended
  return {
    status: 'ended',
    label: 'Beendet',
    daysUntil: 0,
    hoursUntil: 0,
    currentDay: totalDays,
    totalDays,
    progressPercent: 100,
  };
}

/**
 * Hook that computes a live countdown for a trade event.
 * Updates every 60 seconds.
 */
export function useEventCountdown(event: TradeEvent): EventCountdown {
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 60_000);
    return () => clearInterval(timer);
  }, []);

  return useMemo(() => calcCountdown(event, now), [event, now]);
}
