"use client"

import { useState, useEffect, useRef } from "react"
import { useParams, useRouter } from "next/navigation"
import {
  Phone,
  PhoneOff,
  Video,
  VideoOff,
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  RotateCcw,
  Maximize,
  Minimize,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"

interface CallState {
  isConnected: boolean
  isIncoming: boolean
  callType: "audio" | "video"
  duration: number
  isMuted: boolean
  isVideoEnabled: boolean
  isSpeakerEnabled: boolean
  isMinimized: boolean
}

interface User {
  id: string
  firstName: string
  lastName: string
  avatar?: string
}

// Mock user data
const mockUsers: Record<string, User> = {
  "1": {
    id: "1",
    firstName: "Alice",
    lastName: "Johnson",
    avatar: "/diverse-woman-portrait.png",
  },
  "2": {
    id: "2",
    firstName: "Bob",
    lastName: "Smith",
    avatar: "/thoughtful-man.png",
  },
}

export default function CallPage() {
  const params = useParams()
  const router = useRouter()
  const userId = params.userId as string
  const localVideoRef = useRef<HTMLVideoElement>(null)
  const remoteVideoRef = useRef<HTMLVideoElement>(null)
  const localStreamRef = useRef<MediaStream | null>(null)
  const peerConnectionRef = useRef<RTCPeerConnection | null>(null)

  const [callState, setCallState] = useState<CallState>({
    isConnected: false,
    isIncoming: false,
    callType: "video",
    duration: 0,
    isMuted: false,
    isVideoEnabled: true,
    isSpeakerEnabled: true,
    isMinimized: false,
  })

  const currentUser = mockUsers[userId]

  useEffect(() => {
    // Initialize WebRTC
    initializeWebRTC()

    // Start call timer when connected
    let interval: NodeJS.Timeout
    if (callState.isConnected) {
      interval = setInterval(() => {
        setCallState((prev) => ({ ...prev, duration: prev.duration + 1 }))
      }, 1000)
    }

    return () => {
      if (interval) clearInterval(interval)
      cleanup()
    }
  }, [callState.isConnected])

  const initializeWebRTC = async () => {
    try {
      console.log("[v0] Initializing WebRTC connection")

      // Create peer connection
      const configuration = {
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
      }
      peerConnectionRef.current = new RTCPeerConnection(configuration)

      // Get user media
      const stream = await navigator.mediaDevices.getUserMedia({
        video: callState.callType === "video",
        audio: true,
      })

      localStreamRef.current = stream

      if (localVideoRef.current) {
        localVideoRef.current.srcObject = stream
      }

      // Add stream to peer connection
      stream.getTracks().forEach((track) => {
        peerConnectionRef.current?.addTrack(track, stream)
      })

      // Handle remote stream
      peerConnectionRef.current.ontrack = (event) => {
        console.log("[v0] Received remote stream")
        if (remoteVideoRef.current) {
          remoteVideoRef.current.srcObject = event.streams[0]
        }
      }

      // Handle ICE candidates
      peerConnectionRef.current.onicecandidate = (event) => {
        if (event.candidate) {
          console.log("[v0] ICE candidate:", event.candidate)
          // In a real app, send this to the remote peer via signaling server
        }
      }

      // Simulate connection after 2 seconds
      setTimeout(() => {
        setCallState((prev) => ({ ...prev, isConnected: true }))
        console.log("[v0] Call connected")
      }, 2000)
    } catch (error) {
      console.error("[v0] Error initializing WebRTC:", error)
    }
  }

  const cleanup = () => {
    console.log("[v0] Cleaning up WebRTC resources")

    if (localStreamRef.current) {
      localStreamRef.current.getTracks().forEach((track) => track.stop())
    }

    if (peerConnectionRef.current) {
      peerConnectionRef.current.close()
    }
  }

  const toggleMute = () => {
    if (localStreamRef.current) {
      const audioTrack = localStreamRef.current.getAudioTracks()[0]
      if (audioTrack) {
        audioTrack.enabled = callState.isMuted
        setCallState((prev) => ({ ...prev, isMuted: !prev.isMuted }))
        console.log("[v0] Audio muted:", !callState.isMuted)
      }
    }
  }

  const toggleVideo = () => {
    if (localStreamRef.current) {
      const videoTrack = localStreamRef.current.getVideoTracks()[0]
      if (videoTrack) {
        videoTrack.enabled = callState.isVideoEnabled
        setCallState((prev) => ({ ...prev, isVideoEnabled: !prev.isVideoEnabled }))
        console.log("[v0] Video enabled:", !callState.isVideoEnabled)
      }
    }
  }

  const toggleSpeaker = () => {
    setCallState((prev) => ({ ...prev, isSpeakerEnabled: !prev.isSpeakerEnabled }))
    console.log("[v0] Speaker enabled:", !callState.isSpeakerEnabled)
  }

  const switchCamera = async () => {
    try {
      if (localStreamRef.current) {
        const videoTrack = localStreamRef.current.getVideoTracks()[0]
        if (videoTrack) {
          // Get current constraints
          const constraints = videoTrack.getConstraints()
          const currentFacingMode = constraints.facingMode

          // Switch between front and back camera
          const newFacingMode = currentFacingMode === "user" ? "environment" : "user"

          const newStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: newFacingMode },
            audio: true,
          })

          // Replace video track
          const newVideoTrack = newStream.getVideoTracks()[0]
          const sender = peerConnectionRef.current?.getSenders().find((s) => s.track && s.track.kind === "video")

          if (sender) {
            await sender.replaceTrack(newVideoTrack)
          }

          // Update local video
          if (localVideoRef.current) {
            localVideoRef.current.srcObject = newStream
          }

          // Stop old track
          videoTrack.stop()
          localStreamRef.current = newStream

          console.log("[v0] Camera switched to:", newFacingMode)
        }
      }
    } catch (error) {
      console.error("[v0] Error switching camera:", error)
    }
  }

  const endCall = () => {
    console.log("[v0] Ending call")
    cleanup()
    router.push("/chat")
  }

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`
  }

  if (!currentUser) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p>User not found</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-black text-white relative overflow-hidden">
      {/* Remote Video */}
      <div className="absolute inset-0">
        {callState.callType === "video" && callState.isConnected ? (
          <video
            ref={remoteVideoRef}
            autoPlay
            playsInline
            className="w-full h-full object-cover"
            style={{ transform: "scaleX(-1)" }}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/20 to-secondary/20">
            <div className="text-center">
              <Avatar className="h-32 w-32 mx-auto mb-6">
                <AvatarImage
                  src={currentUser.avatar || "/placeholder.svg"}
                  alt={`${currentUser.firstName} ${currentUser.lastName}`}
                />
                <AvatarFallback className="text-4xl">
                  {currentUser.firstName[0]}
                  {currentUser.lastName[0]}
                </AvatarFallback>
              </Avatar>
              <h2 className="text-2xl font-semibold mb-2">
                {currentUser.firstName} {currentUser.lastName}
              </h2>
              <p className="text-lg text-white/70">
                {callState.isConnected ? formatDuration(callState.duration) : "Connecting..."}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Local Video (Picture-in-Picture) */}
      {callState.callType === "video" && callState.isVideoEnabled && !callState.isMinimized && (
        <div className="absolute top-4 right-4 w-32 h-48 bg-black rounded-lg overflow-hidden border-2 border-white/20">
          <video
            ref={localVideoRef}
            autoPlay
            playsInline
            muted
            className="w-full h-full object-cover"
            style={{ transform: "scaleX(-1)" }}
          />
        </div>
      )}

      {/* Call Status */}
      <div className="absolute top-4 left-4">
        <Card className="bg-black/50 border-white/20 text-white">
          <div className="p-3 flex items-center space-x-2">
            <Badge variant="secondary" className="bg-green-500/20 text-green-400 border-green-500/30">
              {callState.isConnected ? "Connected" : "Connecting"}
            </Badge>
            {callState.isConnected && <span className="text-sm font-mono">{formatDuration(callState.duration)}</span>}
          </div>
        </Card>
      </div>

      {/* Call Controls */}
      <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2">
        <Card className="bg-black/50 border-white/20">
          <div className="p-4 flex items-center space-x-4">
            {/* Mute Button */}
            <Button
              variant={callState.isMuted ? "destructive" : "secondary"}
              size="lg"
              className="rounded-full h-14 w-14"
              onClick={toggleMute}
            >
              {callState.isMuted ? <MicOff className="h-6 w-6" /> : <Mic className="h-6 w-6" />}
            </Button>

            {/* Video Toggle (only for video calls) */}
            {callState.callType === "video" && (
              <Button
                variant={callState.isVideoEnabled ? "secondary" : "destructive"}
                size="lg"
                className="rounded-full h-14 w-14"
                onClick={toggleVideo}
              >
                {callState.isVideoEnabled ? <Video className="h-6 w-6" /> : <VideoOff className="h-6 w-6" />}
              </Button>
            )}

            {/* Speaker Toggle */}
            <Button
              variant={callState.isSpeakerEnabled ? "secondary" : "outline"}
              size="lg"
              className="rounded-full h-14 w-14"
              onClick={toggleSpeaker}
            >
              {callState.isSpeakerEnabled ? <Volume2 className="h-6 w-6" /> : <VolumeX className="h-6 w-6" />}
            </Button>

            {/* Camera Switch (only for video calls) */}
            {callState.callType === "video" && (
              <Button variant="secondary" size="lg" className="rounded-full h-14 w-14" onClick={switchCamera}>
                <RotateCcw className="h-6 w-6" />
              </Button>
            )}

            {/* Minimize/Maximize */}
            <Button
              variant="secondary"
              size="lg"
              className="rounded-full h-14 w-14"
              onClick={() => setCallState((prev) => ({ ...prev, isMinimized: !prev.isMinimized }))}
            >
              {callState.isMinimized ? <Maximize className="h-6 w-6" /> : <Minimize className="h-6 w-6" />}
            </Button>

            {/* End Call */}
            <Button variant="destructive" size="lg" className="rounded-full h-14 w-14" onClick={endCall}>
              <PhoneOff className="h-6 w-6" />
            </Button>
          </div>
        </Card>
      </div>

      {/* Incoming Call UI (if applicable) */}
      {callState.isIncoming && !callState.isConnected && (
        <div className="absolute inset-0 bg-black/80 flex items-center justify-center">
          <Card className="bg-card text-card-foreground max-w-sm w-full mx-4">
            <div className="p-6 text-center">
              <Avatar className="h-24 w-24 mx-auto mb-4">
                <AvatarImage
                  src={currentUser.avatar || "/placeholder.svg"}
                  alt={`${currentUser.firstName} ${currentUser.lastName}`}
                />
                <AvatarFallback className="text-2xl">
                  {currentUser.firstName[0]}
                  {currentUser.lastName[0]}
                </AvatarFallback>
              </Avatar>
              <h3 className="text-xl font-semibold mb-2">
                {currentUser.firstName} {currentUser.lastName}
              </h3>
              <p className="text-muted-foreground mb-6">Incoming {callState.callType} call...</p>
              <div className="flex justify-center space-x-4">
                <Button variant="destructive" size="lg" className="rounded-full h-16 w-16" onClick={endCall}>
                  <PhoneOff className="h-6 w-6" />
                </Button>
                <Button
                  variant="default"
                  size="lg"
                  className="rounded-full h-16 w-16 bg-green-500 hover:bg-green-600"
                  onClick={() => setCallState((prev) => ({ ...prev, isConnected: true, isIncoming: false }))}
                >
                  <Phone className="h-6 w-6" />
                </Button>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  )
}
