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

function Doctors() {
  const [doctors, setDoctors] = useState([]);
  const [doctorName, setDoctorName] = useState('');
  const [specialization, setSpecialization] = useState('');
  const [email, setEmail] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  
  // Imiziro yo guhindura amakuru (Edit States)
  const [isEditing, setIsEditing] = useState(false);
  const [editingId, setEditingId] = useState('');

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

  const fetchDoctors = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/doctors');
      setDoctors(res.data);
    } catch (err) {
      console.error("Error loading doctors:", err);
    }
  };

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

  // SAVE OR UPDATE SUBMIT HANDLER
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    const token = localStorage.getItem('hospital_token');
    const config = { headers: { Authorization: `Bearer ${token}` } };

     try {
      if (isEditing) {
        // ONGERAHO config KURI PUT
        await axios.put(`http://localhost:5000/api/doctors/${editingId}`, { doctorName, specialization, email }, config);
        setSuccess('Doctor records updated successfully!');
      } else {
        // ONGERAHO config KURI POST
        await axios.post('http://localhost:5000/api/doctors', { doctorName, specialization, email }, config);
        setSuccess('Doctor registered successfully!');
      }
      
      setDoctorName('');
      setSpecialization('');
      setEmail('');
      setIsEditing(false);
      setEditingId('');
      fetchDoctors();
    } catch (err) {
      setError(err.response?.data?.message || 'Error processing request.');
    }
  };

  const handleEdit = (doc) => {
    setIsEditing(true);
    setEditingId(doc.DoctorId);
    setDoctorName(doc.doctorName);
    setSpecialization(doc.specialization);
    setEmail(doc.email);
  };

    const handleDelete = async (id) => {
    if (window.confirm('Are you sure you want to remove this doctor from the system?')) {
      
      // >>> SHYIRA UYU MURONGO HANO MBERE YA TRY <<<
      const token = localStorage.getItem('hospital_token');
      const config = { headers: { Authorization: `Bearer ${token}` } };

      try {
        // ONGERAHO config KURI DELETE
        await axios.delete(`http://localhost:5000/api/doctors/${id}`, config);
        setSuccess('Doctor removed from system.');
        fetchDoctors();
      } catch (err) {
        setError(err.response?.data?.message || 'Failed to remove doctor.');
      }
    }
  };

  const filteredDoctors = doctors.filter(doc => 
    doc.doctorName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    doc.specialization.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      
      <div className="bg-white border border-slate-200 rounded-2xl shadow-sm p-6 h-fit">
        <h3 className="text-sm font-black text-slate-700 uppercase tracking-widest border-b border-slate-100 pb-3 mb-4">
          {isEditing ? '📝 Edit Doctor Records' : '🩺 Register Doctor'}
        </h3>

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

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Full Name</label>
            <input type="text" placeholder="Dr. Jean de Dieu" value={doctorName} onChange={(e) => setDoctorName(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 focus:outline-none focus:border-teal-500" required />
          </div>

          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Specialization</label>
            <input type="text" placeholder="e.g. Cardiologist" value={specialization} onChange={(e) => setSpecialization(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 focus:outline-none focus:border-teal-500" required />
          </div>

          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Email Address</label>
            <input type="email" placeholder="doctor@hospital.com" value={email} onChange={(e) => setEmail(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 focus:outline-none focus:border-teal-500" required />
          </div>

          <div className="pt-2 flex gap-2">
            <button type="submit" className="flex-1 bg-teal-600 hover:bg-teal-700 text-white font-bold py-2.5 rounded-xl text-sm transition shadow-md shadow-teal-600/10 cursor-pointer">
              {isEditing ? 'Update Records' : 'Save Doctor Record'}
            </button>
            {isEditing && (
              <button type="button" onClick={() => { setIsEditing(false); setDoctorName(''); setSpecialization(''); setEmail(''); }} className="bg-slate-200 hover:bg-slate-300 text-slate-700 font-bold py-2.5 px-4 rounded-xl text-xs transition cursor-pointer">
                Cancel
              </button>
            )}
          </div>
        </form>
      </div>

      <div className="bg-white border border-slate-200 rounded-2xl shadow-sm p-6 lg:col-span-2 space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-3">
          <h3 className="text-sm font-black text-slate-700 uppercase tracking-widest">Medical Practitioners ({filteredDoctors.length})</h3>
          <input type="text" placeholder="🔍 Search practitioners..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="bg-slate-50 border border-slate-300 rounded-xl px-4 py-2 text-xs text-slate-800 focus:outline-none focus:border-teal-500 w-full sm:w-64 shadow-inner" />
        </div>

        <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">Doctor Name</th>
                <th className="p-3">Specialization</th>
                <th className="p-3">Email</th>
                <th className="p-3 text-center">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filteredDoctors.length === 0 ? (
                <tr><td colSpan="4" className="p-4 text-center text-slate-400 italic">No doctor entries registered yet.</td></tr>
              ) : (
                filteredDoctors.map((doc) => (
                  <tr key={doc.DoctorId} className="hover:bg-slate-50 transition">
                    <td className="p-3 text-slate-900 font-bold">{doc.doctorName}</td>
                    <td className="p-3"><span className="bg-teal-50 text-teal-700 px-2.5 py-1 rounded-full font-semibold">{doc.specialization}</span></td>
                    <td className="p-3 text-slate-500">{doc.email}</td>
                    <td className="p-3 flex items-center justify-center gap-2">
                      <button onClick={() => handleEdit(doc)} className="bg-amber-50 hover:bg-amber-500 text-amber-700 hover:text-white px-2.5 py-1.5 rounded-xl font-bold transition cursor-pointer text-[10px]">
                        Edit
                      </button>
                      <button onClick={() => handleDelete(doc.DoctorId)} className="bg-red-50 hover:bg-red-500 text-red-650 hover:text-white px-2.5 py-1.5 rounded-xl font-bold transition cursor-pointer text-[10px]">
                        Remove
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

    </div>
  );
}

export default Doctors;
