'use client';

import { useState, useEffect } from 'react';
import { CalendarDays, Users, Clock, CheckCircle2, XCircle, BellRing } from 'lucide-react';
import { listBookings, type Booking } from '@client/api/bookings';
import { useLanguage } from '@client/contexts/LanguageContext';

interface SummaryStat {
  label: string;
  value: string;
  sub: string;
  icon: React.ReactNode;
  iconBg: string;
  iconColor: string;
  positive: boolean;
}

function buildStats(bookings: Booking[], t: (key: string, fallback: string, vars?: any) => string): SummaryStat[] {
  const total = bookings.length;
  const confirmed = bookings.filter(b => b.status === 'confirmed').length;
  const noShows = bookings.filter(b => b.status === 'noshow').length;
  const covers = bookings.reduce((sum, b) => sum + b.partySize, 0);
  const reminderSent = bookings.filter(b => b.status === 'reminder_sent').length;

  const upcoming = bookings
    .filter(b => b.status === 'confirmed' || b.status === 'reminder_sent')
    .sort((a, b) => a.time.localeCompare(b.time));
  const next = upcoming[0];
  const nextLabel = next ? next.time : t('common.none', 'None');
  const nextSub = next ? t('tableBooking.summary.nextSub', '{{name}} · {{count}} guests', { name: next.guestName, count: next.partySize }) : t('tableBooking.summary.noUpcoming', 'No upcoming');

  return [
    { label: t('tableBooking.summary.totalToday', 'Total Bookings Today'), value: String(total), sub: t('tableBooking.summary.totalSub', '{{count}} reservations', { count: total }), icon: <CalendarDays size={16} />, iconBg: 'hsl(var(--info-bg))', iconColor: 'hsl(var(--info))', positive: true },
    { label: t('tableBooking.summary.coversToday', 'Covers Today'), value: String(covers), sub: t('tableBooking.summary.coversSub', '{{count}} confirmed tables', { count: confirmed }), icon: <Users size={16} />, iconBg: 'hsl(var(--primary-light))', iconColor: 'hsl(var(--primary))', positive: true },
    { label: t('tableBooking.summary.nextReservation', 'Next Reservation'), value: nextLabel, sub: nextSub, icon: <Clock size={16} />, iconBg: 'hsl(var(--warning-bg))', iconColor: 'hsl(var(--warning))', positive: true },
    { label: t('tableBooking.status.confirmed', 'Confirmed'), value: String(confirmed), sub: t('tableBooking.summary.confirmedSub', 'Confirmed for today'), icon: <CheckCircle2 size={16} />, iconBg: 'hsl(var(--success-bg))', iconColor: 'hsl(var(--success))', positive: true },
    { label: t('tableBooking.summary.noShowsToday', 'No-Shows Today'), value: String(noShows), sub: t('tableBooking.summary.noShowsSub', '{{count}} no-show{{plural}}', { count: noShows, plural: noShows !== 1 ? 's' : '' }), icon: <XCircle size={16} />, iconBg: 'hsl(var(--danger-bg))', iconColor: 'hsl(var(--danger))', positive: noShows === 0 },
    { label: t('tableBooking.summary.remindersSent', 'Reminders Sent'), value: String(reminderSent), sub: t('tableBooking.summary.pendingSub', '{{count}} pending', { count: total - confirmed - noShows - reminderSent }), icon: <BellRing size={16} />, iconBg: 'hsl(var(--muted))', iconColor: 'hsl(var(--muted-foreground))', positive: true },
  ];
}

export default function BookingSummaryStrip() {
  const [stats, setStats] = useState<SummaryStat[]>([]);
  const [loading, setLoading] = useState(true);
  const { t } = useLanguage();

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

  if (loading) {
    return (
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 xl:grid-cols-6 2xl:grid-cols-6 gap-3 mb-5">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} className="card px-4 py-3 flex items-center gap-3 animate-pulse">
            <div className="w-8 h-8 rounded-lg bg-gray-200" />
            <div>
              <div className="h-3 w-16 bg-gray-200 rounded mb-1" />
              <div className="h-5 w-10 bg-gray-200 rounded" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 xl:grid-cols-6 2xl:grid-cols-6 gap-3 mb-5">
      {stats.map(stat => (
        <div key={stat.label} className="card px-4 py-3 flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: stat.iconBg, color: stat.iconColor }}>
            {stat.icon}
          </div>
          <div className="min-w-0">
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
            <p className="text-base font-bold font-mono tabular-nums leading-tight" style={{ color: 'hsl(var(--foreground))' }}>{stat.value}</p>
            <p className="text-xs truncate" style={{ color: stat.positive ? 'hsl(var(--success))' : 'hsl(var(--danger))' }}>{stat.sub}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
