import { useState, useEffect, useCallback } from 'react';
import api from '../services/api';
import toast from 'react-hot-toast';
import StatusBadge from '../components/StatusBadge';
import { CardSkeleton } from '../components/LoadingSkeleton';
import EmptyState from '../components/EmptyState';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import { AlertTriangle, Users } from 'lucide-react';

const initialForm = { name: '', email: '', password: '', phone: '', job_title: '', department: '', department_id: '', role_id: '' };
const systemRoleOrder = ['admin', 'project_manager', 'product_manager', 'scrum_master', 'specialist', 'observer', 'ceo'];
const getUserRole = (user) => user.role || user.roles?.[0] || null;

export default function Team() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState({ department: '', role: '', status: '' });
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [form, setForm] = useState(initialForm);
  const [saving, setSaving] = useState(false);
  const [roles, setRoles] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [jobTitles, setJobTitles] = useState([]);
  const [selectedUser, setSelectedUser] = useState(null);
  const [userDetail, setUserDetail] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [confirmToggle, setConfirmToggle] = useState(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const { data } = await api.get('/users', { params: { per_page: 200 } });
      setUsers(data.data || []);
    } catch (err) {
      setError('خطا در بارگذاری کاربران');
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchRoles = useCallback(async () => {
    try {
      const { data } = await api.get('/roles', { params: { per_page: 100, sort_by: 'id', sort_dir: 'asc' } });
      const uniqueRoles = (data.data || [])
        .filter((role) => role.name !== 'team_member')
        .sort((a, b) => systemRoleOrder.indexOf(a.name) - systemRoleOrder.indexOf(b.name));
      setRoles(uniqueRoles);
    } catch {}
  }, []);

  const fetchDepartments = useCallback(async () => {
    try {
      const { data } = await api.get('/departments');
      setDepartments(Array.isArray(data.flat) ? data.flat : Object.values(data.flat || {}));
    } catch {}
  }, []);

  const fetchJobTitles = useCallback(async () => {
    try {
      const { data } = await api.get('/settings', { params: { group: 'people' } });
      const setting = (data.data || []).find((item) => item.key === 'job_titles');
      const titles = Array.isArray(setting?.value) ? setting.value.map((title) => String(title || '').trim()).filter(Boolean) : [];
      setJobTitles(Array.from(new Set(titles)));
    } catch {}
  }, []);

  useEffect(() => { fetchUsers(); fetchRoles(); fetchDepartments(); fetchJobTitles(); }, [fetchUsers, fetchRoles, fetchDepartments, fetchJobTitles]);

  const handleToggleStatus = async (user) => {
    try {
      const newStatus = user.status === 'active' ? 'inactive' : 'active';
      await api.put(`/users/${user.id}/status`, { status: newStatus });
      toast.success('وضعیت کاربر با موفقیت تغییر کرد');
      setConfirmToggle(null);
      fetchUsers();
    } catch {
      toast.error('خطا در تغییر وضعیت کاربر');
    }
  };

  const handleDelete = async (id) => {
    try {
      await api.delete(`/users/${id}`);
      toast.success('کاربر با موفقیت حذف شد');
      setConfirmDelete(null);
      fetchUsers();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در حذف کاربر');
    }
  };

  const openCreate = () => {
    setEditingUser(null);
    setForm(initialForm);
    setShowModal(true);
  };

  const openEdit = (user, e) => {
    if (e) e.stopPropagation();
    setEditingUser(user);
    setForm({
      name: user.name || '',
      email: user.email || '',
      password: '',
      phone: user.phone || '',
      job_title: user.job_title || '',
      department: user.department || '',
      department_id: user.department_id?.toString() || '',
      role_id: user.role_id || getUserRole(user)?.id || '',
    });
    setShowModal(true);
  };

  const handleSave = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim()) {
      toast.error('نام و ایمیل الزامی هستند');
      return;
    }
    setSaving(true);
    try {
      if (editingUser) {
        const payload = { ...form };
        if (!payload.password) delete payload.password;
        await api.put(`/users/${editingUser.id}`, payload);
        toast.success('کاربر با موفقیت ویرایش شد');
      } else {
        if (!form.password) { toast.error('رمز عبور الزامی است'); setSaving(false); return; }
        await api.post('/users', form);
        toast.success('کاربر با موفقیت ایجاد شد');
      }
      setShowModal(false);
      fetchUsers();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در ذخیره کاربر');
    } finally {
      setSaving(false);
    }
  };

  const viewDetail = async (user) => {
    setSelectedUser(user);
    try {
      const { data } = await api.get(`/users/${user.id}/tasks`);
      setUserDetail(data.data || {});
    } catch {
      setUserDetail({});
    }
  };

  const filteredUsers = users.filter((u) => {
    const q = search.trim().toLowerCase();
    if (q && !u.name?.toLowerCase().includes(q) && !u.email?.toLowerCase().includes(q)) return false;
    if (filters.department && u.department !== filters.department) return false;
    if (filters.role && (u.role_id?.toString() !== filters.role && getUserRole(u)?.id?.toString() !== filters.role)) return false;
    if (filters.status && u.status !== filters.status) return false;
    return true;
  });

  if (loading) return <div className="page-container"><div className="grid grid-3">{Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}</div></div>;
  if (error) return <div className="page-container"><EmptyState icon={AlertTriangle} title={error} description="لطفا دوباره تلاش کنید" action={<button className="btn btn-primary" onClick={fetchUsers}>تلاش مجدد</button>} /></div>;

  return (
    <div className="page-container">
      <div className="page-header">
        <button className="btn btn-primary" onClick={openCreate}>+ عضو جدید</button>
      </div>

      <div className="filter-bar">
        <input className="form-input" placeholder="جستجوی نام یا ایمیل..." value={search} onChange={(e) => setSearch(e.target.value)} />
        <select className="form-select" value={filters.department} onChange={(e) => setFilters({ ...filters, department: e.target.value })}>
          <option value="">تمام دپارتمان‌ها</option>
          {departments.map((d) => <option key={d.id} value={d.name}>{d.name}</option>)}
        </select>
        <select className="form-select" value={filters.role} onChange={(e) => setFilters({ ...filters, role: e.target.value })}>
          <option value="">تمام نقش‌ها</option>
          {roles.map((r) => <option key={r.id} value={r.id.toString()}>{r.display_name || r.name}</option>)}
        </select>
        <select className="form-select" value={filters.status} onChange={(e) => setFilters({ ...filters, status: e.target.value })}>
          <option value="">تمام وضعیت‌ها</option>
          <option value="active">فعال</option>
          <option value="inactive">غیرفعال</option>
        </select>
      </div>

      {filteredUsers.length === 0 ? (
        <EmptyState icon={Users} title="کاربری یافت نشد" description="هیچ کاربری با فیلترهای انتخاب شده وجود ندارد" />
      ) : (
        <div className="grid grid-3">
          {filteredUsers.map((user) => (
            <div key={user.id} className="card" style={{ cursor: 'pointer', padding: '1.25rem' }} onClick={() => viewDetail(user)}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '0.75rem' }}>
                <div className="avatar avatar-lg">{user.name?.[0] || '?'}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: '0.9375rem', color: 'var(--gray-900)' }}>{user.name}</div>
                  <div style={{ fontSize: '0.8125rem', color: 'var(--gray-500)', marginTop: 2 }}>{user.email}</div>
                </div>
                <StatusBadge status={user.status || 'active'} />
              </div>
              <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', fontSize: '0.8125rem', color: 'var(--gray-600)' }}>
                {user.job_title && <span>{user.job_title}</span>}
                {user.department && <><span>|</span><span>{user.department}</span></>}
                {getUserRole(user) && <><span>|</span><span style={{ color: 'var(--primary)' }}>{getUserRole(user).display_name || getUserRole(user).name}</span></>}
              </div>
              <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem', paddingTop: '0.75rem', borderTop: '1px solid var(--gray-100)' }}>
                <button className="btn btn-sm btn-outline" onClick={(e) => openEdit(user, e)}>ویرایش</button>
                <button className="btn btn-sm btn-outline" onClick={(e) => { e.stopPropagation(); setConfirmToggle(user); }}>
                  {user.status === 'active' ? 'غیرفعال‌سازی' : 'فعال‌سازی'}
                </button>
                <button className="btn btn-sm btn-danger" onClick={(e) => { e.stopPropagation(); setConfirmDelete(user); }}>حذف</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <Modal title={editingUser ? 'ویرایش کاربر' : 'کاربر جدید'} onClose={() => setShowModal(false)} footer={
          <>
            <button className="btn btn-secondary" onClick={() => setShowModal(false)}>انصراف</button>
            <button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره'}</button>
          </>
        }>
          <form onSubmit={handleSave} className="compact-modal-form">
            <div className="compact-modal-grid">
            <div className="form-group">
              <label className="form-label">نام</label>
              <input className="form-input" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
            </div>
            <div className="form-group">
              <label className="form-label">ایمیل</label>
              <input className="form-input" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
            </div>
            <div className="form-group">
              <label className="form-label">{editingUser ? 'رمز عبور (خالی برای عدم تغییر)' : 'رمز عبور'}</label>
              <input className="form-input" type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} required={!editingUser} />
            </div>
            <div className="form-group">
              <label className="form-label">شماره تماس</label>
              <input className="form-input" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            </div>
            <div className="form-group">
              <label className="form-label">سمت</label>
              <select className="form-select" value={form.job_title} onChange={(e) => setForm({ ...form, job_title: e.target.value })}>
                <option value="">انتخاب سمت</option>
                {jobTitles.map((title, index) => <option key={`${title}-${index}`} value={title}>{title}</option>)}
                {form.job_title && !jobTitles.includes(form.job_title) && <option key="current-job-title" value={form.job_title}>{form.job_title}</option>}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">دپارتمان</label>
              <select className="form-select" value={form.department_id} onChange={(e) => {
                const deptId = e.target.value;
                const dept = departments.find(d => d.id === parseInt(deptId));
                setForm({ ...form, department_id: deptId, department: dept?.name || '' });
              }}>
                <option value="">انتخاب دپارتمان</option>
                {departments.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">نقش</label>
              <select className="form-select" value={form.role_id} onChange={(e) => setForm({ ...form, role_id: e.target.value })}>
                <option value="">انتخاب نقش</option>
                {roles.map((r) => <option key={r.id} value={r.id}>{r.display_name || r.name}</option>)}
              </select>
            </div>
            </div>
          </form>
        </Modal>
      )}

      {confirmDelete && (
        <ConfirmDialog title="حذف کاربر" message={`آیا از حذف کاربر "${confirmDelete.name}" اطمینان دارید؟`} danger
          onConfirm={() => handleDelete(confirmDelete.id)} onCancel={() => setConfirmDelete(null)} confirmText="حذف" />
      )}

      {confirmToggle && (
        <ConfirmDialog title="تغییر وضعیت" message={`آیا می‌خواهید وضعیت کاربر "${confirmToggle.name}" به ${confirmToggle.status === 'active' ? 'غیرفعال' : 'فعال'} تغییر یابد؟`}
          onConfirm={() => handleToggleStatus(confirmToggle)} onCancel={() => setConfirmToggle(null)} confirmText="تغییر وضعیت" />
      )}

      {selectedUser && (
        <>
          <div className="drawer-overlay" onClick={() => { setSelectedUser(null); setUserDetail(null); }} />
          <div className="drawer">
            <div className="drawer-header">
              <span className="drawer-title">جزئیات کاربر</span>
              <button className="modal-close" onClick={() => { setSelectedUser(null); setUserDetail(null); }}>&times;</button>
            </div>
            <div className="drawer-body">
              <div style={{ textAlign: 'center', marginBottom: '1.5rem' }}>
                <div className="avatar avatar-xl" style={{ margin: '0 auto 0.75rem' }}>{selectedUser.name?.[0] || '?'}</div>
                <div style={{ fontWeight: 600, fontSize: '1.125rem' }}>{selectedUser.name}</div>
                <div style={{ color: 'var(--gray-500)', fontSize: '0.875rem' }}>{selectedUser.email}</div>
              </div>
              <div className="card" style={{ padding: '1rem', marginBottom: '1rem' }}>
                <div style={{ display: 'grid', gap: '0.5rem', fontSize: '0.875rem' }}>
                  {selectedUser.job_title && <div><strong>سمت:</strong> {selectedUser.job_title}</div>}
                  {selectedUser.department && <div><strong>دپارتمان:</strong> {selectedUser.department}</div>}
                  {selectedUser.phone && <div><strong>شماره تماس:</strong> {selectedUser.phone}</div>}
                  {getUserRole(selectedUser) && <div><strong>نقش:</strong> {getUserRole(selectedUser).display_name || getUserRole(selectedUser).name}</div>}
                  <div><strong>وضعیت:</strong> <StatusBadge status={selectedUser.status || 'active'} /></div>
                </div>
              </div>
              {userDetail ? (
                <div className="card" style={{ padding: '1rem' }}>
                  <h4 style={{ fontSize: '0.9375rem', fontWeight: 600, marginBottom: '0.75rem' }}>آمار تسک‌ها</h4>
                  <div style={{ display: 'grid', gap: '0.75rem' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0', borderBottom: '1px solid var(--gray-100)' }}>
                      <span>تسک‌های محول شده</span>
                      <span style={{ fontWeight: 600 }}>{userDetail.assigned_tasks_count ?? userDetail.total ?? '—'}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0', borderBottom: '1px solid var(--gray-100)' }}>
                      <span>تسک‌های عقب‌افتاده</span>
                      <span style={{ fontWeight: 600, color: 'var(--danger)' }}>{userDetail.delayed_tasks_count ?? userDetail.delayed ?? '—'}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0' }}>
                      <span>تسک‌های در حال انجام</span>
                      <span style={{ fontWeight: 600, color: 'var(--primary)' }}>{userDetail.in_progress_count ?? userDetail.inProgress ?? '—'}</span>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="skeleton" style={{ height: 120, borderRadius: 'var(--radius)' }} />
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
