'use client';

import { useEffect, useState } from 'react';
import {
  Eye, Pencil, Settings, Video, CalendarX, Clock, PhoneCall, Reply
} from 'lucide-react';
import clsx from 'clsx';
import { useRouter } from 'next/navigation';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';
import PrescriptionModal from './PrescriptionForm';
import LabTestModal from './LabTestModal';
import ViewPrescriptionsModal from './ViewPrescriptionsModal';
import ViewLabTestsModal from './ViewLabTestsModal';
import AvailabilityForm from './AvailabilityForm';

function calculateAge(dateString) {
  const birthDate = new Date(dateString);
  const ageDiff = Date.now() - birthDate.getTime();
  const ageDate = new Date(ageDiff);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

export default function DoctorConsultationWindow() {
  const [consultations, setConsultations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [message, setMessage] = useState(null);
  const [notesModal, setNotesModal] = useState(null);
  const [noteContent, setNoteContent] = useState('');
  const [selectedConsultation, setSelectedConsultation] = useState(null);
  const [moreActionsModal, setMoreActionsModal] = useState(null);
  const [activeTab, setActiveTab] = useState('prescribe');
  const [viewPrescriptionsModal, setViewPrescriptionsModal] = useState(null);
  const [viewLabTestsModal, setViewLabTestsModal] = useState(null);
  const [callOutModal, setCallOutModal] = useState(null);
  const [callOutMessage, setCallOutMessage] = useState('');
  const [incomingCalloutModal, setIncomingCalloutModal] = useState(null);
  const [replyMessage, setReplyMessage] = useState('');
  const [showAvailabilityModal, setShowAvailabilityModal] = useState(false);

  const { socket } = useSocket();
  const user = useAuthStore((state) => state.user);
  const router = useRouter();

  useEffect(() => {
    const fetchConsultations = async () => {
      try {
        const res = await fetch('/api/appointmentbooking/doctor/scheduled', {
          credentials: 'include',
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to fetch consultations');
        setConsultations(Array.isArray(data) ? data : data.consultations || []);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchConsultations();
  }, []);

  const startVideoCall = (consultation) => {
    const roomId = consultation.id;
    const participantName = `Dr. ${user?.profile?.firstName} ${user?.profile?.lastName}`;
    const targetUserId = consultation?.patientId;

    router.push(`/video-call?roomId=${roomId}&participantName=${encodeURIComponent(participantName)}&targetUserId=${targetUserId}`);
  };



  const saveNotes = async () => {
    try {
      const res = await fetch(`/api/updatepatientnotes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: notesModal.id, notes: noteContent }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update notes');
      setConsultations(prev =>
        prev.map(c => (c.id === notesModal.id ? { ...c, notes: noteContent } : c))
      );
      setMessage('Notes saved successfully.');
      setTimeout(() => {
        setNotesModal(null);
        setMessage(null);
      }, 1500);
    } catch (err) {
      setMessage(err.message || 'Failed to save notes.');
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleDoctorCallOut = async () => {
    try {
      const res = await fetch(`/api/callouts/${callOutModal.id}/callout`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          message: callOutMessage,
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to send call out');

      alert('Call out sent to patient successfully.');
      setCallOutModal(null);
      setCallOutMessage('');
    } catch (err) {
      alert(err.message || 'Error sending call out.');
    }
  };


  const handleCalloutReply = async (status) => {
    try {
      const res = await fetch(`/api/callouts/${incomingCalloutModal.id}/callout/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ status }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update callout status');

      alert(`Callout ${status} successfully.`);
      setIncomingCalloutModal(null);
    } catch (err) {
      alert(err.message);
    }
  };



  const getStatusBadge = (status) => {
    const base = 'text-xs px-2 py-1 rounded-full font-medium inline-block';
    switch (status) {
      case 'active': return `${base} bg-blue-100 text-blue-700`;
      case 'completed': return `${base} bg-green-100 text-green-700`;
      case 'archived': return `${base} bg-gray-100 text-gray-700`;
      case 'pending': return `${base} bg-yellow-100 text-yellow-700`;
      default: return `${base} bg-gray-100 text-gray-500`;
    }
  };

  return (
    <div className="bg-white p-4 rounded shadow-md">
      <h2 className="text-xl font-semibold mb-4">Your Consultations</h2>
      <button
        onClick={() => setShowAvailabilityModal(true)}
        className="mb-5 bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700 text-sm"
      >
        Set Availability
      </button>

      {loading ? (
        <p className="text-sm text-gray-500">Loading consultations...</p>
      ) : error ? (
        <p className="text-sm text-red-500">{error}</p>
      ) : consultations.length === 0 ? (
        <div className="flex flex-col items-center justify-center text-center text-gray-500 mt-20">
          <CalendarX className="w-12 h-12 mb-3 text-gray-400" />
          <p className="text-md font-semibold">No consultations scheduled</p>
          <p className="text-sm text-gray-400 max-w-sm">
            You currently have no consultations assigned. Once a patient books with you, it will show up here.
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {consultations.map((consultation) => {
            const patient = consultation.patient?.patientProfile;
            const isPatientCallout = !!consultation.calloutMessage;
            const canRespondToCallout = isPatientCallout && consultation.calloutStatus === 'pending';

            return (
              <div key={consultation.id} className="border p-4 rounded shadow-sm">
                <h4 className="font-semibold text-gray-800">
                  {patient?.firstName} {patient?.lastName}
                </h4>
                <p className="text-sm text-gray-600">{new Date(consultation.scheduledAt).toLocaleString()}</p>
                <p className="text-sm text-gray-500 mt-1">{consultation.notes}</p>
                <div className="mt-2 flex gap-2 items-center flex-wrap">
                  <span className={getStatusBadge(consultation.status)}>
                    {consultation.status.toUpperCase()}
                  </span>
                  {isPatientCallout && (
                    <button
                      onClick={() => {
                        setIncomingCalloutModal(consultation);
                      }}
                      className="inline-flex items-center gap-1 text-sm font-medium text-orange-600 hover:text-orange-800 hover:underline transition duration-150"
                    >
                      <svg
                        className="w-4 h-4"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        viewBox="0 0 24 24"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      View Patient Callout
                    </button>

                  )}
                </div>
                <div className="flex gap-2 mt-3">
                  <button onClick={() => setSelectedConsultation(consultation)} className="p-2 bg-indigo-100 rounded-full hover:bg-indigo-200" title="View Details"><Eye className="w-5 h-5 text-indigo-600" /></button>
                  <button onClick={() => { setCallOutModal(consultation); setCallOutMessage(''); }} className="p-2 bg-orange-100 rounded-full hover:bg-orange-200" title="Send Call Out"><PhoneCall className="w-5 h-5 text-orange-600" /></button>
                  <button onClick={() => { setNotesModal(consultation); setNoteContent(consultation.notes || ''); }} className="p-2 bg-green-100 rounded-full hover:bg-green-200" title="Add Notes"><Pencil className="w-5 h-5 text-green-600" /></button>
                  <button onClick={() => { setMoreActionsModal(consultation); setActiveTab('prescribe'); }} className="p-2 bg-purple-100 rounded-full hover:bg-purple-200" title="More Actions"><Settings className="w-5 h-5 text-purple-600" /></button>
                  <button onClick={() => startVideoCall(consultation)} className="p-2 bg-blue-100 rounded-full hover:bg-blue-200" title="Start Video Call"><Video className="w-5 h-5 text-blue-600" /></button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Modals */}
      {showAvailabilityModal && (
        <Modal title="Set Availability" onClose={() => setShowAvailabilityModal(false)}>
          <AvailabilityForm doctorId={user?.id} onClose={() => setShowAvailabilityModal(false)} />
        </Modal>
      )}

      {selectedConsultation && (
        <Modal title="Consultation Details" onClose={() => setSelectedConsultation(null)}>
          <div className="space-y-1 text-sm text-gray-700">
            <p><strong>Patient:</strong> {selectedConsultation.patient?.patientProfile?.firstName} {selectedConsultation.patient?.patientProfile?.lastName}</p>
            <p><strong>Email:</strong> {selectedConsultation.patient?.email}</p>
            <p><strong>Gender:</strong> {selectedConsultation.patient?.patientProfile?.gender}</p>
            <p><strong>Age:</strong> {calculateAge(selectedConsultation.patient?.patientProfile?.dateOfBirth)}</p>
            <p><strong>Scheduled Date:</strong> {new Date(selectedConsultation.scheduledAt).toLocaleString()}</p>
            <p><strong>Status:</strong> {selectedConsultation.status}</p>
            <p><strong>Type:</strong> {selectedConsultation.type}</p>
            {selectedConsultation.notes && <p><strong>Notes:</strong> {selectedConsultation.notes}</p>}
          </div>
        </Modal>
      )}

      {notesModal && (
        <Modal title="Add Notes" onClose={() => setNotesModal(null)}>
          <textarea value={noteContent} onChange={(e) => setNoteContent(e.target.value)} rows={6} className="w-full border p-2 rounded text-sm" />
          {message && <p className={`mt-2 text-sm ${message.includes('success') ? 'text-green-600' : 'text-red-600'}`}>{message}</p>}
          <div className="mt-3 text-right">
            <button onClick={saveNotes} className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">Save Notes</button>
          </div>
        </Modal>
      )}

      {moreActionsModal && (
        <Modal title="More Actions" onClose={() => setMoreActionsModal(null)}>
          <div className="flex border-b mb-4">
            <button onClick={() => setActiveTab('prescribe')} className={clsx("px-4 py-2", { "border-b-2 border-purple-600 font-semibold": activeTab === 'prescribe' })}>Prescribe</button>
            <button onClick={() => setActiveTab('lab')} className={clsx("px-4 py-2", { "border-b-2 border-purple-600 font-semibold": activeTab === 'lab' })}>Lab Test</button>
          </div>
          {activeTab === 'lab' ? (
            <>
              <LabTestModal patientId={moreActionsModal.patient?.id} patientName={`${moreActionsModal.patient?.patientProfile?.firstName} ${moreActionsModal.patient?.patientProfile?.lastName}`}>
                <button className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">Suggest Lab Test</button>
              </LabTestModal>
              <br />
              <button onClick={() => setViewLabTestsModal(moreActionsModal)} className="bg-gray-600 text-white px-4 py-2 rounded mt-2 hover:bg-gray-700">View Lab Tests</button>
            </>
          ) : (
            <>
              <PrescriptionModal consultationId={moreActionsModal.id} patientId={moreActionsModal.patient?.id} patientName={`${moreActionsModal.patient?.patientProfile?.firstName} ${moreActionsModal.patient?.patientProfile?.lastName}`}>
                <button className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">Create New Prescription</button>
              </PrescriptionModal>
              <br />
              <button onClick={() => setViewPrescriptionsModal(moreActionsModal)} className="bg-gray-600 text-white px-4 py-2 rounded mt-2 hover:bg-gray-700">View Prescriptions</button>
            </>
          )}
        </Modal>
      )}

      {viewPrescriptionsModal && (
        <ViewPrescriptionsModal
          patientId={viewPrescriptionsModal.patient?.id}
          patientName={`${viewPrescriptionsModal.patient?.patientProfile?.firstName} ${viewPrescriptionsModal.patient?.patientProfile?.lastName}`}
          onClose={() => setViewPrescriptionsModal(null)}
        />
      )}

      {viewLabTestsModal && (
        <ViewLabTestsModal
          patientId={viewLabTestsModal.patient?.id}
          patientName={`${viewLabTestsModal.patient?.patientProfile?.firstName} ${viewLabTestsModal.patient?.patientProfile?.lastName}`}
          onClose={() => setViewLabTestsModal(null)}
        />
      )}

      {callOutModal && (
        <Modal title="Send Call Out" onClose={() => setCallOutModal(null)}>
          <textarea value={callOutMessage} onChange={(e) => setCallOutMessage(e.target.value)} rows={4} className="w-full border p-2 rounded text-sm" placeholder="Optional message..." />
          <div className="text-right mt-3">
            <button onClick={handleDoctorCallOut} className="bg-orange-600 text-white px-4 py-2 rounded hover:bg-orange-700">Send</button>
          </div>
        </Modal>
      )}

      {incomingCalloutModal && (
        <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 px-4">
          <div className="bg-white p-6 rounded shadow-lg max-w-md w-full relative">
            <button
              className="absolute top-2 right-2 text-gray-500 hover:text-gray-700 text-2xl"
              onClick={() => setIncomingCalloutModal(null)}
            >
              &times;
            </button>

            <h3 className="text-lg font-semibold mb-3">Doctor Call Out Request</h3>

            <p className="text-sm text-gray-600 mb-2">Message:</p>
            <div className="bg-gray-100 p-3 rounded text-sm text-gray-800 mb-3">
              {incomingCalloutModal.calloutMessage}
            </div>

            {incomingCalloutModal.calloutTimeOption && (
              <div className="bg-purple-50 p-3 rounded text-sm text-purple-700 mb-4">
                <strong>Requested Time:</strong>{' '}
                {incomingCalloutModal.calloutTimeOption === 'within_45mins'
                  ? 'Within 45 mins'
                  : incomingCalloutModal.calloutTimeOption === '1hr_45mins'
                    ? 'Within 1 hr 45 mins'
                    : incomingCalloutModal.calloutTimeOption === '3_5hrs'
                      ? 'Within 3–5 hrs'
                      : incomingCalloutModal.calloutTimeOption}
              </div>
            )}

            <p className="text-sm text-gray-600 mb-3">Choose how to respond:</p>

            <div className="flex justify-end gap-2">
              <button
                onClick={() => handleCalloutReply('declined')}
                className="px-4 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700"
              >
                Reject
              </button>
              <button
                onClick={() => handleCalloutReply('accepted')}
                className="px-4 py-2 text-sm bg-green-600 text-white rounded hover:bg-green-700"
              >
                Accept
              </button>
            </div>
          </div>
        </div>
      )}



    </div>
  );
}

// Modal helper
function Modal({ title, children, onClose }) {
  return (
    <div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 px-4">
      <div className="bg-white p-6 rounded shadow-lg max-w-md w-full relative">
        <button className="absolute top-2 right-2 text-gray-500 hover:text-gray-700 text-2xl" onClick={onClose}>
          &times;
        </button>
        <h3 className="text-lg font-semibold mb-4">{title}</h3>
        {children}
      </div>
    </div>
  );
}
