'use client';

import { useEffect, useState } from 'react';
import { Eye, NotebookPen, Video, CalendarX, Edit3, Home } from 'lucide-react';
import { useRouter } from 'next/navigation';

export default function ConsultationWindow() {
  const [consultations, setConsultations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedConsultation, setSelectedConsultation] = useState(null);
  const [viewingNotes, setViewingNotes] = useState(null);
  const [editingStatus, setEditingStatus] = useState(null);
  const [newStatus, setNewStatus] = useState('');
  const [statusError, setStatusError] = useState('');
  const [callingOutConsultation, setCallingOutConsultation] = useState(null);
  const [callOutMessage, setCallOutMessage] = useState('');
  const [callouts, setCallouts] = useState({});
  
  const [callOutTimeOption, setCallOutTimeOption] = useState('');

  const router = useRouter();

  const fetchConsultations = async () => {
    try {
      const res = await fetch('/api/appointmentbooking/patient/scheduled', {
        method: 'GET',
        credentials: 'include',
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to fetch consultations');

      const consultationsArray = Array.isArray(data) ? data : data.consultations || [];
      // Fetch callouts in parallel
      await Promise.all(consultationsArray.map(c => fetchCallout(c.id)));

      setConsultations(consultationsArray);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConsultations();
  }, []);

  const getConsultationTiming = (scheduledAt) => {
    const now = new Date();
    const scheduledTime = new Date(scheduledAt);
    return scheduledTime > now ? 'Upcoming' : 'Past Due';
  };

  const handleStartCall = (consultation) => {
    const roomId = consultation.id;
    const doctorName = `${consultation?.doctor?.doctorProfile?.firstName} ${consultation?.doctor?.doctorProfile?.lastName}`;
    const targetUserId = consultation?.doctorId;

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



  const handleStatusChange = async () => {
    if (!newStatus) {
      setStatusError('Please select a status.');
      return;
    }

    try {
      const res = await fetch('/api/changestatus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          consultationId: editingStatus.id,
          status: newStatus,
        }),
      });

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

      setEditingStatus(null);
      setNewStatus('');
      fetchConsultations();
    } catch (err) {
      setStatusError(err.message);
    }
  };

  const handleRequestCallOut = async () => {
    console.log('Requesting call out for consultation:', callingOutConsultation.id);
    if (!callOutMessage.trim() && !callOutTimeOption) {
      alert('Please provide a message or select a response time.');
      return;
    }
    try {
      const res = await fetch(`/api/callouts/${callingOutConsultation.id}/callout`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          message: callOutMessage,
          calloutTimeOption: callOutTimeOption || undefined,
        }),
      });

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

      alert('Call out request sent successfully');
      setCallingOutConsultation(null);
      setCallOutMessage('');
      setCallOutTimeOption('');
    } catch (err) {
      alert(err.message || 'Error sending call out request.');
    }
  };



  const fetchCallout = async (consultationId) => {
    try {
      const res = await fetch(`/api/callouts/${consultationId}/callout`, {
        method: 'GET',
        credentials: 'include',
      });

      const data = await res.json();

      if (res.ok && (data.calloutMessage || data.calloutStatus)) {
        setCallouts(prev => ({ ...prev, [consultationId]: data }));
      }
    } catch (err) {
      console.error(`Error fetching callout for ${consultationId}:`, err.message);
    }
  };



  const getStatusBorderColor = (status) => {
    switch (status) {
      case 'active': return 'border-green-500';
      case 'completed': return 'border-blue-500';
      case 'pending': return 'border-yellow-500';
      case 'archived': return 'border-gray-400';
      default: return 'border-gray-200';
    }
  };

  return (
    <div className="bg-white p-4 rounded shadow-md">
      <h2 className="text-xl font-semibold mb-4">Scheduled Consultations</h2>

      {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 scheduled consultations</p>
          <p className="text-sm text-gray-400 max-w-sm">
            You don’t have any consultations booked yet. Once your doctor schedules one, it will appear here.
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {consultations.map((consultation) => {
            const timing = getConsultationTiming(consultation.scheduledAt);
            const isPastDue = timing === 'Past Due';
            const timingColor = isPastDue ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700';
            const borderColor = getStatusBorderColor(consultation.status);

            return (
              <div
                key={consultation.id}
                className={`border ${borderColor} p-4 rounded bg-white shadow-sm hover:shadow-md transition`}
              >
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-semibold text-gray-800">
                      Dr. {consultation?.doctor?.doctorProfile?.firstName}{' '}
                      {consultation?.doctor?.doctorProfile?.lastName}
                    </h4>
                    <p className="text-sm text-gray-600">
                      {new Date(consultation.scheduledAt).toLocaleString()}
                    </p>
                    <p className="text-sm text-gray-500 mt-1">
                      Status: {consultation.status}
                    </p>
                    {callouts[consultation.id]?.calloutMessage && (
                      <div className="mt-2 text-sm text-purple-700 bg-purple-50 p-2 rounded">
                        <p><strong>Callout:</strong> {callouts[consultation.id].calloutMessage}</p>
                        {callouts[consultation.id].calloutTimeOption && (
                          <p>
                            <strong>Requested Time:</strong>{' '}
                            {callouts[consultation.id].calloutTimeOption === 'within_45mins'
                              ? 'Within 45 mins – N120,000'
                              : callouts[consultation.id].calloutTimeOption === '1hr_45mins'
                                ? 'Within 1 hr 45 mins – N75,000'
                                : callouts[consultation.id].calloutTimeOption === '3_5hrs'
                                  ? 'Within 3–5 hrs – N45,000'
                                  : callouts[consultation.id].calloutTimeOption}
                          </p>
                        )}
                        <p><strong>Status:</strong> {callouts[consultation.id].calloutStatus}</p>
                      </div>
                    )}


                    <span
                      className={`inline-block text-xs px-2 py-1 mt-1 rounded-full font-medium ${timingColor}`}
                    >
                      {timing}
                    </span>

                    <div className="flex gap-2 mt-3 flex-wrap">
                      <button
                        onClick={() => setSelectedConsultation(consultation)}
                        className="p-2 bg-blue-100 rounded-full hover:bg-blue-200"
                        title="View Details"
                      >
                        <Eye className="w-5 h-5 text-blue-600" />
                      </button>

                      <button
                        onClick={() => setViewingNotes(consultation)}
                        className="p-2 bg-green-100 rounded-full hover:bg-green-200"
                        title="View Notes"
                      >
                        <NotebookPen className="w-5 h-5 text-green-600" />
                      </button>

                      <button
                        onClick={() => handleStartCall(consultation)}
                        className={`p-2 rounded-full transition ${isPastDue ? 'bg-red-100 hover:bg-red-200' : 'bg-gray-100 cursor-not-allowed opacity-50'}`}
                        title={isPastDue ? 'Start Video Call' : 'Available after scheduled time'}
                        disabled={!isPastDue}
                      >
                        <Video className="w-5 h-5 text-red-600" />
                      </button>

                      <button
                        onClick={() => {
                          setCallingOutConsultation(consultation);
                          setCallOutMessage('');
                        }}
                        className="p-2 bg-purple-100 rounded-full hover:bg-purple-200"
                        title="Request Call Out"
                      >
                        <Home className="w-5 h-5 text-purple-600" />
                      </button>
                      
                      <button
                        onClick={() => {
                          setEditingStatus(consultation);
                          setNewStatus(consultation.status);
                          setStatusError('');
                        }}
                        className="p-2 bg-yellow-100 rounded-full hover:bg-yellow-200"
                        title="Change Status"
                      >
                        <Edit3 className="w-5 h-5 text-yellow-600" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {selectedConsultation && (
        <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={() => setSelectedConsultation(null)}>
              &times;
            </button>
            <h3 className="text-lg font-semibold mb-2">Consultation Details</h3>
            <div className="space-y-1 text-sm text-gray-700">
              <p><strong>Doctor:</strong> {selectedConsultation.doctor?.doctorProfile?.firstName} {selectedConsultation.doctor?.doctorProfile?.lastName}</p>
              <p><strong>Email:</strong> {selectedConsultation.doctor?.email}</p>
              <p><strong>Date:</strong> {new Date(selectedConsultation.scheduledAt).toLocaleString()}</p>
              <p><strong>Status:</strong> {selectedConsultation.status}</p>
              <p><strong>Type:</strong> {selectedConsultation.type}</p>
            </div>
          </div>
        </div>
      )}

      {viewingNotes && (
        <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={() => setViewingNotes(null)}>
              &times;
            </button>
            <h3 className="text-lg font-semibold mb-2">Doctor&apos;s Notes</h3>
            <div className="text-sm text-gray-700 whitespace-pre-wrap">
              {viewingNotes.notes ? viewingNotes.notes : "No notes available for this consultation."}
            </div>
          </div>
        </div>
      )}

      {editingStatus && (
        <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-sm w-full relative">
            <button className="absolute top-2 right-2 text-gray-500 hover:text-gray-700 text-2xl" onClick={() => setEditingStatus(null)}>
              &times;
            </button>
            <h3 className="text-lg font-semibold mb-3">Change Status</h3>
            <label className="block text-sm font-medium text-gray-700 mb-1">Select new status</label>
            <select
              value={newStatus}
              onChange={(e) => setNewStatus(e.target.value)}
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
            >
              <option value="">-- Select Status --</option>
              <option value="active">Active</option>
              <option value="completed">Completed</option>
            </select>
            {statusError && <p className="text-sm text-red-500 mt-1">{statusError}</p>}
            <div className="flex justify-end mt-4 gap-2">
              <button className="px-4 py-2 text-sm bg-gray-200 rounded hover:bg-gray-300" onClick={() => setEditingStatus(null)}>Cancel</button>
              <button className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700" onClick={handleStatusChange}>Update</button>
            </div>
          </div>
        </div>
      )}

      {callingOutConsultation && (
        <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={() => setCallingOutConsultation(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">
              You are requesting a doctor to visit your location in person.
            </p>

            {/* New Callout Option Dropdown */}
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Select Response Time
            </label>
            <select
              value={callOutTimeOption}
              onChange={(e) => setCallOutTimeOption(e.target.value)}
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm mb-3"
            >
              <option value="">-- Select preferred time --</option>
              <option value="within_45mins">Within 45 mins – N120,000</option>
              <option value="1hr_45mins">Within 1 hr 45 mins – N75,000</option>
              <option value="3_5hrs">Within 3–5 hrs – N45,000</option>
            </select>

            <textarea
              value={callOutMessage}
              onChange={(e) => setCallOutMessage(e.target.value)}
              placeholder="Add any details or instructions for the doctor (optional)..."
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm mb-3"
              rows={4}
            />

            <div className="flex justify-end gap-2">
              <button
                className="px-4 py-2 text-sm bg-gray-200 rounded hover:bg-gray-300"
                onClick={() => setCallingOutConsultation(null)}
              >
                Cancel
              </button>
              <button
                className="px-4 py-2 text-sm bg-purple-600 text-white rounded hover:bg-purple-700"
                onClick={handleRequestCallOut}
              >
                Send Request
              </button>
            </div>
          </div>
        </div>
      )}

      

    </div>
  );
}