'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

export default function IncomingCallWrapper() {
  const { socket } = useSocket();
  const user = useAuthStore((state) => state.user);
  const router = useRouter();
  const [incomingCall, setIncomingCall] = useState(null);

  useEffect(() => {
    if (!socket || !user?.id) return;

    const handleIncomingCall = ({ roomId }) => {
      setIncomingCall({ roomId });
    };

    socket.on('incoming-call', handleIncomingCall);

    return () => {
      socket.off('incoming-call', handleIncomingCall);
    };
  }, [socket, user?.id]);

  const handleJoin = () => {
    if (!incomingCall) return;
    router.push(
      `/video-call?roomId=${incomingCall.roomId}&participantName=${encodeURIComponent(
        `${user?.firstName} ${user?.lastName}`
      )}`
    );
    setIncomingCall(null);
  };

  return (
    <Dialog open={!!incomingCall}>
      <DialogContent className="bg-white text-center space-y-4 p-6 rounded-xl shadow-xl">
        <DialogTitle className="text-lg font-semibold">
          Incoming Video Call
        </DialogTitle>
        <p className="text-sm text-gray-600">You have a video call invitation.</p>
        <div className="flex justify-center gap-4 pt-2">
          <Button
            onClick={handleJoin}
            className="bg-blue-600 hover:bg-blue-700 text-white"
          >
            Join Call
          </Button>
          <Button
            variant="outline"
            onClick={() => setIncomingCall(null)}
            className="border-gray-300"
          >
            Dismiss
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
