'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import {
  Video,
  Phone,
  MessageCircle,
  Send,
  ArrowLeft,
  User,
  Clock,
  FileText,
  Pill,
  AlertCircle,
  CheckCircle,
  XCircle,
  Plus,
  ChevronRight,
  Heart,
  Thermometer,
  Activity,
} from 'lucide-react';
import SidebarLayout from '../../../components/sidebar-layout';
import VideoCall from '../../../components/VideoCall';

interface Session {
  _id: string;
  sessionNumber: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    email: string;
    phone: string;
    dateOfBirth?: string;
    gender?: string;
    profilePhoto?: string;
  };
  doctorId: {
    _id: string;
    name: string;
    specialization?: string;
    email: string;
    profilePhoto?: string;
  };
  consultationType: 'video' | 'audio' | 'chat';
  scheduledStartTime: string;
  scheduledEndTime: string;
  actualStartTime?: string;
  actualEndTime?: string;
  status: string;
  roomId: string;
  chiefComplaint?: string;
  symptoms?: string[];
  diagnosis?: string;
  clinicalNotes?: string;
  vitalSigns?: any[];
  chatMessages: ChatMessage[];
  paymentStatus: string;
  consultationFee: number;
  currency: string;
  patientRating?: number;
  patientFeedback?: string;
}

interface ChatMessage {
  _id: string;
  senderId: string;
  senderType: 'doctor' | 'patient';
  senderName: string;
  message: string;
  messageType: 'text' | 'image' | 'file' | 'prescription';
  timestamp: string;
  read: boolean;
}

