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

function Patients() {
  const [patients, setPatients] = useState([]);
  const [patientName, setPatientName] = useState('');
  const [age, setAge] = useState('');
  const [gender, setGender] = useState('Male');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // 1. KUREBA ABARWAYI BOSE KURI BACKEND (GET)
  const fetchPatients = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/patients');
      setPatients(res.data);
    } catch (err) {
      console.error("Error loading patients:", err);
    }
  };

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

  // 2. KUBIKA UMURWAYI GISHYA (POST)
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    try {
      await axios.post('http://localhost:5000/api/patients', {
        patientName,
        age: Number(age),
        gender,
        phoneNumber
      });
      setSuccess('Patient admitted successfully!');
      setPatientName('');
      setAge('');
      setGender('Male');
      setPhoneNumber('');
      fetchPatients(); // Refresh urutonde
    } catch (err) {
      setError(err.response?.data?.message || 'Error saving patient.');
    }
  };

  // 3. GUSHAKISHA KURI FRONTEND
  const filteredPatients = patients.filter(pat => 
    pat.patientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    String(pat.phoneNumber).includes(searchQuery)
  );

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      
      {/* COLUMN 1: IFISHI YO KWANDIKA ABARWAYI */}
      <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">
          🛌 Admit Patient
        </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">Patient Name</label>
            <input type="text" placeholder="e.g. Keza Alice" value={patientName} onChange={(e) => setPatientName(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="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-600 uppercase">Age (Imyaka)</label>
              <input type="number" placeholder="25" value={age} onChange={(e) => setAge(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" min="0" required />
            </div>

            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-600 uppercase">Gender</label>
              <select value={gender} onChange={(e) => setGender(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 cursor-pointer">
                <option value="Male">Male</option>
                <option value="Female">Female</option>
              </select>
            </div>
          </div>

          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Phone Number</label>
            <input type="text" placeholder="0788000000" value={phoneNumber} onChange={(e) => setPhoneNumber(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" />
          </div>

          <button type="submit" className="w-full 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">
            Save Patient File
          </button>
        </form>
      </div>

      {/* COLUMN 2 & 3: URUTONDE RW'ABARWAYI */}
      <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">
            Admitted Patients ({filteredPatients.length})
          </h3>
          <input
            type="text"
            placeholder="🔍 Search patient by name..."
            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">ID</th>
                <th className="p-3">Patient Name</th>
                <th className="p-3">Age</th>
                <th className="p-3">Gender</th>
                <th className="p-3">Phone</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filteredPatients.length === 0 ? (
                <tr>
                  <td colSpan="5" className="p-4 text-center text-slate-400 italic">No patient files found.</td>
                </tr>
              ) : (
                filteredPatients.map((pat) => (
                  <tr key={pat.PatientId} className="hover:bg-slate-50 transition">
                    <td className="p-3 font-mono text-slate-400">#P0{pat.PatientId}</td>
                    <td className="p-3 text-slate-900 font-bold">{pat.patientName}</td>
                    <td className="p-3 text-slate-700 font-medium">{pat.age} yrs</td>
                    <td className="p-3">
                      <span className={`px-2.5 py-0.5 rounded-full font-semibold text-[10px] uppercase ${pat.gender === 'Male' ? 'bg-blue-50 text-blue-700' : 'bg-pink-50 text-pink-750'}`}>
                        {pat.gender}
                      </span>
                    </td>
                    <td className="p-3 text-slate-500">{pat.phoneNumber || 'N/A'}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

    </div>
  );
}

export default Patients;
