import { useEffect, useState } from 'react';
import axios from 'axios';

function Appointments() {
  const [appointments, setAppointments] = useState([]);
  const [patients, setPatients] = useState([]);
  const [doctors, setDoctors] = useState([]);

  const [PatientId, setPatientId] = useState('');
  const [DoctorId, setDoctorId] = useState('');
  const [appointmentDate, setAppointmentDate] = useState('');
  const [prescription, setPrescription] = useState('');
  const [consultationFee, setConsultationFee] = useState('');
  const [medicationFee, setMedicationFee] = useState('');

  // Invoice States
  const [showBill, setShowBill] = useState(false);
  const [selectedBill, setSelectedBill] = useState(null);

  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const fetchData = async () => {
    try {
      const resApps = await axios.get('http://localhost:5000/api/appointments');
      setAppointments(resApps.data);

      const resPats = await axios.get('http://localhost:5000/api/patients');
      setPatients(resPats.data);

      const resDocs = await axios.get('http://localhost:5000/api/doctors');
      setDoctors(resDocs.data);
    } catch (err) {
      console.error(err);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    setError('');
    setSuccess('');

    try {
      await axios.post('http://localhost:5000/api/appointments', {
        PatientId: Number(PatientId),
        DoctorId: Number(DoctorId),
        appointmentDate,
        prescription,
        consultationFee: Number(consultationFee),
        medicationFee: Number(medicationFee),
      });

      setSuccess('Appointment and invoice scheduled cleanly!');

      setPatientId('');
      setDoctorId('');
      setAppointmentDate('');
      setPrescription('');
      setConsultationFee('');
      setMedicationFee('');

      fetchData();
    } catch (err) {
      setError(err.response?.data?.message || 'Booking failed.');
    }
  };

  const handleOpenBill = (app) => {
    setSelectedBill(app);
    setShowBill(true);
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

      {/* FORM AREA */}
      <div className="bg-white border border-slate-200 rounded-2xl shadow-sm p-6 h-fit space-y-4">
        <h3 className="text-sm font-black text-slate-700 uppercase tracking-widest border-b border-slate-100 pb-3">
          📅 Clinical Consultation & Bill
        </h3>

        {error && (
          <div className="bg-red-50 text-red-600 border border-red-100 p-3 rounded-xl text-xs font-medium">
            ⚠️ {error}
          </div>
        )}

        {success && (
          <div className="bg-teal-50 text-teal-600 border border-teal-100 p-3 rounded-xl text-xs font-semibold">
            ✅ {success}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">

          {/* Patient */}
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">
              Select Patient
            </label>

            <select
              value={PatientId}
              onChange={(e) => setPatientId(e.target.value)}
              className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800"
              required
            >
              <option value="">-- Choose Patient --</option>

              {patients.map((p) => (
                <option key={p.PatientId} value={p.PatientId}>
                  {p.patientName}
                </option>
              ))}
            </select>
          </div>

          {/* Doctor */}
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">
              Select Doctor
            </label>

            <select
              value={DoctorId}
              onChange={(e) => setDoctorId(e.target.value)}
              className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800"
              required
            >
              <option value="">-- Choose Doctor --</option>

              {doctors.map((d) => (
                <option key={d.DoctorId} value={d.DoctorId}>
                  {d.doctorName} ({d.specialization})
                </option>
              ))}
            </select>
          </div>

          {/* Appointment Date */}
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">
              Appointment Date
            </label>

            <input
              type="date"
              value={appointmentDate}
              onChange={(e) => setAppointmentDate(e.target.value)}
              className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800"
              required
            />
          </div>

          {/* Prescription */}
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">
              Prescription (Imiti Yanditswe)
            </label>

            <textarea
              placeholder="e.g. Paracetamol 500mg, Amoxicillin"
              value={prescription}
              onChange={(e) => setPrescription(e.target.value)}
              className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2 text-sm text-slate-800 h-16 focus:outline-none"
            />
          </div>

          {/* Fees */}
          <div className="grid grid-cols-2 gap-3">

            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-600 uppercase">
                Consult Fee (RWF)
              </label>

              <input
                type="number"
                placeholder="5000"
                value={consultationFee}
                onChange={(e) => setConsultationFee(e.target.value)}
                className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800"
              />
            </div>

            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-600 uppercase">
                Medication Fee
              </label>

              <input
                type="number"
                placeholder="2500"
                value={medicationFee}
                onChange={(e) => setMedicationFee(e.target.value)}
                className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800"
              />
            </div>

          </div>

          {/* Submit Button */}
          <button
            type="submit"
            className="w-full bg-teal-600 hover:bg-teal-700 text-white font-bold py-2.5 rounded-xl text-sm cursor-pointer shadow-md"
          >
            Schedule & Invoice
          </button>

        </form>
      </div>

      {/* LIST AREA */}
      <div className="bg-white border border-slate-200 rounded-2xl shadow-sm p-6 lg:col-span-2 space-y-4">

        <h3 className="text-sm font-black text-slate-700 uppercase tracking-widest border-b border-slate-100 pb-3">
          Clinical Booking Journal ({appointments.length})
        </h3>

        <div className="overflow-x-auto">

          <table className="w-full text-left border-collapse text-xs text-slate-600">

            <thead>
              <tr className="border-b border-slate-200 bg-slate-50 text-slate-500 font-bold uppercase tracking-wider">
                <th className="p-3">Patient</th>
                <th className="p-3">Doctor</th>
                <th className="p-3">Total Bill</th>
                <th className="p-3 text-center">Action</th>
              </tr>
            </thead>

            <tbody className="divide-y divide-slate-100">

              {appointments.map((app) => (
                <tr
                  key={app.AppointmentId}
                  className="hover:bg-slate-50 transition"
                >
                  <td className="p-3 text-slate-900 font-bold">
                    {app.patientName}
                  </td>

                  <td className="p-3 text-teal-700 font-semibold">
                    Dr. {app.doctorName}
                  </td>

                  <td className="p-3 font-bold text-slate-800">
                    {(
                      Number(app.consultationFee || 0) +
                      Number(app.medicationFee || 0)
                    ).toLocaleString()} RWF
                  </td>

                  <td className="p-3 text-center">
                    <button
                      onClick={() => handleOpenBill(app)}
                      className="bg-blue-50 hover:bg-blue-600 text-blue-600 hover:text-white px-2.5 py-1.5 rounded-xl font-bold transition text-[10px]"
                    >
                      📄 View Bill
                    </button>
                  </td>
                </tr>
              ))}

            </tbody>
          </table>

        </div>
      </div>

      {/* MEDICAL BILL POPUP MODAL */}
      {showBill && selectedBill && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">

          <div className="bg-white rounded-2xl shadow-2xl p-6 max-w-md w-full border border-slate-200">

            <div id="hospital-invoice" className="space-y-4">

              {/* Header */}
              <div className="text-center border-b pb-3">
                <h2 className="text-lg font-black text-slate-800">
                  HMS CLINIC RECEIPT
                </h2>

                <p className="text-[10px] text-slate-400">
                  Rubavu, Western Province
                </p>
              </div>

              {/* Patient Info */}
              <div className="text-xs space-y-1 text-slate-600 border-b pb-3">

                <div>
                  <strong>Patient Name:</strong> {selectedBill.patientName}
                </div>

                <div>
                  <strong>Assigned Consultant:</strong> Dr.{' '}
                  {selectedBill.doctorName} ({selectedBill.specialization})
                </div>

                <div>
                  <strong>Date:</strong>{' '}
                  {new Date(selectedBill.appointmentDate).toLocaleDateString('en-GB')}
                </div>

              </div>

              {/* Prescription */}
              <div className="text-xs bg-slate-50 p-2.5 rounded-xl text-slate-700">

                <strong>Prescription / Imiti:</strong>

                <p className="mt-1 font-medium text-slate-600">
                  {selectedBill.prescription || 'No medication prescribed.'}
                </p>

              </div>

              {/* Bill Summary */}
              <div className="text-xs space-y-2 border-t pt-3">

                <div className="flex justify-between">
                  <span>Consultation Service:</span>

                  <span className="font-semibold">
                    {Number(selectedBill.consultationFee || 0).toLocaleString()} RWF
                  </span>
                </div>

                <div className="flex justify-between">
                  <span>Pharmacy Medication:</span>

                  <span className="font-semibold">
                    {Number(selectedBill.medicationFee || 0).toLocaleString()} RWF
                  </span>
                </div>

                <div className="flex justify-between text-sm font-black text-slate-900 border-t border-dashed pt-2">

                  <span>TOTAL MEDICAL CHARGE:</span>

                  <span className="text-teal-600">
                    {(
                      Number(selectedBill.consultationFee || 0) +
                      Number(selectedBill.medicationFee || 0)
                    ).toLocaleString()} RWF
                  </span>

                </div>

              </div>
            </div>

            {/* Buttons */}
            <div className="mt-6 flex gap-3">

              <button
                onClick={() => window.print()}
                className="flex-1 bg-slate-900 hover:bg-slate-800 text-white font-bold py-2 rounded-xl text-xs transition cursor-pointer text-center"
              >
                🖨️ Print Invoice
              </button>

              <button
                onClick={() => setShowBill(false)}
                className="bg-slate-200 hover:bg-slate-300 text-slate-700 font-bold py-2 px-4 rounded-xl text-xs transition cursor-pointer"
              >
                Close
              </button>

            </div>

          </div>
        </div>
      )}

    </div>
  );
}

export default Appointments;