export default function SessionDetailPage() {
  const { data: authSession } = useSession();
  const params = useParams();
  const searchParams = useSearchParams();
  const router = useRouter();
  const sessionId = params.id as string;
  
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Call state
  const [isCallActive, setIsCallActive] = useState(false);
  const [callDuration, setCallDuration] = useState(0);
  
  // Chat state
  const [showChat, setShowChat] = useState(true);
  const [newMessage, setNewMessage] = useState('');
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const lastMessageTimestampRef = useRef<string>('');
  
  // Clinical notes
  const [showNotes, setShowNotes] = useState(false);
  const [clinicalNotes, setClinicalNotes] = useState('');
  const [diagnosis, setDiagnosis] = useState('');
  const [symptoms, setSymptoms] = useState<string[]>([]);
  const [newSymptom, setNewSymptom] = useState('');
  const [updatingStatus, setUpdatingStatus] = useState(false);

  const fetchSession = async () => {
    try {
      const res = await fetch(`/api/telemedicine/sessions/${sessionId}`);
      if (!res.ok) throw new Error('Failed to fetch session');
      const data = await res.json();
      setSession(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const pollMessages = useCallback(async () => {
    try {
      const since = lastMessageTimestampRef.current;
      const res = await fetch(`/api/telemedicine/sessions/${sessionId}/chat${since ? `?since=${since}` : ''}`);
      if (res.ok) {
        const data = await res.json();
        if (data.messages && data.messages.length > 0) {
          setMessages(prev => {
            const existingIds = new Set(prev.map(m => m._id));
            const newMessages = data.messages.filter((m: ChatMessage) => !existingIds.has(m._id));
            if (newMessages.length > 0) {
              const lastNew = newMessages[newMessages.length - 1];
              lastMessageTimestampRef.current = lastNew.timestamp;
              return [...prev, ...newMessages];
            }
            return prev;
          });
        }
      }
    } catch (error) {
      console.error('Error polling messages:', error);
    }
  }, [sessionId]);

  useEffect(() => {
    fetchSession();
    
    const messageInterval = setInterval(pollMessages, 3000);
    
    return () => {
      clearInterval(messageInterval);
    };
  }, [sessionId, pollMessages]);

  useEffect(() => {
    if (searchParams.get('start') === 'true' && session && !isCallActive) {
      startCall();
    }
  }, [session, searchParams]);

  useEffect(() => {
    if (session) {
      const chatMessages = session.chatMessages || [];
      setMessages(chatMessages);
      if (chatMessages.length > 0) {
        lastMessageTimestampRef.current = chatMessages[chatMessages.length - 1].timestamp;
      }
      setClinicalNotes(session.clinicalNotes || '');
      setDiagnosis(session.diagnosis || '');
      setSymptoms(session.symptoms || []);
    }
  }, [session]);

  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isCallActive) {
      interval = setInterval(() => {
        setCallDuration(d => d + 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [isCallActive]);

  const startCall = async () => {
    try {
      await fetch(`/api/telemedicine/sessions/${sessionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'in-progress' }),
      });

      setIsCallActive(true);
      setCallDuration(0);
      fetchSession();
    } catch (error: any) {
      console.error('Error starting call:', error);
      setError('Failed to start call.');
    }
  };

  const endCall = async () => {
    setIsCallActive(false);

    await fetch(`/api/telemedicine/sessions/${sessionId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        status: 'completed',
        clinicalNotes,
        diagnosis,
        symptoms,
      }),
    });

    fetchSession();
  };

  const handleJitsiReadyToClose = () => {
    endCall();
  };

  const sendMessage = async () => {
    if (!newMessage.trim()) return;

    try {
      const res = await fetch(`/api/telemedicine/sessions/${sessionId}/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: newMessage,
          senderType: 'doctor',
          senderName: authSession?.user?.name || 'Doctor',
        }),
      });

      if (res.ok) {
        const data = await res.json();
        setMessages(prev => {
          const exists = prev.some(m => m._id === data.message._id);
          if (exists) return prev;
          return [...prev, data.message];
        });
        if (data.message.timestamp) {
          lastMessageTimestampRef.current = data.message.timestamp;
        }
        setNewMessage('');
      }
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };

  const addSymptom = () => {
    if (newSymptom.trim() && !symptoms.includes(newSymptom.trim())) {
      setSymptoms([...symptoms, newSymptom.trim()]);
      setNewSymptom('');
    }
  };

  const removeSymptom = (symptom: string) => {
    setSymptoms(symptoms.filter(s => s !== symptom));
  };

  const saveNotes = async () => {
    try {
      await fetch(`/api/telemedicine/sessions/${sessionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clinicalNotes,
          diagnosis,
          symptoms,
        }),
      });
    } catch (error) {
      console.error('Error saving notes:', error);
    }
  };

  const formatDuration = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    if (h > 0) {
      return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    }
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      'scheduled': 'bg-blue-100 text-blue-800',
      'waiting': 'bg-yellow-100 text-yellow-800',
      'in-progress': 'bg-green-100 text-green-800',
      'completed': 'bg-gray-100 text-gray-800',
      'cancelled': 'bg-red-100 text-red-800',
    };
    return styles[status] || 'bg-gray-100 text-gray-800';
  };

  const updateSessionStatus = async (newStatus: string) => {
    if (updatingStatus) return;
    if (newStatus === 'completed' && !confirm('End this session and mark as completed?')) return;
    if (newStatus === 'cancelled' && !confirm('Cancel this session? The consultation will be marked as cancelled.')) return;
    setUpdatingStatus(true);
    try {
      const payload: Record<string, unknown> = { status: newStatus };
      if (newStatus === 'completed') {
        payload.clinicalNotes = clinicalNotes;
        payload.diagnosis = diagnosis;
        payload.symptoms = symptoms;
      }
      const res = await fetch(`/api/telemedicine/sessions/${sessionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        await fetchSession();
        if (newStatus === 'completed') {
          setIsCallActive(false);
        }
      } else {
        const err = await res.json().catch(() => ({}));
        alert(err.error || 'Failed to update status');
      }
    } catch (e) {
      console.error(e);
      alert('Failed to update status');
    } finally {
      setUpdatingStatus(false);
    }
  };

  if (loading) {
    return (
      <SidebarLayout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      </SidebarLayout>
    );
  }

  if (error || !session) {
    return (
      <SidebarLayout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
            <p className="text-gray-600">{error || 'Session not found'}</p>
            <Link
              href="/telemedicine"
              className="mt-4 inline-flex items-center gap-2 text-blue-600 hover:text-blue-700"
            >
              <ArrowLeft className="w-4 h-4" />
              Back to Telemedicine
            </Link>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout>
      <div className="h-screen flex flex-col bg-gray-900">
        {/* Header */}
        <div className="bg-gray-800 px-4 py-3 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link
              href="/telemedicine"
              className="text-gray-400 hover:text-white transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </Link>
            <div>
              <h1 className="text-white font-semibold">{session.sessionNumber}</h1>
              <p className="text-gray-400 text-sm">
                {session.patientId.name} with Dr. {session.doctorId.name}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusBadge(session.status)}`}>
              {session.status.replace('-', ' ')}
            </span>
            {session.status === 'in-progress' && (
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => updateSessionStatus('completed')}
                  disabled={updatingStatus}
                  className="px-3 py-1.5 rounded-lg text-xs font-medium bg-green-600 hover:bg-green-500 text-white disabled:opacity-50 flex items-center gap-1"
                >
                  <CheckCircle className="w-3.5 h-3.5" />
                  End session
                </button>
                <button
                  type="button"
                  onClick={() => updateSessionStatus('cancelled')}
                  disabled={updatingStatus}
                  className="px-3 py-1.5 rounded-lg text-xs font-medium bg-gray-600 hover:bg-gray-500 text-white disabled:opacity-50 flex items-center gap-1"
                >
                  <XCircle className="w-3.5 h-3.5" />
                  Cancel session
                </button>
              </div>
            )}
            {isCallActive && (
              <span className="flex items-center gap-2 text-white">
                <span className="relative flex h-2 w-2">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                  <span className="relative inline-flex rounded-full h-2 w-2 bg-red-500"></span>
                </span>
                {formatDuration(callDuration)}
              </span>
            )}
          </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 flex overflow-hidden">
          {/* Video/Audio Area */}
          <div className="flex-1 relative bg-gray-900 flex items-center justify-center">
            {isCallActive ? (
              <div className="w-full h-full relative">
                <VideoCall
                  roomId={session.roomId}
                  participantName={authSession?.user?.name || 'Doctor'}
                  participantRole="doctor"
                  sessionStatus={session.status}
                  onCallEnd={handleJitsiReadyToClose}
                />
                {/* Side panel toggle buttons */}
                <div className="absolute top-4 left-4 flex items-center gap-2 z-10">
                  <button
                    onClick={() => { setShowChat(!showChat); setShowNotes(false); }}
                    className={`p-2 rounded-lg transition-colors ${
                      showChat ? 'bg-blue-500 text-white' : 'bg-gray-800/80 text-gray-300 hover:bg-gray-700'
                    }`}
                    title="Toggle Chat"
                  >
                    <MessageCircle className="w-5 h-5" />
                  </button>
                  <button
                    onClick={() => { setShowNotes(!showNotes); setShowChat(false); }}
                    className={`p-2 rounded-lg transition-colors ${
                      showNotes ? 'bg-purple-500 text-white' : 'bg-gray-800/80 text-gray-300 hover:bg-gray-700'
                    }`}
                    title="Toggle Notes"
                  >
                    <FileText className="w-5 h-5" />
                  </button>
                </div>
              </div>
            ) : (
              /* Pre-call Screen */
              <div className="text-center">
                <div className="w-24 h-24 bg-gray-700 rounded-full mx-auto flex items-center justify-center mb-6">
                  {session.consultationType === 'video' ? (
                    <Video className="w-12 h-12 text-blue-500" />
                  ) : session.consultationType === 'audio' ? (
                    <Phone className="w-12 h-12 text-green-500" />
                  ) : (
                    <MessageCircle className="w-12 h-12 text-purple-500" />
                  )}
                </div>
                <h2 className="text-white text-2xl font-semibold mb-2">
                  {session.consultationType.charAt(0).toUpperCase() + session.consultationType.slice(1)} Consultation
                </h2>
                <p className="text-gray-400 mb-2">
                  Patient: {session.patientId.name}
                </p>
                <p className="text-gray-500 mb-6">
                  Scheduled: {new Date(session.scheduledStartTime).toLocaleString()}
                </p>
                {session.chiefComplaint && (
                  <p className="text-gray-400 mb-6">
                    Chief Complaint: {session.chiefComplaint}
                  </p>
                )}
                
                {session.status === 'completed' ? (
                  <div className="text-green-500 flex items-center justify-center gap-2">
                    <CheckCircle className="w-5 h-5" />
                    Session Completed
                  </div>
                ) : session.status === 'cancelled' ? (
                  <div className="text-red-500 flex items-center justify-center gap-2">
                    <XCircle className="w-5 h-5" />
                    Session Cancelled
                  </div>
                ) : (
                  <button
                    onClick={startCall}
                    className="px-8 py-3 bg-green-500 hover:bg-green-600 text-white rounded-full font-medium transition-colors flex items-center gap-2 mx-auto"
                  >
                    {session.consultationType === 'video' ? (
                      <>
                        <Video className="w-5 h-5" />
                        Start Video Call
                      </>
                    ) : session.consultationType === 'audio' ? (
                      <>
                        <Phone className="w-5 h-5" />
                        Start Audio Call
                      </>
                    ) : (
                      <>
                        <MessageCircle className="w-5 h-5" />
                        Start Chat
                      </>
                    )}
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Side Panel - Chat or Notes */}
          {(showChat || showNotes) && (
            <div className="w-96 bg-white border-l border-gray-200 flex flex-col">
              {/* Tabs */}
              <div className="flex border-b border-gray-200">
                <button
                  onClick={() => { setShowChat(true); setShowNotes(false); }}
                  className={`flex-1 px-4 py-3 text-sm font-medium ${
                    showChat && !showNotes
                      ? 'text-blue-600 border-b-2 border-blue-600'
                      : 'text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Chat
                </button>
                <button
                  onClick={() => { setShowNotes(true); setShowChat(false); }}
                  className={`flex-1 px-4 py-3 text-sm font-medium ${
                    showNotes
                      ? 'text-blue-600 border-b-2 border-blue-600'
                      : 'text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Clinical Notes
                </button>
              </div>

              {showChat && !showNotes && (
                <>
                  {/* Messages */}
                  <div ref={chatContainerRef} className="flex-1 overflow-y-auto p-4 space-y-4">
                    {messages.length === 0 ? (
                      <div className="text-center text-gray-500 py-8">
                        <MessageCircle className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                        <p>No messages yet</p>
                      </div>
                    ) : (
                      messages.map(msg => (
                        <div
                          key={msg._id}
                          className={`flex ${msg.senderType === 'doctor' ? 'justify-end' : 'justify-start'}`}
                        >
                          <div
                            className={`max-w-[80%] px-4 py-2 rounded-lg ${
                              msg.senderType === 'doctor'
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-900'
                            }`}
                          >
                            <p className="text-sm">{msg.message}</p>
                            <p className={`text-xs mt-1 ${
                              msg.senderType === 'doctor' ? 'text-blue-200' : 'text-gray-500'
                            }`}>
                              {new Date(msg.timestamp).toLocaleTimeString()}
                            </p>
                          </div>
                        </div>
                      ))
                    )}
                  </div>

                  {/* Message Input */}
                  <div className="p-4 border-t border-gray-200">
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={newMessage}
                        onChange={(e) => setNewMessage(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                        placeholder="Type a message..."
                        className="flex-1 px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        onClick={sendMessage}
                        className="p-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg"
                      >
                        <Send className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </>
              )}

              {showNotes && (
                <div className="flex-1 overflow-y-auto p-4 space-y-4">
                  {/* Patient Info */}
                  <div className="bg-gray-50 rounded-lg p-4">
                    <h3 className="font-medium text-gray-900 mb-2">Patient Information</h3>
                    <div className="space-y-1 text-sm">
                      <p><span className="text-gray-500">Name:</span> {session.patientId.name}</p>
                      <p><span className="text-gray-500">ID:</span> {session.patientId.patientId}</p>
                      {session.patientId.dateOfBirth && (
                        <p><span className="text-gray-500">DOB:</span> {new Date(session.patientId.dateOfBirth).toLocaleDateString()}</p>
                      )}
                      {session.patientId.gender && (
                        <p><span className="text-gray-500">Gender:</span> {session.patientId.gender}</p>
                      )}
                    </div>
                  </div>

                  {/* Symptoms */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Symptoms</label>
                    <div className="flex flex-wrap gap-2 mb-2">
                      {symptoms.map(symptom => (
                        <span
                          key={symptom}
                          className="inline-flex items-center gap-1 px-3 py-1 bg-orange-100 text-orange-800 rounded-full text-sm"
                        >
                          {symptom}
                          <button onClick={() => removeSymptom(symptom)} className="hover:text-orange-600">
                            <XCircle className="w-4 h-4" />
                          </button>
                        </span>
                      ))}
                    </div>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={newSymptom}
                        onChange={(e) => setNewSymptom(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && addSymptom()}
                        placeholder="Add symptom..."
                        className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm"
                      />
                      <button
                        onClick={addSymptom}
                        className="px-3 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600"
                      >
                        <Plus className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  {/* Diagnosis */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Diagnosis</label>
                    <input
                      type="text"
                      value={diagnosis}
                      onChange={(e) => setDiagnosis(e.target.value)}
                      placeholder="Enter diagnosis..."
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                    />
                  </div>

                  {/* Clinical Notes */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Clinical Notes</label>
                    <textarea
                      value={clinicalNotes}
                      onChange={(e) => setClinicalNotes(e.target.value)}
                      placeholder="Enter clinical notes..."
                      rows={6}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                    />
                  </div>

                  {/* Save Button */}
                  <button
                    onClick={saveNotes}
                    className="w-full py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-medium"
                  >
                    Save Notes
                  </button>

                  {/* Create Prescription */}
                  <Link
                    href={`/telemedicine/sessions/${sessionId}/prescription`}
                    className="w-full py-2 border border-green-500 text-green-600 hover:bg-green-50 rounded-lg font-medium flex items-center justify-center gap-2"
                  >
                    <Pill className="w-4 h-4" />
                    Create Prescription
                  </Link>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </SidebarLayout>
  );
}
