'use client';

import { useState, useEffect } from 'react';
import { Users, Phone, MessageSquare, Star, Clock } from 'lucide-react';
import { listBookings, type Booking } from '@client/api/bookings';
import { useLanguage } from '@client/contexts/LanguageContext';

interface TimeSlot {
  time: string;
  reservations: {
    id: string;
    guest: string;
    party: number;
    table: string;
    status: string;
    channel: string;
    isVip: boolean;
  }[];
}

const statusColors: Record<string, { bg: string; border: string; text: string }> = {
  confirmed: { bg: 'hsl(var(--success-bg))', border: 'hsl(var(--success-border))', text: 'hsl(var(--success))' },
  reminder_sent: { bg: 'hsl(var(--info-bg))', border: 'hsl(var(--info-border))', text: 'hsl(var(--info))' },
  seated: { bg: 'hsl(var(--primary-light))', border: 'hsl(22, 89%, 85%)', text: 'hsl(var(--primary))' },
  escalated: { bg: 'hsl(var(--danger-bg))', border: 'hsl(var(--danger-border))', text: 'hsl(var(--danger))' },
  noshow: { bg: 'hsl(var(--danger-bg))', border: 'hsl(var(--danger-border))', text: 'hsl(var(--danger))' },
  cancelled: { bg: 'hsl(var(--muted))', border: 'hsl(var(--border))', text: 'hsl(var(--muted-foreground))' },
  pending: { bg: 'hsl(var(--warning-bg))', border: 'hsl(var(--warning-border))', text: 'hsl(var(--warning))' },
  completed: { bg: 'hsl(var(--success-bg))', border: 'hsl(var(--success-border))', text: 'hsl(var(--success))' },
};

function groupByTimeSlot(bookings: Booking[]): TimeSlot[] {
  const slotMap: Record<string, TimeSlot['reservations']> = {};

  for (const b of bookings) {
    const time = b.time || '7:00 PM';
    if (!slotMap[time]) slotMap[time] = [];
    slotMap[time].push({
      id: b.id,
      guest: b.guestName,
      party: b.partySize,
      table: b.tableNumber ?? 'TBD',
      status: b.status,
      channel: b.channel,
      isVip: false,
    });
  }

  return Object.entries(slotMap)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([time, reservations]) => ({ time, reservations }));
}

export default function TimelineView() {
  const { t } = useLanguage();
  const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    listBookings({ date: today, limit: '200' })
      .then(res => setTimeSlots(groupByTimeSlot(res.bookings ?? [])))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const currentHour = new Date().getHours();
  const now = new Date();
  const nowStr = now.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });

  if (loading) {
    return (
      <div className="card p-5 mb-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <p className="section-label">{t('tableBooking.tonightsTimeline', "Tonight's Timeline")}</p>
            <p className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{t('common.loading', 'Loading...')}</p>
          </div>
        </div>
        <div className="flex gap-4 pb-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="flex flex-col gap-2 animate-pulse" style={{ minWidth: '140px' }}>
              <div className="h-7 bg-gray-200 rounded-lg" />
              <div className="h-16 bg-gray-200 rounded-lg" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="card p-5 mb-5">
      <div className="flex items-center justify-between mb-4">
        <div>
          <p className="section-label">{t('tableBooking.tonightsTimeline', "Tonight's Timeline")}</p>
          <p className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>
            {t('tableBooking.reservationsByTimeSlot', 'Reservations by time slot')}
          </p>
        </div>
        <div className="flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full"
          style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))', border: '1px solid hsl(22, 89%, 85%)' }}
        >
          <Clock size={12} />
          {t('common.current', 'Current')}: {nowStr}
        </div>
      </div>

      {timeSlots.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-10 text-center">
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('tableBooking.noReservationsToday', 'No reservations today')}</p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.bookingsWillAppearHere', 'Bookings will appear here as they are made')}</p>
        </div>
      ) : (
        <div className="overflow-x-auto scrollbar-thin">
          <div className="flex gap-4 min-w-max pb-2">
            {timeSlots.map((slot) => {
              const timeMatch = slot.time.match(/(\d+)/);
              const slotHour = timeMatch ? parseInt(timeMatch[1], 10) + (slot.time.toLowerCase().includes('pm') && parseInt(timeMatch[1], 10) !== 12 ? 12 : 0) : 0;
              const isPast = slotHour < currentHour;
              const isCurrent = slotHour === currentHour;

              return (
                <div key={slot.time} className="flex flex-col gap-2" style={{ minWidth: '140px' }}>
                  <div
                    className="flex items-center justify-between px-2 py-1 rounded-lg"
                    style={{
                      backgroundColor: isCurrent ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                      border: `1px solid ${isCurrent ? 'hsl(22, 89%, 85%)' : 'hsl(var(--border))'}`,
                    }}
                  >
                    <span
                      className="text-xs font-bold"
                      style={{ color: isCurrent ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))' }}
                    >
                      {slot.time}
                    </span>
                    {isCurrent && (
                      <span className="w-1.5 h-1.5 rounded-full animate-pulse" style={{ backgroundColor: 'hsl(var(--primary))' }} />
                    )}
                  </div>

                  <div className="space-y-1.5">
                    {slot.reservations.map((res) => {
                      const colors = statusColors[res.status] || statusColors.confirmed;
                      return (
                        <div
                          key={res.id}
                          className="px-2.5 py-2 rounded-lg cursor-pointer transition-all duration-150 hover:scale-[1.02]"
                          style={{
                            backgroundColor: colors.bg,
                            border: `1px solid ${colors.border}`,
                            opacity: isPast && res.status !== 'seated' ? 0.6 : 1,
                          }}
                        >
                          <div className="flex items-center justify-between gap-1 mb-0.5">
                            <p className="text-xs font-semibold truncate" style={{ color: colors.text }}>
                              {res.guest.split(' ')[0]}
                            </p>
                            <div className="flex items-center gap-1 shrink-0">
                              {res.isVip && <Star size={9} style={{ color: 'hsl(var(--warning))' }} />}
                              {res.channel === 'voice'
                                ? <Phone size={9} style={{ color: colors.text, opacity: 0.7 }} />
                                : <MessageSquare size={9} style={{ color: colors.text, opacity: 0.7 }} />
                              }
                            </div>
                          </div>
                          <div className="flex items-center justify-between gap-1">
                            <div className="flex items-center gap-1">
                              <Users size={9} style={{ color: colors.text, opacity: 0.7 }} />
                              <span className="text-xs font-mono tabular-nums" style={{ color: colors.text, opacity: 0.8 }}>
                                {res.party}
                              </span>
                            </div>
                            <span className="text-xs font-mono" style={{ color: colors.text, opacity: 0.7 }}>
                              T{res.table}
                            </span>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  <div className="text-center">
                    <span className="text-xs font-mono tabular-nums" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {slot.reservations.reduce((sum, r) => sum + r.party, 0)} {t('tableBooking.covers', 'covers')}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
