'use client';

import { useState, useEffect } from 'react';
import { Home, Plus, X } from 'lucide-react';

export default function CalloutRequestPage() {
  const [showModal, setShowModal] = useState(false);
  const [callOutMessage, setCallOutMessage] = useState('');
  const [callOutTimeOption, setCallOutTimeOption] = useState('');
  const [callouts, setCallouts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchCallouts = async () => {
      try {
        const res = await fetch('/api/callouts/standalone', {
          method: 'GET',
          credentials: 'include',
        });
        const data = await res.json();
        setCallouts(Array.isArray(data.callouts) ? data.callouts : []);
      } catch (err) {
        console.error('Failed to fetch callouts:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchCallouts();
  }, []);

  const handleSendCallout = async () => {
    if (!callOutMessage.trim() && !callOutTimeOption) {
      alert('Please provide a message or select a response time.');
      return;
    }

    try {
      const res = await fetch(`/api/callouts/standalone`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          message: callOutMessage,
          callOutTimeOption: callOutTimeOption,
        }),
      });

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

      alert('Callout request sent successfully');
      setShowModal(false);
      setCallOutMessage('');
      setCallOutTimeOption('');
      setCallouts((prev) => [data, ...prev]);
    } catch (err) {
      alert(err.message || 'Something went wrong.');
    }
  };

  return (
    <main className="p-4 max-w-3xl mx-auto">
      {/* Request Section */}
      <div className="bg-white rounded-xl shadow-lg p-6 mb-8">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold">Request a Doctor Callout</h2>
          <button
            onClick={() => setShowModal(true)}
            className="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700 flex items-center gap-2"
          >
            <Plus size={16} />
            Request Callout
          </button>
        </div>
        <p className="text-sm text-gray-600">
          Need a doctor at your location? Submit a callout request and a doctor will be assigned.
        </p>
      </div>

      {/* Callout History */}
      <div>
        <h3 className="text-lg font-semibold mb-4">Your Previous Callout Requests</h3>
        {loading ? (
          <p className="text-sm text-gray-500">Loading...</p>
        ) : callouts.length === 0 ? (
          <p className="text-sm text-gray-500">You haven’t made any callout requests yet.</p>
        ) : (
          <div className="space-y-4">
            {callouts.map((callout) => (
              <div
                key={callout.id}
                className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm"
              >
                <div className="flex justify-between items-center mb-2">
                  <span className="text-sm font-medium text-purple-700">
                    Expected Time: {formatTimeOption(callout.callOutTimeOption)}
                  </span>
                  <span
                    className={`text-xs px-2 py-1 rounded-full ${getStatusColor(callout.status)}`}
                  >
                    {formatStatus(callout.status)}
                  </span>
                </div>
                <p className="text-sm text-gray-700 mb-1">
                  <strong>Message:</strong> {callout.message}
                </p>
                {callout.doctor && (
                  <p className="text-xs text-gray-500">
                    Assigned Doctor: {callout.doctor.firstName} {callout.doctor.lastName}
                  </p>
                )}
                <p className="text-xs text-gray-400">
                  Created at: {new Date(callout.createdAt).toLocaleString()}
                </p>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-50 flex justify-center items-center p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 relative">
            <button
              onClick={() => setShowModal(false)}
              className="absolute top-2 right-2 text-gray-500 hover:text-gray-700"
            >
              <X size={20} />
            </button>

            <h3 className="text-lg font-semibold mb-2">Request a Standalone Callout</h3>
            <p className="text-sm text-gray-500 mb-4">
              Provide your symptoms or instructions and select a response time.
            </p>

            <div className="mb-3">
              <label className="text-sm font-medium block mb-1">Preferred 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"
              >
                <option value="">-- Select time --</option>
                <option value="within_45mins">Within 45 mins – ₦120,000</option>
                <option value="1hr_45mins">Within 1 hr 45 mins – ₦75,000</option>
                <option value="3_5hrs">Within 3–5 hrs – ₦45,000</option>
              </select>
            </div>

            <div className="mb-4">
              <label className="text-sm font-medium block mb-1">Message</label>
              <textarea
                value={callOutMessage}
                onChange={(e) => setCallOutMessage(e.target.value)}
                rows={4}
                className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
                placeholder="Add notes, symptoms, or directions..."
              />
            </div>

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

// Utility functions
function formatTimeOption(option) {
  switch (option) {
    case 'within_45mins':
      return 'Within 45 mins';
    case '1hr_45mins':
      return 'Within 1 hr 45 mins';
    case '3_5hrs':
      return 'Within 3–5 hrs';
    default:
      return 'Unknown';
  }
}

function formatStatus(status) {
  switch (status) {
    case 'pending':
      return 'Pending';
    case 'accepted':
      return 'Accepted';
    case 'rejected':
      return 'Rejected';
    default:
      return status || 'Unknown';
  }
}

function getStatusColor(status) {
  switch (status) {
    case 'pending':
      return 'bg-yellow-100 text-yellow-700';
    case 'accepted':
      return 'bg-green-100 text-green-700';
    case 'rejected':
      return 'bg-red-100 text-red-700';
    default:
      return 'bg-gray-100 text-gray-700';
  }
}
