'use client';

import { useEffect, useRef } from 'react';
import { X, Phone, MessageSquare, Users, Clock, CalendarDays, MapPin, Zap, FileText, ChevronRight, BellRing, Edit3, Printer, Star,  } from 'lucide-react';
import StatusBadge from '@client/components/ui/StatusBadge';
import { toast } from 'sonner';
import { useLanguage } from '@client/contexts/LanguageContext';

export interface Reservation {
  id: string;
  guestName: string;
  guestPhone: string;
  guestEmail?: string;
  channel: 'voice' | 'chat';
  status: string;
  partySize: number;
  date: string;
  time: string;
  tableNumber: string;
  zone: string;
  specialRequests?: string;
  occasion?: string;
  dietaryNeeds?: string[];
  aiNotes?: string;
  aiConfidence?: number | null;
  confirmedAt?: string;
  reminderSent: boolean;
  conversationId: string;
  agentId: string;
  isVip: boolean;
  confirmationChannel: 'sms' | 'email' | 'both' | 'none';
}

const getConfidenceColor = (score: number) => {
  if (score >= 90) return { color: 'hsl(var(--success))', bg: 'hsl(var(--success-bg))', border: 'hsl(var(--success-border))' };
  if (score >= 70) return { color: 'hsl(var(--warning))', bg: 'hsl(var(--warning-bg))', border: 'hsl(var(--warning-border))' };
  return { color: 'hsl(var(--danger))', bg: 'hsl(var(--danger-bg))', border: 'hsl(var(--danger-border))' };
};

const VOICE_BOOKING_COLORS = { color: 'hsl(var(--success))', bg: 'hsl(var(--success-bg))', border: 'hsl(var(--success-border))' };

interface BookingDetailModalProps {
  reservation: Reservation | null;
  isOpen: boolean;
  onClose: () => void;
  onStatusChange: (id: string, status: string) => void;
}

