import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Users, Plus, X, ShieldCheck, Pencil, Trash } from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

export default function CompanyUsers() {
  const [searchParams] = useSearchParams();
  const companyId = searchParams.get('company_id');
  const action = searchParams.get('action');

  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState({ name:'', email:'', password:'', role:'Company User', status:'active' });

  useEffect(() => { fetchData(); }, []);
  useEffect(() => { if (action === 'create') openModal(); }, [action]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const params = companyId ? { params: { company_id: companyId } } : {};
      const [uRes, rRes] = await Promise.all([
        axios.get('/api/users', params),
        axios.get('/api/roles')
      ]);
      setUsers(uRes.data.data || []);
      setRoles(rRes.data.data || []);
    } catch (e) {
      toast.error('Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const openModal = (u=null) => {
    if (u) {
      setForm({ name: u.name, email: u.email, password: '', role: u.roles?.[0]?.name || 'Company User', status: u.status || 'active' });
      setEditing(u);
    } else {
      setForm({ name:'', email:'', password:'', role:'Company User', status:'active' });
      setEditing(null);
    }
    setShowModal(true);
  };

  const submit = async (e) => {
    e.preventDefault();
    try {
      const payload = { ...form, roles: [form.role] };
      if (companyId && !editing) payload.company_id = companyId;
      if (editing) {
        await axios.put(`/api/users/${editing.id}`, payload);
        toast.success('User updated');
      } else {
        await axios.post('/api/users', payload);
        toast.success('User created');
      }
      setShowModal(false);
      fetchData();
    } catch (e) {
      toast.error(e.response?.data?.message || 'Failed');
    }
  };

  const del = async (id) => {
    if (!window.confirm('Delete this user?')) return;
    try { await axios.delete(`/api/users/${id}`); toast.success('Deleted'); fetchData(); }
    catch { toast.error('Delete failed'); }
  };

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

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2"><Users size={28} className="text-primary-600"/>Company Users & Roles</h1>
          <p className="text-gray-600 text-sm mt-1">Manage users and their access roles within your company</p>
        </div>
        <button onClick={()=>openModal()} className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg text-sm font-medium transition-colors"><Plus size={18}/>Add User</button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <table className="w-full text-sm"><thead className="bg-gray-50"><tr><th className="px-4 py-3 text-left font-semibold text-gray-700">Name</th><th className="px-4 py-3 text-left font-semibold text-gray-700">Email</th><th className="px-4 py-3 text-left font-semibold text-gray-700">Role</th><th className="px-4 py-3 text-left font-semibold text-gray-700">Status</th><th className="px-4 py-3 text-right font-semibold text-gray-700">Actions</th></tr></thead>
        <tbody className="divide-y divide-gray-100">
          {users.length===0 && <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">No users found.</td></tr>}
          {users.map(u=><tr key={u.id} className="hover:bg-gray-50">
            <td className="px-4 py-3 font-medium text-gray-900">{u.name}</td>
            <td className="px-4 py-3 text-gray-600">{u.email}</td>
            <td className="px-4 py-3"><span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-700"><ShieldCheck size={12}/>{u.roles?.map(r=>r.name).join(', ')||'None'}</span></td>
            <td className="px-4 py-3"><span className={`px-2 py-1 rounded-full text-xs font-medium ${u.status==='active'?'bg-green-100 text-green-700':'bg-gray-100 text-gray-600'}`}>{u.status}</span></td>
            <td className="px-4 py-3 text-right">
              <button onClick={()=>openModal(u)} className="text-primary-600 hover:text-primary-800 mr-2"><Pencil size={16}/></button>
              <button onClick={()=>del(u.id)} className="text-red-500 hover:text-red-700"><Trash size={16}/></button>
            </td>
          </tr>)}
        </tbody>
      </table>
      </div>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setShowModal(false)}>
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-4 border-b"><h3 className="font-bold text-gray-900">{editing?'Edit':'Add'} User</h3><button onClick={()=>setShowModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <form onSubmit={submit} className="p-4">
              <div className="mb-3"><label className="block text-sm font-medium text-gray-700 mb-1">Name</label><input required className="w-full px-3 py-2 border rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.name} onChange={e=>setForm({...form,name:e.target.value})}/></div>
              <div className="mb-3"><label className="block text-sm font-medium text-gray-700 mb-1">Email</label><input type="email" required className="w-full px-3 py-2 border 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>
              {!editing && <div className="mb-3"><label className="block text-sm font-medium text-gray-700 mb-1">Password</label><input type="password" required={!editing} className="w-full px-3 py-2 border rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500" value={form.password} onChange={e=>setForm({...form,password:e.target.value})}/></div>}
              <div className="mb-3"><label className="block text-sm font-medium text-gray-700 mb-1">Role</label><select className="w-full px-3 py-2 border rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500 bg-white" value={form.role} onChange={e=>setForm({...form,role:e.target.value})}>{roles.map(r=><option key={r.id} value={r.name}>{r.name}</option>)}</select></div>
              <div className="mb-3"><label className="block text-sm font-medium text-gray-700 mb-1">Status</label><select className="w-full px-3 py-2 border rounded-lg text-sm outline-none focus:ring-2 focus:ring-primary-500 bg-white" value={form.status} onChange={e=>setForm({...form,status:e.target.value})}><option value="active">Active</option><option value="inactive">Inactive</option></select></div>
              <div className="flex justify-end gap-2"><button type="button" onClick={()=>setShowModal(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" className="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg text-sm font-medium">{editing?'Update':'Add'} User</button></div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
