"use client";

import { useState, useEffect } from 'react';
import { Phone, PhoneOff } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { OutlookNotification, OutlookNotificationData } from '@/components/outlook-notification';

export interface IncomingCall {
  from: {
    userId: string;
    username: string;
    name: string;
  };
  roomId: string;
  roomName: string;
  timestamp: Date;
}

interface IncomingCallNotificationProps {
  call: IncomingCall | null;
  onDismiss: () => void;
  onAccept: (roomId: string) => void;
  onReject: () => void;
}

export function IncomingCallNotification({
  call,
  onDismiss,
  onAccept,
  onReject,
}: IncomingCallNotificationProps) {
  const router = useRouter();
  const [notificationData, setNotificationData] = useState<OutlookNotificationData | null>(null);

  useEffect(() => {
    if (call) {
      console.log('[IncomingCallNotification] 📞 Call received, showing notification', {
        from: call.from.name || call.from.username,
        roomId: call.roomId,
      });

      const callerName = call.from.name || call.from.username || 'Inconnu';
      
      const notification: OutlookNotificationData = {
        id: `call-${call.roomId}-${Date.now()}`,
        source: 'call',
        title: 'Parole',
        subtitle: 'Appel entrant',
        message: `Vous avez un appel de ${callerName}${call.roomName && call.roomName !== callerName ? ` dans ${call.roomName}` : ''}`,
        icon: Phone,
        iconColor: 'text-blue-600',
        iconBgColor: 'bg-blue-100',
        borderColor: 'border-blue-500',
        timestamp: call.timestamp,
        autoDismiss: 30000, // 30 seconds
        actions: [
          {
            label: 'Accepter',
            onClick: () => {
              onAccept(call.roomId);
              router.push(`/parole?room=${call.roomId}`);
              setNotificationData(null);
            },
            variant: 'default',
            className: 'bg-green-600 hover:bg-green-700 text-white',
            icon: Phone,
          },
          {
            label: 'Raccrocher',
            onClick: () => {
              onReject();
              setNotificationData(null);
            },
            variant: 'destructive',
            icon: PhoneOff,
          },
        ],
      };

      setNotificationData(notification);
    } else {
      setNotificationData(null);
    }
  }, [call, router, onAccept, onReject]);

  if (!notificationData) {
    return null;
  }

  return (
    <OutlookNotification
      notification={notificationData}
      onDismiss={() => {
        onDismiss();
        setNotificationData(null);
      }}
    />
  );
}