export default function BookingDetailModal({ reservation, isOpen, onClose, onStatusChange }: BookingDetailModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);
  const { t } = useLanguage();

  const statusOptions = [
    { value: 'processing', label: t('tableBooking.status.processing', 'AI Processing') },
    { value: 'confirmed', label: t('tableBooking.status.confirmed', 'Confirmed') },
    { value: 'reminder_sent', label: t('tableBooking.status.reminderSent', 'Reminder Sent') },
    { value: 'seated', label: t('tableBooking.status.seated', 'Seated') },
    { value: 'noshow', label: t('tableBooking.status.noShow', 'No Show') },
    { value: 'cancelled', label: t('tableBooking.status.cancelled', 'Cancelled') },
  ];

  useEffect(() => {
    if (isOpen) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  if (!isOpen || !reservation) return null;

  const hasConfidence = reservation.aiConfidence != null;
  const confColors = hasConfidence ? getConfidenceColor(reservation.aiConfidence as number) : VOICE_BOOKING_COLORS;
  const isVoiceBooking = !hasConfidence && reservation.channel === 'voice';

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-start justify-end"
      style={{ backgroundColor: 'rgba(0,0,0,0.4)' }}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div
        className="h-full w-full max-w-lg overflow-y-auto scrollbar-thin slide-in-right"
        style={{
          backgroundColor: 'hsl(var(--surface))',
          borderLeft: '1px solid hsl(var(--border))',
          boxShadow: 'var(--shadow-xl)',
        }}
      >
        {/* Header */}
        <div
          className="sticky top-0 z-10 flex items-center justify-between px-6 py-4"
          style={{ backgroundColor: 'hsl(var(--surface))', borderBottom: '1px solid hsl(var(--border))' }}
        >
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-base font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                {reservation.id}
              </h2>
              <StatusBadge status={reservation.status} />
              {reservation.isVip && (
                <span className="badge badge-warning">
                  <Star size={10} />
                  {t('tableBooking.vip', 'VIP')}
                </span>
              )}
            </div>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {reservation.date} · {reservation.time}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={() => toast.info(t('tableBooking.printing', 'Printing booking {id}', { id: reservation.id }))} className="btn-ghost p-2" title={t('tableBooking.printTitle', 'Print booking')}>
              <Printer size={16} />
            </button>
            <button onClick={() => toast.info(t('tableBooking.editing', 'Edit booking {id}', { id: reservation.id }))} className="btn-ghost p-2" title={t('tableBooking.editTitle', 'Edit booking')}>
              <Edit3 size={16} />
            </button>
            <button onClick={onClose} className="btn-ghost p-2" title={t('common.close', 'Close')}>
              <X size={16} />
            </button>
          </div>
        </div>

        <div className="px-6 py-5 space-y-5">
          {/* AI Confidence */}
          <div
            className="flex items-center justify-between p-3 rounded-xl"
            style={{ backgroundColor: confColors.bg, border: `1px solid ${confColors.border}` }}
          >
            <div className="flex items-center gap-2">
              <Zap size={15} style={{ color: confColors.color }} />
              <span className="text-sm font-semibold" style={{ color: confColors.color }}>
                {t('tableBooking.aiConfidence', 'AI Confidence Score')}
              </span>
            </div>
            {isVoiceBooking ? (
              <span className="flex items-center gap-1.5 text-xs font-bold px-2 py-1 rounded-lg" style={{ backgroundColor: confColors.color + '22', color: confColors.color }}>
                <Phone size={11} /> {t('tableBooking.voiceBooking', 'Voice Booking')}
              </span>
            ) : (
              <div className="flex items-center gap-3">
                <div className="w-24 h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--border))' }}>
                  <div className="h-full rounded-full" style={{ width: `${reservation.aiConfidence}%`, backgroundColor: confColors.color }} />
                </div>
                <span className="font-mono font-bold tabular-nums text-sm" style={{ color: confColors.color }}>
                  {reservation.aiConfidence}%
                </span>
              </div>
            )}
          </div>

          {/* Guest info */}
          <div>
            <p className="section-label mb-3">{t('tableBooking.guestDetails', 'Guest Details')}</p>
            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 rounded-xl col-span-2" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                      {reservation.guestName}
                    </p>
                    <p className="text-xs font-mono mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {reservation.guestPhone}
                    </p>
                    {reservation.guestEmail && (
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {reservation.guestEmail}
                      </p>
                    )}
                  </div>
                  {reservation.isVip && (
                    <span className="badge badge-warning">
                      <Star size={10} /> {t('tableBooking.vipGuest', 'VIP Guest')}
                    </span>
                  )}
                </div>
              </div>

              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.partySize', 'Party Size')}</p>
                <div className="flex items-center gap-2">
                  <Users size={14} style={{ color: 'hsl(var(--primary))' }} />
                  <p className="text-sm font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                    {t('tableBooking.guestsCount', '{count} guests', { count: reservation.partySize })}
                  </p>
                </div>
              </div>

              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.channel', 'Channel')}</p>
                <div className="flex items-center gap-2">
                  {reservation.channel === 'voice'
                    ? <Phone size={14} style={{ color: 'hsl(var(--primary))' }} />
                    : <MessageSquare size={14} style={{ color: 'hsl(var(--info))' }} />
                  }
                  <p className="text-sm font-semibold capitalize" style={{ color: 'hsl(var(--foreground))' }}>
                    {reservation.channel === 'voice' ? t('tableBooking.channels.voice', 'Voice') : t('tableBooking.channels.chat', 'Chat')}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Table & timing */}
          <div>
            <p className="section-label mb-3">{t('tableBooking.reservationDetails', 'Reservation Details')}</p>
            <div className="grid grid-cols-3 gap-3">
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.date', 'Date')}</p>
                <div className="flex items-center gap-1.5">
                  <CalendarDays size={13} style={{ color: 'hsl(var(--primary))' }} />
                  <p className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{reservation.date}</p>
                </div>
              </div>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.time', 'Time')}</p>
                <div className="flex items-center gap-1.5">
                  <Clock size={13} style={{ color: 'hsl(var(--primary))' }} />
                  <p className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{reservation.time}</p>
                </div>
              </div>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.table', 'Table')}</p>
                <div className="flex items-center gap-1.5">
                  <MapPin size={13} style={{ color: 'hsl(var(--primary))' }} />
                  <p className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                    #{reservation.tableNumber} · {reservation.zone}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Occasion & dietary */}
          {(reservation.occasion || (reservation.dietaryNeeds && reservation.dietaryNeeds.length > 0)) && (
            <div className="space-y-3">
              {reservation.occasion && (
                <div
                  className="flex items-center gap-2 p-3 rounded-xl"
                  style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsl(22, 89%, 85%)' }}
                >
                  <Star size={14} style={{ color: 'hsl(var(--primary))' }} />
                  <div>
                    <p className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>{t('tableBooking.specialOccasion', 'Special Occasion')}</p>
                    <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{reservation.occasion}</p>
                  </div>
                </div>
              )}
              {reservation.dietaryNeeds && reservation.dietaryNeeds.length > 0 && (
                <div>
                  <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.dietaryRequirements', 'Dietary Requirements')}</p>
                  <div className="flex flex-wrap gap-2">
                    {reservation.dietaryNeeds.map((d) => (
                      <span key={d} className="badge badge-warning">{d}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Special requests */}
          {reservation.specialRequests && (
            <div
              className="p-3 rounded-xl"
              style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}
            >
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--warning))' }}>{t('tableBooking.specialRequests', 'Special Requests')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}>{reservation.specialRequests}</p>
            </div>
          )}

          {/* AI notes */}
          {reservation.aiNotes && (
            <div>
              <p className="section-label mb-2">{t('tableBooking.aiNotes', 'AI Booking Notes')}</p>
              <div
                className="p-3 rounded-xl"
                style={{ backgroundColor: 'hsl(var(--info-bg))', border: '1px solid hsl(var(--info-border))' }}
              >
                <div className="flex items-center gap-2 mb-1.5">
                  <FileText size={13} style={{ color: 'hsl(var(--info))' }} />
                  <span className="text-xs font-semibold" style={{ color: 'hsl(var(--info))' }}>
                    {reservation.conversationId}
                  </span>
                </div>
                <p className="text-xs leading-relaxed" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                  {reservation.aiNotes}
                </p>
                <button
                  className="mt-2 text-xs font-semibold flex items-center gap-1"
                  style={{ color: 'hsl(var(--info))' }}
                  onClick={() => toast.info(t('tableBooking.openingTranscript', 'Opening full transcript viewer'))}
                >
                  {t('tableBooking.viewFullTranscript', 'View full transcript')} <ChevronRight size={11} />
                </button>
              </div>
            </div>
          )}

          {/* Confirmation status */}
          <div>
            <p className="section-label mb-2">{t('tableBooking.confirmation', 'Confirmation')}</p>
            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.reminderSent', 'Reminder Sent')}</p>
                <div className="flex items-center gap-2">
                  <BellRing size={13} style={{ color: reservation.reminderSent ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }} />
                  <p className="text-sm font-semibold" style={{ color: reservation.reminderSent ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                    {reservation.reminderSent ? t('common.yes', 'Yes') : t('common.notYet', 'Not yet')}
                  </p>
                </div>
              </div>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('tableBooking.sentVia', 'Sent via')}</p>
                <p className="text-sm font-semibold capitalize" style={{ color: 'hsl(var(--foreground))' }}>
                  {reservation.confirmationChannel === 'none' ? '—' : (
                    reservation.confirmationChannel === 'sms' ? t('common.sms', 'SMS') : 
                    reservation.confirmationChannel === 'email' ? t('common.email', 'Email') :
                    reservation.confirmationChannel === 'both' ? t('common.both', 'Both') : reservation.confirmationChannel
                  )}
                </p>
              </div>
            </div>
            {!reservation.reminderSent && (
              <button
                className="btn-secondary w-full mt-2 justify-center"
                onClick={() => toast.success(t('tableBooking.reminderSentTo', 'Reminder sent to {name}', { name: reservation.guestName }))}
              >
                <BellRing size={14} />
                {t('tableBooking.sendReminderNow', 'Send Reminder Now')}
              </button>
            )}
          </div>

          {/* Update status */}
          <div>
            <p className="section-label mb-2">{t('tableBooking.updateStatus', 'Update Status')}</p>
            <div className="grid grid-cols-2 gap-2">
              {statusOptions.map((s) => (
                <button
                  key={s.value}
                  onClick={() => {
                    onStatusChange(reservation.id, s.value);
                    toast.success(t('tableBooking.statusUpdated', 'Booking {id} status updated to {status}', { id: reservation.id, status: s.label }));
                    onClose();
                  }}
                  className="px-3 py-2 rounded-lg text-xs font-semibold text-left transition-all duration-150 hover:scale-[1.02] active:scale-[0.98]"
                  style={{
                    backgroundColor: reservation.status === s.value ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                    color: reservation.status === s.value ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                    border: `1px solid ${reservation.status === s.value ? 'hsl(var(--primary))' : 'hsl(var(--border))'}`,
                  }}
                >
                  {s.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}