const { useState, useEffect, useRef } = React;

const FacultyMaster = () => {
  const [faculties, setFaculties] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState(null);
  
  const [formData, setFormData] = useState({
    salutation: 'Mr.',
    first_name: '',
    middle_name: '',
    last_name: '',
    mobile_number: '',
    email: '',
    dept_id: '',
    designation: '',
    highest_qualification: '',
    date_of_joining: '',
    photograph: '',
    role: ['Faculty'],
    hod_dept_id: '',
    password: ''
  });

  const fileInputRef = useRef(null);

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

  const fetchData = async () => {
    setLoading(true);
    try {
      const [facRes, deptRes] = await Promise.all([
        fetch('/api/faculties'),
        fetch('/api/departments') // Assuming this exists, fallback to empty if not
      ]);
      if (facRes.ok) {
        const facData = await facRes.json();
        setFaculties(facData);
      }
      if (deptRes.ok) {
        const deptData = await deptRes.json();
        setDepartments(deptData);
      }
    } catch (err) {
      console.error('Error fetching data', err);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    if (name === 'role') {
      setFormData(prev => {
        const roles = [...prev.role];
        if (checked) {
          if (!roles.includes(value)) roles.push(value);
        } else {
          const index = roles.indexOf(value);
          if (index > -1) roles.splice(index, 1);
        }
        return { ...prev, role: roles };
      });
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setFormData(prev => ({ ...prev, photograph: reader.result }));
      };
      reader.readAsDataURL(file);
    }
  };

  const removePhoto = () => {
    setFormData(prev => ({ ...prev, photograph: '' }));
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const url = editingId ? `/api/faculties/${editingId}` : '/api/faculties';
      const method = editingId ? 'PUT' : 'POST';
      
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          role: formData.role.join(',')
        })
      });
      
      if (res.ok) {
        alert(`Faculty ${editingId ? 'updated' : 'added'} successfully!`);
        resetForm();
        fetchData();
      } else {
        const data = await res.json();
        alert(data.error || 'Failed to save faculty');
      }
    } catch (err) {
      console.error(err);
      alert('Network error');
    }
  };

  const handleEdit = (faculty) => {
    setEditingId(faculty.id);
    setFormData({
      salutation: faculty.salutation || 'Mr.',
      first_name: faculty.first_name || '',
      middle_name: faculty.middle_name || '',
      last_name: faculty.last_name || '',
      mobile_number: faculty.mobile_number || '',
      email: faculty.email || '',
      dept_id: faculty.dept_id || '',
      designation: faculty.designation || '',
      highest_qualification: faculty.highest_qualification || '',
      date_of_joining: faculty.date_of_joining || '',
      photograph: faculty.photograph || '',
      role: faculty.role ? faculty.role.split(',') : ['Faculty'],
      hod_dept_id: faculty.hod_dept_id || '',
      password: ''
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    if (!confirm('Are you sure you want to delete this faculty member?')) return;
    try {
      const res = await fetch(`/api/faculties/${id}`, { method: 'DELETE' });
      if (res.ok) {
        fetchData();
      } else {
        alert('Failed to delete');
      }
    } catch (err) {
      console.error(err);
      alert('Network error');
    }
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData({
      salutation: 'Mr.',
      first_name: '',
      middle_name: '',
      last_name: '',
      mobile_number: '',
      email: '',
      dept_id: '',
      designation: '',
      highest_qualification: '',
      date_of_joining: '',
      photograph: '',
      role: ['Faculty'],
      hod_dept_id: '',
      password: ''
    });
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  return (
    <div className="animate-fade-in-up space-y-6">
      <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
        <h2 className="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2">
          <span className="bg-blue-100 text-blue-600 p-2 rounded-lg">👨‍🏫</span>
          {editingId ? 'Edit Faculty Profile' : 'Add New Faculty'}
        </h2>

        <form onSubmit={handleSubmit}>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            
            {/* Column 1: Photo Upload */}
            <div className="md:col-span-1 flex flex-col items-center space-y-4">
              <div className="w-40 h-40 border-2 border-dashed border-gray-300 rounded-xl flex items-center justify-center bg-gray-50 overflow-hidden relative group">
                {formData.photograph ? (
                  <>
                    <img src={formData.photograph} alt="Preview" className="w-full h-full object-cover" />
                    <button type="button" onClick={removePhoto} className="absolute inset-0 bg-black/50 text-white opacity-0 group-hover:opacity-100 transition flex items-center justify-center font-semibold">
                      Remove
                    </button>
                  </>
                ) : (
                  <span className="text-gray-400 text-sm font-medium">No Photo</span>
                )}
              </div>
              <input 
                type="file" 
                accept="image/*"
                onChange={handleFileChange}
                ref={fileInputRef}
                className="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
              />
            </div>

            {/* Column 2 & 3: Form Fields */}
            <div className="md:col-span-3 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Salutation</label>
                <select name="salutation" value={formData.salutation} onChange={handleChange} className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                  <option value="Mr.">Mr.</option>
                  <option value="Ms.">Ms.</option>
                  <option value="Mrs.">Mrs.</option>
                  <option value="Dr.">Dr.</option>
                  <option value="Prof.">Prof.</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">First Name</label>
                <input type="text" name="first_name" value={formData.first_name} onChange={handleChange} required className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Middle Name</label>
                <input type="text" name="middle_name" value={formData.middle_name} onChange={handleChange} className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Last Name</label>
                <input type="text" name="last_name" value={formData.last_name} onChange={handleChange} required className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Email</label>
                <input type="email" name="email" value={formData.email} onChange={handleChange} required className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Mobile Number</label>
                <input type="tel" name="mobile_number" value={formData.mobile_number} onChange={handleChange} className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Department</label>
                <select name="dept_id" value={formData.dept_id} onChange={handleChange} required className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none bg-white">
                  <option value="">Select Dept...</option>
                  {departments.map(d => (
                    <option key={d.id} value={d.id}>{d.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Designation</label>
                <input type="text" name="designation" value={formData.designation} onChange={handleChange} required className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" placeholder="e.g. Lecturer" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Highest Qualification</label>
                <input type="text" name="highest_qualification" value={formData.highest_qualification} onChange={handleChange} className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" placeholder="e.g. M.Tech, Ph.D" />
              </div>

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Date of Joining</label>
                <input type="date" name="date_of_joining" value={formData.date_of_joining} onChange={handleChange} className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

              <div className="sm:col-span-2 lg:col-span-3">
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-2">System Roles (Select all that apply)</label>
                <div className="flex flex-wrap gap-4 p-3 border border-gray-300 rounded-lg bg-gray-50">
                  {['Faculty', 'HOD', 'Assistant', 'Principal', 'Administrator'].map(role => (
                    <label key={role} className="flex items-center gap-2 cursor-pointer hover:text-blue-600 transition">
                      <input 
                        type="checkbox" 
                        name="role" 
                        value={role} 
                        checked={formData.role.includes(role)} 
                        onChange={handleChange}
                        className="w-4 h-4 rounded text-blue-600 focus:ring-blue-500 border-gray-300"
                      />
                      <span className="text-sm font-medium">{role}</span>
                    </label>
                  ))}
                </div>
              </div>

              {formData.role.includes('HOD') && (
                <div>
                  <label className="block text-xs font-semibold text-gray-600 uppercase mb-1 text-blue-700">Heads Department</label>
                  <select name="hod_dept_id" value={formData.hod_dept_id} onChange={handleChange} required className="w-full p-2.5 border-2 border-blue-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none bg-blue-50 font-semibold">
                    <option value="">Select Dept...</option>
                    {departments.map(d => (
                      <option key={d.id} value={d.id}>{d.name}</option>
                    ))}
                  </select>
                </div>
              )}

              <div>
                <label className="block text-xs font-semibold text-gray-600 uppercase mb-1">Login Password</label>
                <input type="password" name="password" value={formData.password} onChange={handleChange} placeholder="Leave blank to keep current" className="w-full p-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" />
              </div>

            </div>
          </div>

          <div className="mt-8 flex justify-end gap-3 border-t pt-4">
            <button type="button" onClick={resetForm} className="px-5 py-2.5 text-gray-600 font-semibold hover:bg-gray-100 rounded-lg transition">
              Cancel
            </button>
            <button type="submit" className="px-6 py-2.5 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 shadow-md transition">
              {editingId ? 'Update Faculty' : 'Save Faculty'}
            </button>
          </div>
        </form>
      </div>

      {/* Data Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
          <h3 className="font-bold text-gray-800">Registered Faculty</h3>
          <span className="text-sm font-semibold bg-gray-200 text-gray-700 px-3 py-1 rounded-full">{faculties.length} Total</span>
        </div>
        <div className="overflow-x-auto">
          {loading ? (
             <div className="p-8 text-center text-gray-500">Loading directory...</div>
          ) : (
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider">
                  <th className="p-4 font-semibold">Profile</th>
                  <th className="p-4 font-semibold">Name</th>
                  <th className="p-4 font-semibold">Department</th>
                  <th className="p-4 font-semibold">Contact</th>
                  <th className="p-4 font-semibold">Qualification</th>
                  <th className="p-4 font-semibold text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {faculties.map(fac => (
                  <tr key={fac.id} className="hover:bg-blue-50/50 transition">
                    <td className="p-4">
                      {fac.photograph ? (
                        <img src={fac.photograph} alt={fac.first_name} className="w-12 h-12 rounded-full object-cover border border-gray-200 shadow-sm" />
                      ) : (
                        <div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center text-gray-500 font-bold text-lg">
                          {fac.first_name?.charAt(0) || fac.name?.charAt(0) || '?'}
                        </div>
                      )}
                    </td>
                    <td className="p-4">
                      <div className="font-bold text-gray-900">{fac.salutation} {fac.first_name} {fac.last_name}</div>
                      <div className="text-xs text-blue-600 font-semibold">{fac.designation}</div>
                    </td>
                    <td className="p-4 text-sm text-gray-700 font-medium">
                      {fac.Department ? fac.Department.name : (fac.dept_id || '-')}
                    </td>
                    <td className="p-4">
                      <div className="text-sm text-gray-800">{fac.mobile_number || '-'}</div>
                      <div className="text-xs text-gray-500">{fac.email}</div>
                    </td>
                    <td className="p-4 text-sm text-gray-700">
                      {fac.highest_qualification || '-'}
                    </td>
                    <td className="p-4 text-right">
                      <button onClick={() => handleEdit(fac)} className="text-blue-600 hover:bg-blue-100 p-2 rounded-lg transition mr-2">Edit</button>
                      <button onClick={() => handleDelete(fac.id)} className="text-red-600 hover:bg-red-100 p-2 rounded-lg transition">Delete</button>
                    </td>
                  </tr>
                ))}
                {faculties.length === 0 && (
                  <tr>
                    <td colSpan="6" className="p-8 text-center text-gray-500">No faculty members found. Add one above.</td>
                  </tr>
                )}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
};

window.FacultyMaster = FacultyMaster;
