'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import Link from 'next/link';
import { ShoppingBag, CalendarDays, AlertTriangle, X, Check, Volume2, Clock, ChevronRight } from 'lucide-react';

type AlertType = 'order' | 'booking' | 'escalation';

interface Alert {
  id: string;
  type: AlertType;
  title: string;
  subtitle: string;
  details: string[];
  timestamp: string;
  countdown: number;
  acceptDisabled?: boolean;
  acceptLabel?: string;
}

interface AlertOverlayProps {
  alerts?: Alert[];
  onDismiss?: (id: string) => void;
  onAccept?: (id: string) => void;
  soundEnabled?: boolean;
  volume?: number;
}

function playAlertSound(volume: number = 70) {
  try {
    const w = window as Window & { webkitAudioContext?: typeof AudioContext };
    const AudioCtx = window.AudioContext || w.webkitAudioContext;
    if (!AudioCtx) return;
    const ctx = new AudioCtx();
    const gain = ctx.createGain();
    gain.gain.value = Math.max(0, Math.min(1, volume / 100));
    gain.connect(ctx.destination);
    const osc1 = ctx.createOscillator();
    osc1.type = 'sine';
    osc1.frequency.value = 880;
    osc1.connect(gain);
    osc1.start(ctx.currentTime);
    osc1.stop(ctx.currentTime + 0.12);
    const osc2 = ctx.createOscillator();
    osc2.type = 'sine';
    osc2.frequency.value = 1100;
    osc2.connect(gain);
    osc2.start(ctx.currentTime + 0.15);
    osc2.stop(ctx.currentTime + 0.27);
    setTimeout(() => ctx.close(), 500);
  } catch {}
}

function SingleAlert({ alert, onDismiss, onAccept }: { alert: Alert; onDismiss: (id: string) => void; onAccept: (id: string) => void }) {
  const [countdown, setCountdown] = useState(alert.countdown);

  useEffect(() => {
    if (countdown <= 0) { onDismiss(alert.id); return; }
    const t = setTimeout(() => setCountdown(c => c - 1), 1000);
    return () => clearTimeout(t);
  }, [countdown, alert.id, onDismiss]);

  const color = alert.type === 'order' ? 'hsl(22, 89%, 48%)' : alert.type === 'escalation' ? 'hsl(0, 72%, 51%)' : 'hsl(210, 100%, 40%)';
  const bg = alert.type === 'order' ? 'hsl(22, 100%, 96%)' : alert.type === 'escalation' ? 'hsl(0, 100%, 97%)' : 'hsl(210, 100%, 96%)';
  const Icon = alert.type === 'order' ? ShoppingBag : alert.type === 'escalation' ? AlertTriangle : CalendarDays;
  const href = alert.type === 'order' ? '/order-management' : alert.type === 'escalation' ? '/conversations' : '/table-booking-management';

  return (
    <div
      className="w-80 rounded-2xl overflow-hidden shadow-xl"
      style={{
        backgroundColor: 'hsl(var(--surface))',
        border: `2px solid ${color}`,
        boxShadow: `0 8px 32px ${color}30, 0 4px 12px rgba(0,0,0,0.12)`,
        animation: 'slideInRight 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)',
      }}
    >
      <div className="flex items-center gap-3 px-4 py-3" style={{ backgroundColor: bg, borderBottom: `1px solid ${color}30` }}>
        <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: color }}>
          <Icon size={15} className="text-white" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-bold truncate" style={{ color: 'hsl(var(--foreground))' }}>{alert.title}</p>
          <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{alert.subtitle}</p>
        </div>
        <div className="flex items-center gap-1.5">
          <Volume2 size={13} style={{ color }} />
          <button onClick={() => onDismiss(alert.id)} className="p-1 rounded-lg hover:bg-black/10 transition-colors">
            <X size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
          </button>
        </div>
      </div>

      <div className="px-4 py-3">
        <ul className="space-y-1">
          {alert.details.map((d, i) => (
            <li key={i} className="flex items-center gap-2 text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              <span className="w-1 h-1 rounded-full shrink-0" style={{ backgroundColor: color }} />
              {d}
            </li>
          ))}
        </ul>
      </div>

      <div className="px-4 pb-1">
        <div className="flex items-center justify-between mb-1">
          <span className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <Clock size={11} /> Auto-dismiss in {countdown}s
          </span>
          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{alert.timestamp}</span>
        </div>
        <div className="h-1 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--border))' }}>
          <div
            className="h-full rounded-full transition-all"
            style={{
              width: `${(countdown / alert.countdown) * 100}%`,
              backgroundColor: color,
              transition: 'width 1s linear',
            }}
          />
        </div>
      </div>

      <div className="flex gap-2 px-4 py-3">
        {!alert.acceptDisabled && (
          <button
            className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold transition-all hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ backgroundColor: color, color: 'white' }}
            onClick={() => onAccept(alert.id)}
          >
            <Check size={13} /> {alert.acceptLabel || 'Accept'}
          </button>
        )}
        <Link
          href={href}
          className="flex items-center justify-center gap-1 px-3 py-2 rounded-xl text-xs font-semibold transition-all"
          style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}
          onClick={() => onDismiss(alert.id)}
        >
          View <ChevronRight size={12} />
        </Link>
        <button
          className="px-3 py-2 rounded-xl text-xs font-semibold transition-all"
          style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}
          onClick={() => onDismiss(alert.id)}
        >
          Dismiss
        </button>
      </div>
    </div>
  );
}

export default function AlertOverlay({ alerts = [], onDismiss, onAccept, soundEnabled, volume }: AlertOverlayProps) {
  const [activeAlerts, setActiveAlerts] = useState<Alert[]>(alerts);
  const prevCountRef = useRef(0);

  useEffect(() => {
    if (alerts.length > prevCountRef.current) {
      if (soundEnabled !== false) {
        playAlertSound(typeof volume === 'number' ? volume : 70);
      }
    }
    prevCountRef.current = alerts.length;
    setActiveAlerts(alerts);
  }, [alerts, soundEnabled, volume]);

  const handleDismiss = useCallback((id: string) => {
    setActiveAlerts(prev => prev.filter(a => a.id !== id));
    onDismiss?.(id);
  }, [onDismiss]);

  const handleAccept = useCallback((id: string) => {
    setActiveAlerts(prev => prev.filter(a => a.id !== id));
    onAccept?.(id);
  }, [onAccept]);

  if (activeAlerts.length === 0) return null;

  return (
    <>
      <style>{`
        @keyframes slideInRight {
          from { transform: translateX(120%); opacity: 0; }
          to { transform: translateX(0); opacity: 1; }
        }
      `}</style>
      <div className="fixed bottom-6 right-6 z-50 flex flex-col gap-3 items-end">
        {activeAlerts.map(alert => (
          <SingleAlert key={alert.id} alert={alert} onDismiss={handleDismiss} onAccept={handleAccept} />
        ))}
      </div>
    </>
  );
}
