import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Users, X, Pencil, Trash } from '@phosphor-icons/react';
import { Search, Filter } from 'lucide-react';
import axios from 'axios';
import toast from 'react-hot-toast';
import useAuthStore from '../../store/authStore';

const STATUS_COLORS = { 'active':'bg-green-100 text-green-700', 'on-leave':'bg-yellow-100 text-yellow-700', 'terminated':'bg-red-100 text-red-700', 'resigned':'bg-gray-100 text-gray-700' };
const EMPTY = { first_name:'', last_name:'', email:'', phone:'', department_id:'', salary:'', position:'', employment_type:'full-time', status:'active', hire_date:'' };

export default function Employees() {
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [selected, setSelected] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(EMPTY);
  const [saving, setSaving] = useState(false);
  const { user } = useAuthStore();
  const navigate = useNavigate();

  useEffect(() => { fetchEmployees(); fetchDepts(); }, []);
  useEffect(() => { fetchEmployees(); }, [search, statusFilter]);

  const fetchEmployees = async () => {
    try {
      const res = await axios.get('/api/employees', { params: { search, status: statusFilter, per_page: 100 } });
      setEmployees(res.data.data || res.data);
    } catch { toast.error('Failed to fetch employees'); }
    finally { setLoading(false); }
  };

  const fetchDepts = async () => {
    try { const r = await axios.get('/api/departments'); setDepartments(r.data.data || []); } catch {}
  };

  const openNew = () => { setForm(EMPTY); setSelected(null); setShowForm(true); };
  const openEdit = (emp) => {
    setForm({ first_name: emp.first_name||'', last_name: emp.last_name||'', email: emp.email||'', phone: emp.phone||'', department_id: emp.department_id||'', salary: emp.salary||'', position: emp.position||'', employment_type: emp.employment_type||'full-time', status: emp.status||'active', hire_date: emp.hire_date||'' });
    setSelected(emp); setShowForm(true);
  };

  const save = async (e) => {
    e.preventDefault(); setSaving(true);
    try {
      if (selected) { await axios.put(`/api/employees/${selected.id}`, form); toast.success('Employee updated'); }
      else { await axios.post('/api/employees', form); toast.success('Employee added'); }
      setShowForm(false); fetchEmployees();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const changeStatus = async (emp, status, e) => {
    e.stopPropagation();
    try { await axios.put(`/api/employees/${emp.id}`, { ...emp, status }); toast.success(`Status → ${status}`); fetchEmployees(); }
    catch { toast.error('Failed to update status'); }
  };

  const del = async (id, e) => {
    e.stopPropagation();
    if (!confirm('Delete this employee?')) return;
    try { await axios.delete(`/api/employees/${id}`); toast.success('Deleted'); fetchEmployees(); }
    catch { toast.error('Failed'); }
  };

  if (loading) return <div className="flex items-center justify-center h-96"><div className="animate-spin rounded-full h-12 w-12 border-4 border-primary-600 border-t-transparent"/></div>;

  return (
    <div className="space-y-6 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Employees</h1>
          <p className="text-gray-600 mt-1">Click any row to view details • Use employee profile to change status</p>
        </div>
        <button onClick={openNew} className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-xl text-sm font-semibold shadow-sm">
          <Plus size={18} weight="bold"/> Add Employee
        </button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 flex flex-col sm:flex-row gap-3">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"/>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search employees..." className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500"/>
        </div>
        <select value={statusFilter} onChange={e=>setStatusFilter(e.target.value)} className="px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-primary-500 min-w-[160px]">
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="on-leave">On Leave</option>
          <option value="terminated">Terminated</option>
          <option value="resigned">Resigned</option>
        </select>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-100">
            <tr>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Employee</th>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Position</th>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Department</th>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Type</th>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Status</th>
              <th className="text-left py-3 px-4 font-semibold text-gray-600">Hired</th>
              <th className="text-right py-3 px-4 font-semibold text-gray-600">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-50">
            {employees.map(emp => (
              <tr key={emp.id} className="hover:bg-primary-50/30 cursor-pointer transition-colors" onClick={()=>navigate(`/employees/${emp.id}`)}>
                <td className="py-3 px-4">
                  <div className="flex items-center gap-3">
                    <div className="w-9 h-9 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{background:'linear-gradient(135deg,#5D4037,#6D4C41)'}}>
                      {emp.first_name?.[0]}{emp.last_name?.[0]}
                    </div>
                    <div>
                      <p className="font-semibold text-gray-900">{emp.full_name||`${emp.first_name} ${emp.last_name}`}</p>
                      <p className="text-xs text-gray-500">{emp.email}</p>
                    </div>
                  </div>
                </td>
                <td className="py-3 px-4 text-gray-700">{emp.position||'—'}</td>
                <td className="py-3 px-4 text-gray-700">{emp.department?.name||'—'}</td>
                <td className="py-3 px-4 capitalize text-gray-600 text-xs">{(emp.employment_type||'').replace('_',' ')}</td>
                <td className="py-3 px-4">
                  <span className={`text-xs font-semibold px-2 py-1 rounded-full capitalize ${STATUS_COLORS[emp.status]||'bg-gray-100 text-gray-600'}`}>
                    {(emp.status||'active').replace('-',' ')}
                  </span>
                </td>
                <td className="py-3 px-4 text-gray-500 text-xs">{emp.hire_date?new Date(emp.hire_date).toLocaleDateString():'—'}</td>
                <td className="py-3 px-4 text-right" onClick={e=>e.stopPropagation()}>
                  <button onClick={e=>{e.stopPropagation();navigate(`/employees/${emp.id}`);}} className="text-primary-600 hover:text-primary-800 mr-2 p-1 rounded hover:bg-primary-50 text-xs font-medium px-2 py-1">Open</button>
                  <button onClick={e=>{e.stopPropagation();openEdit(emp);}} className="text-gray-500 hover:text-gray-800 mr-1 p-1 rounded hover:bg-gray-50"><Pencil size={14}/></button>
                  <button onClick={e=>del(emp.id,e)} className="text-red-500 hover:text-red-700 p-1 rounded hover:bg-red-50"><Trash size={14}/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {employees.length===0&&<div className="text-center py-14"><Users size={48} className="mx-auto text-gray-300 mb-3"/><p className="text-gray-500">{search?'No employees match your search':'No employees yet — add one!'}</p></div>}
      </div>

      {showForm&&(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setShowForm(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b sticky top-0 bg-white z-10">
              <h2 className="text-lg font-bold text-gray-900">{selected?`Edit: ${selected.first_name} ${selected.last_name}`:'Add New Employee'}</h2>
              <button onClick={()=>setShowForm(false)} className="p-1.5 hover:bg-gray-100 rounded-lg"><X size={20}/></button>
            </div>
            <form onSubmit={save} className="p-5">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">First Name *</label><input required className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.first_name} onChange={e=>setForm({...form,first_name:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Last Name *</label><input required className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.last_name} onChange={e=>setForm({...form,last_name:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Email *</label><input type="email" required className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.email} onChange={e=>setForm({...form,email:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Phone</label><input className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.phone} onChange={e=>setForm({...form,phone:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Position *</label><input required className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.position} onChange={e=>setForm({...form,position:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Department</label>
                  <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-primary-500" value={form.department_id} onChange={e=>setForm({...form,department_id:e.target.value})}>
                    <option value="">None</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 mb-1">Salary (₦)</label><input type="number" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.salary} onChange={e=>setForm({...form,salary:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Hire Date</label><input type="date" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.hire_date} onChange={e=>setForm({...form,hire_date:e.target.value})}/></div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Employment Type</label>
                  <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-primary-500" value={form.employment_type} onChange={e=>setForm({...form,employment_type:e.target.value})}>
                    <option value="full-time">Full Time</option><option value="part-time">Part Time</option><option value="contract">Contract</option><option value="intern">Intern</option>
                  </select>
                </div>
                <div><label className="block text-xs font-semibold text-gray-600 mb-1">Status</label>
                  <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white outline-none focus:ring-2 focus:ring-primary-500" value={form.status} onChange={e=>setForm({...form,status:e.target.value})}>
                    <option value="active">Active</option><option value="on-leave">On Leave</option><option value="terminated">Terminated</option><option value="resigned">Resigned</option>
                  </select>
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-3 border-t">
                <button type="button" onClick={()=>setShowForm(false)} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-lg text-sm font-medium">Cancel</button>
                <button type="submit" disabled={saving} className="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg text-sm font-semibold disabled:opacity-60">{saving?'Saving…':selected?'Update Employee':'Add Employee'}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
