import { useEffect, useMemo, useState } from 'react';
import api from '../services/api';
import toast from 'react-hot-toast';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import EmptyState from '../components/EmptyState';
import StatusBadge from '../components/StatusBadge';
import FormSelect from '../components/FormSelect';
import {
  AlertTriangle,
  BarChart3,
  Building2,
  CheckCircle2,
  ChevronDown,
  ChevronLeft,
  ClipboardList,
  Edit3,
  Folder,
  GitBranch,
  History,
  LayoutGrid,
  ListTree,
  MoreVertical,
  Plus,
  Search,
  Settings,
  ShieldCheck,
  Table2,
  TimerReset,
  Trash2,
  UserCog,
  UserPlus,
  Users,
} from 'lucide-react';
import { sortUsersByRolePriority } from '../utils/rolePriority';

const emptySectionForm = {
  name: '',
  type: 'department',
  parent_id: '',
  manager_id: '',
  description: '',
  is_active: true,
  sort_order: 0,
};
const emptyMemberForm = { user_id: '', role_in_team: '', is_primary: true, target_department_id: '' };

const typeLabels = {
  organization: 'سازمان',
  department: 'دپارتمان',
  unit: 'واحد',
  team: 'تیم',
  person: 'فرد',
};
const typeIcons = { organization: Building2, department: Folder, unit: GitBranch, team: Users };
const activeProjectStatuses = ['planning', 'active', 'in_progress'];
const openTaskStatuses = ['waiting', 'todo', 'in_progress', 'review'];
const tabs = ['اعضا', 'زیرمجموعه‌ها', 'پروژه‌ها', 'تسک‌ها', 'Sprintها', 'گزارش عملکرد', 'تنظیمات', 'تاریخچه تغییرات'];

const getRoleName = (user) => user.role?.display_name || user.roles?.[0]?.display_name || user.role?.name || user.roles?.[0]?.name || '—';
const asDate = (value) => value ? new Date(value).toLocaleDateString('fa-IR') : '—';
const asDateTime = (value) => value ? new Date(value).toLocaleString('fa-IR') : '—';

const asArray = (value) => Array.isArray(value) ? value : Object.values(value || {});

const flattenTree = (nodes, depth = 0, parentName = '') => asArray(nodes).flatMap((node) => [
  { ...node, depth, parentName },
  ...flattenTree(node.children || [], depth + 1, node.name),
]);

export default function Organization() {
  const [tree, setTree] = useState([]);
  const [flat, setFlat] = useState([]);
  const [users, setUsers] = useState([]);
  const [projects, setProjects] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [sprints, setSprints] = useState([]);
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedId, setSelectedId] = useState(null);
  const [expanded, setExpanded] = useState({});
  const [view, setView] = useState('tree');
  const [activeTab, setActiveTab] = useState('اعضا');
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState('all');
  const [actionMenu, setActionMenu] = useState(null);

  const [sectionModal, setSectionModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [sectionForm, setSectionForm] = useState(emptySectionForm);
  const [advancedOpen, setAdvancedOpen] = useState(false);
  const [memberModal, setMemberModal] = useState(null);
  const [memberForm, setMemberForm] = useState(emptyMemberForm);
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [saving, setSaving] = useState(false);
  const [highlightTarget, setHighlightTarget] = useState(null);
  const [seenAlerts, setSeenAlerts] = useState(new Set());

  const fetchAll = async () => {
    setLoading(true);
    try {
      const [departmentsRes, usersRes, projectsRes, tasksRes, sprintsRes] = await Promise.allSettled([
        api.get('/departments'),
        api.get('/users', { params: { per_page: 300 } }),
        api.get('/projects', { params: { per_page: 300 } }),
        api.get('/tasks', { params: { per_page: 300 } }),
        api.get('/sprints', { params: { per_page: 300 } }),
      ]);

      if (departmentsRes.status !== 'fulfilled') {
        throw departmentsRes.reason;
      }

      const nextTree = asArray(departmentsRes.value.data.data);
      const nextFlat = flattenTree(nextTree);
      setTree(nextTree);
      setFlat(nextFlat);
      setUsers(usersRes.status === 'fulfilled' ? asArray(usersRes.value.data.data) : []);
      setProjects(projectsRes.status === 'fulfilled' ? asArray(projectsRes.value.data.data) : []);
      setTasks(tasksRes.status === 'fulfilled' ? asArray(tasksRes.value.data.data) : []);
      setSprints(sprintsRes.status === 'fulfilled' ? asArray(sprintsRes.value.data.data) : []);
      setSelectedId((current) => current || nextFlat[0]?.id || null);
      setExpanded(Object.fromEntries(nextFlat.map((node) => [node.id, true])));
    } catch {
      toast.error('خطا در دریافت ساختار سازمانی');
    } finally {
      setLoading(false);
    }
  };

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

  const selected = flat.find((item) => item.id === selectedId) || flat[0] || null;
  const descendants = useMemo(() => {
    if (!selected) return [];
    const collect = (node) => (node.children || []).flatMap((child) => [child, ...collect(child)]);
    return collect(selected);
  }, [selected]);
  const scopeIds = selected ? [selected.id, ...descendants.map((item) => item.id)] : [];
  const selectedMembers = sortUsersByRolePriority(users.filter((user) => (user.departments || []).some((dept) => scopeIds.includes(dept.id)) || scopeIds.includes(user.department_id)));
  const directMembers = sortUsersByRolePriority(users.filter((user) => (user.departments || []).some((dept) => dept.id === selected?.id) || user.department_id === selected?.id));
  const selectedMemberIds = new Set(selectedMembers.map((user) => user.id));
  const selectedProjects = projects.filter((project) => {
    const memberIds = (project.members || []).map((member) => member.id);
    return scopeIds.includes(project.department_id) || selectedMemberIds.has(project.project_manager_id) || memberIds.some((id) => selectedMemberIds.has(id));
  });
  const selectedTasks = tasks.filter((task) => selectedMemberIds.has(task.assignee_id));
  const selectedSprints = sprints.filter((sprint) => selectedProjects.some((project) => project.id === sprint.project_id) || (sprint.members || []).some((member) => selectedMemberIds.has(member.id)));
  const selectedActiveProjects = selectedProjects.filter((project) => activeProjectStatuses.includes(project.status));

  useEffect(() => {
    if (!selected?.id) return;
    api.get('/activity-logs', { params: { subject_type: 'department', subject_id: selected.id, per_page: 30 } })
      .then(({ data }) => setLogs(data.data || []))
      .catch(() => setLogs([]));
  }, [selected?.id]);

  const metrics = useMemo(() => {
    const teams = flat.filter((item) => item.type === 'team');
    const departments = flat.filter((item) => !item.type || item.type === 'department');
    const membersWithoutTeam = users.filter((user) => !(user.departments || []).length && !user.department_id);
    const teamsWithoutManager = teams.filter((team) => !team.manager);
    const teamIds = teams.map((team) => team.id);
    const activeConnectedProjects = projects.filter((project) => activeProjectStatuses.includes(project.status) && teamIds.includes(project.department_id));
    return [
      { label: 'تعداد کل دپارتمان‌ها', value: departments.length || flat.filter((item) => item.type !== 'team' && item.type !== 'unit' && item.type !== 'organization').length, icon: Building2 },
      { label: 'تعداد کل تیم‌ها', value: teams.length, icon: Users },
      { label: 'تعداد کل اعضا', value: users.length, icon: UserCog },
      { label: 'تیم‌های بدون مدیر', value: teamsWithoutManager.length, icon: AlertTriangle },
      { label: 'اعضای بدون تیم', value: membersWithoutTeam.length, icon: UserPlus },
      { label: 'پروژه‌های فعال متصل به تیم‌ها', value: activeConnectedProjects.length, icon: ClipboardList },
    ];
  }, [flat, users, projects]);

  const warnings = useMemo(() => {
    const teams = flat.filter((item) => item.type === 'team');
    const withoutManager = teams.filter((team) => !team.manager);
    const withoutMembers = flat.filter((item) => item.type !== 'organization' && !item.users_count);
    const withoutProjects = teams.filter((team) => {
      const teamUserIds = users.filter((user) => (user.departments || []).some((dept) => dept.id === team.id) || user.department_id === team.id).map((user) => user.id);
      return !projects.some((project) => activeProjectStatuses.includes(project.status) && (project.department_id === team.id || (project.members || []).some((member) => teamUserIds.includes(member.id))));
    });
    const withoutTeam = users.filter((user) => !(user.departments || []).length && !user.department_id);
    const multiNoPrimary = users.filter((user) => (user.departments || []).length > 1 && !(user.departments || []).some((dept) => dept.is_primary));
    const withoutJobTitle = users.filter((user) => !user.job_title);
    return [
      withoutManager.length && { id: `manager-${withoutManager[0].id}`, text: `${withoutManager.length} تیم بدون مدیر هستند.`, action: 'تعیین مدیر', filter: 'without_manager', targetType: 'team', targetId: withoutManager[0].id, targetField: 'manager_id' },
      withoutTeam.length && { id: `user-team-${withoutTeam[0].id}`, text: `${withoutTeam.length} عضو هنوز به هیچ تیمی وصل نشده‌اند.`, action: 'مشاهده عضو', filter: 'members_without_team', targetType: 'user', targetId: withoutTeam[0].id, targetField: 'department_id' },
      withoutJobTitle.length && { id: `user-job-${withoutJobTitle[0].id}`, text: `${withoutJobTitle.length} کاربر عنوان شغلی ندارند.`, action: 'مشاهده کاربر', targetType: 'user', targetId: withoutJobTitle[0].id, targetField: 'job_title' },
      withoutProjects.length && { id: `project-${withoutProjects[0].id}`, text: `${withoutProjects.length} تیم هیچ پروژه فعالی ندارد.`, action: 'مشاهده تیم', filter: 'without_active_project', targetType: 'team', targetId: withoutProjects[0].id },
      withoutMembers.length && { id: `members-${withoutMembers[0].id}`, text: `${withoutMembers.length} بخش بدون عضو هستند.`, action: 'افزودن عضو', filter: 'without_members', targetType: 'department', targetId: withoutMembers[0].id, targetField: 'members' },
      multiNoPrimary.length && { id: `primary-${multiNoPrimary[0].id}`, text: `${multiNoPrimary.length} عضو چندتیمی تیم اصلی مشخص ندارند.`, action: 'مشاهده عضو', filter: 'multi_no_primary', targetType: 'user', targetId: multiNoPrimary[0].id },
    ].filter(Boolean);
  }, [flat, users, projects]);

  const expandAncestors = (nodeId) => {
    const ancestors = [];
    let current = flat.find((item) => item.id === nodeId);
    while (current?.parent_id) {
      ancestors.push(current.parent_id);
      current = flat.find((item) => item.id === current.parent_id);
    }
    setExpanded((prev) => ({ ...prev, ...Object.fromEntries(ancestors.map((id) => [id, true])), [nodeId]: true }));
  };

  const scrollAndHighlight = (elementId) => {
    window.setTimeout(() => {
      const element = document.getElementById(elementId);
      if (!element) {
        toast.error('مورد مرتبط با این هشدار دیگر پیدا نشد');
        return;
      }
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
      setHighlightTarget(elementId);
      window.setTimeout(() => setHighlightTarget(null), 2200);
    }, 120);
  };

  const handleAlertClick = (warning) => {
    setSeenAlerts((prev) => new Set([...prev, warning.id]));
    setFilter(warning.filter || 'all');
    setView('tree');
    setSearch('');

    if (warning.targetType === 'user') {
      const user = users.find((item) => item.id === warning.targetId);
      if (!user) return toast.error('کاربر مرتبط با این هشدار دیگر وجود ندارد');
      const departmentId = user.department_id || user.departments?.[0]?.id;
      if (!departmentId) return toast('این کاربر هنوز به هیچ بخشی متصل نیست');
      const node = flat.find((item) => item.id === departmentId);
      if (!node) return toast.error('بخش مرتبط با این کاربر پیدا نشد');
      expandAncestors(node.id);
      setSelectedId(node.id);
      setActiveTab('اعضا');
      scrollAndHighlight(`org-member-${user.id}`);
      return;
    }

    const node = flat.find((item) => item.id === warning.targetId);
    if (!node) return toast.error('بخش مرتبط با این هشدار دیگر وجود ندارد');
    expandAncestors(node.id);
    setSelectedId(node.id);
    if (warning.targetField === 'members') setActiveTab('اعضا');
    scrollAndHighlight(`org-node-${node.id}`);
    if (warning.targetField === 'manager_id') {
      window.setTimeout(() => {
        openEdit(node);
        window.setTimeout(() => document.querySelector('[data-field="manager_id"]')?.focus(), 120);
      }, 250);
    }
  };

  const visibleNodes = flat.filter((node) => {
    const q = search.trim().toLowerCase();
    const nodeUsers = users.filter((user) => (user.departments || []).some((dept) => dept.id === node.id) || user.department_id === node.id);
    const hasSearch = !q || node.name?.toLowerCase().includes(q) || node.description?.toLowerCase().includes(q) || nodeUsers.some((user) => user.name?.toLowerCase().includes(q) || user.email?.toLowerCase().includes(q));
    if (!hasSearch) return false;
    if (filter === 'without_manager') return !node.manager;
    if (filter === 'without_members') return !node.users_count;
    if (filter === 'inactive') return !node.is_active;
    if (filter === 'without_active_project') return node.type === 'team' && !projects.some((project) => activeProjectStatuses.includes(project.status) && project.department_id === node.id);
    if (filter === 'with_active_project') return projects.some((project) => activeProjectStatuses.includes(project.status) && project.department_id === node.id);
    return true;
  });

  const openCreate = (parentId = '') => {
    setEditing(null);
    setSectionForm({ ...emptySectionForm, parent_id: parentId || '' });
    setAdvancedOpen(false);
    setSectionModal(true);
    setActionMenu(null);
  };

  const openEdit = (item = selected) => {
    if (!item) return;
    setEditing(item);
    setSectionForm({
      name: item.name || '',
      type: item.type || 'department',
      parent_id: item.parent_id || '',
      manager_id: item.manager?.id || item.manager_id || '',
      description: item.description || '',
      is_active: item.is_active !== false,
      sort_order: item.sort_order || 0,
    });
    setAdvancedOpen(false);
    setSectionModal(true);
    setActionMenu(null);
  };

  const saveSection = async (e) => {
    e.preventDefault();
    if (!sectionForm.name.trim()) return toast.error('نام بخش الزامی است');
    setSaving(true);
    try {
      const payload = {
        ...sectionForm,
        parent_id: sectionForm.parent_id || null,
        manager_id: sectionForm.manager_id || null,
      };
      if (editing) {
        await api.put(`/departments/${editing.id}`, payload);
        toast.success('بخش به‌روزرسانی شد');
      } else {
        await api.post('/departments', payload);
        toast.success('بخش ایجاد شد');
      }
      setSectionModal(false);
      fetchAll();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در ذخیره بخش');
    } finally {
      setSaving(false);
    }
  };

  const openMemberModal = (mode, member = null) => {
    setMemberModal({ mode, member });
    const membership = member?.departments?.find((dept) => dept.id === selected?.id);
    setMemberForm({
      user_id: member?.id || '',
      role_in_team: membership?.role_in_team || member?.job_title || '',
      is_primary: membership?.is_primary ?? true,
      target_department_id: '',
    });
    setActionMenu(null);
  };

  const saveMember = async (e) => {
    e.preventDefault();
    if (!selected) return;
    if (memberModal.mode === 'transfer' && !memberForm.target_department_id) return toast.error('تیم مقصد را انتخاب کنید');
    if (!memberForm.user_id) return toast.error('عضو را انتخاب کنید');
    setSaving(true);
    try {
      if (memberModal.mode === 'transfer') {
        await api.post(`/departments/${selected.id}/members/${memberForm.user_id}/transfer`, memberForm);
        toast.success('عضو منتقل شد');
      } else if (memberModal.mode === 'edit') {
        await api.put(`/departments/${selected.id}/members/${memberForm.user_id}`, memberForm);
        toast.success('عضویت به‌روزرسانی شد');
      } else {
        await api.post(`/departments/${selected.id}/members`, memberForm);
        toast.success('عضو اضافه شد');
      }
      setMemberModal(null);
      fetchAll();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در ذخیره عضویت');
    } finally {
      setSaving(false);
    }
  };

  const removeMember = async (member) => {
    if (!selected) return;
    try {
      await api.delete(`/departments/${selected.id}/members/${member.id}`);
      toast.success('عضو از تیم حذف شد');
      fetchAll();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در حذف عضو');
    }
  };

  const toggleActive = async (item) => {
    try {
      await api.put(`/departments/${item.id}`, { is_active: !item.is_active });
      toast.success(item.is_active ? 'بخش غیرفعال شد' : 'بخش فعال شد');
      fetchAll();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در تغییر وضعیت');
    }
  };

  const deleteSection = async () => {
    try {
      await api.delete(`/departments/${confirmDelete.id}`);
      toast.success('بخش حذف شد');
      setConfirmDelete(null);
      setSelectedId(null);
      fetchAll();
    } catch (err) {
      toast.error(err.response?.data?.message || 'حذف مستقیم ممکن نیست؛ اعضا یا زیرمجموعه‌ها را منتقل کنید یا بخش را غیرفعال کنید.');
    }
  };

  const renderActionMenu = (item) => actionMenu === item.id && (
    <div className="org-action-menu">
      <button onClick={() => openEdit(item)}><Edit3 size={14} /> ویرایش</button>
      <button onClick={() => openCreate(item.id)}><Plus size={14} /> افزودن زیرمجموعه</button>
      <button onClick={() => { setSelectedId(item.id); openMemberModal('add'); }}><UserPlus size={14} /> افزودن عضو</button>
      <button onClick={() => openEdit(item)}><UserCog size={14} /> تغییر مدیر</button>
      <button onClick={() => openEdit(item)}><GitBranch size={14} /> انتقال به بخش دیگر</button>
      <button onClick={() => toggleActive(item)}><ShieldCheck size={14} /> {item.is_active ? 'غیرفعال کردن' : 'فعال کردن'}</button>
      <button className="danger" onClick={() => { setConfirmDelete(item); setActionMenu(null); }}><Trash2 size={14} /> حذف</button>
    </div>
  );

  const renderNode = (node, depth = 0) => {
    const hasChildren = (node.children || []).length > 0;
    const Icon = typeIcons[node.type] || Folder;
    const isSelected = selected?.id === node.id;
    return (
      <div key={node.id}>
        <div id={`org-node-${node.id}`} className={`org-tree-node ${isSelected ? 'active' : ''} ${highlightTarget === `org-node-${node.id}` ? 'org-highlight' : ''}`} style={{ marginRight: depth * 18 }} onClick={() => setSelectedId(node.id)}>
          <button className="org-icon-btn" onClick={(e) => { e.stopPropagation(); setExpanded((prev) => ({ ...prev, [node.id]: !prev[node.id] })); }}>
            {hasChildren ? (expanded[node.id] ? <ChevronDown size={16} /> : <ChevronLeft size={16} />) : <span />}
          </button>
          <span className="org-node-icon"><Icon size={16} /></span>
          <div className="org-node-title">
            <strong>{node.name}</strong>
            <span>{typeLabels[node.type] || 'دپارتمان'} · {node.users_count || 0} عضو</span>
          </div>
          {!node.manager && node.type === 'team' && <span className="badge badge-warning">بدون مدیر</span>}
          {!node.is_active && <span className="badge badge-gray">غیرفعال</span>}
          <div className="org-menu-wrap">
            <button className="org-icon-btn" onClick={(e) => { e.stopPropagation(); setActionMenu(actionMenu === node.id ? null : node.id); }}><MoreVertical size={16} /></button>
            {renderActionMenu(node)}
          </div>
        </div>
        {hasChildren && expanded[node.id] && node.children.map((child) => renderNode(child, depth + 1))}
      </div>
    );
  };

  if (loading) return <div className="page-container"><div className="skeleton" style={{ height: 520, borderRadius: 'var(--radius)' }} /></div>;

  const memberOptions = sortUsersByRolePriority(users.filter((user) => !(user.departments || []).some((dept) => dept.id === selected?.id)));
  const parentOptions = flat.filter((item) => item.id !== editing?.id);
  const openTasks = selectedTasks.filter((task) => openTaskStatuses.includes(task.status));
  const delayedTasks = selectedTasks.filter((task) => task.due_date && new Date(task.due_date) < new Date() && task.status !== 'done');

  return (
    <div className="page-container">
      <div className="page-header">
        <div>
        </div>
        <button className="btn btn-primary" onClick={() => openCreate(null)}><Plus size={16} /> بخش جدید</button>
      </div>

      <div className="org-summary-grid">
        {metrics.map(({ label, value, icon: Icon }) => (
          <div className="card org-stat" key={label}>
            <Icon size={18} />
            <span>{label}</span>
            <strong>{value}</strong>
          </div>
        ))}
      </div>

      {warnings.length > 0 && (
        <div className="org-alerts">
          {warnings.map((warning) => (
            <button type="button" className={`org-alert ${seenAlerts.has(warning.id) ? 'seen' : ''}`} key={warning.id} onClick={() => handleAlertClick(warning)}>
              <AlertTriangle size={16} />
              <span>{warning.text}</span>
              <em>{warning.action}</em>
            </button>
          ))}
        </div>
      )}

      <div className="card org-toolbar">
        <div className="org-search">
          <Search size={16} />
          <input className="form-input" placeholder="جستجو در دپارتمان‌ها، تیم‌ها و اعضا..." value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <FormSelect value={filter} onChange={(e) => setFilter(e.target.value)} style={{ maxWidth: 220 }}>
          <option value="all">همه</option>
          <option value="without_manager">بدون مدیر</option>
          <option value="without_members">بدون عضو</option>
          <option value="inactive">غیرفعال</option>
          <option value="with_active_project">دارای پروژه فعال</option>
          <option value="without_active_project">بدون پروژه فعال</option>
          <option value="members_without_team">اعضای بدون تیم</option>
        </FormSelect>
        <div className="org-view-toggle">
          <button className={view === 'tree' ? 'active' : ''} onClick={() => setView('tree')} title="حالت درختی"><ListTree size={16} /></button>
          <button className={view === 'cards' ? 'active' : ''} onClick={() => setView('cards')} title="حالت کارتی"><LayoutGrid size={16} /></button>
          <button className={view === 'table' ? 'active' : ''} onClick={() => setView('table')} title="حالت جدول"><Table2 size={16} /></button>
        </div>
      </div>

      {flat.length === 0 ? (
        <EmptyState icon={Building2} title="ساختار سازمانی تعریف نشده" description="اولین سازمان یا تیم را ایجاد کنید." action={<button className="btn btn-primary" onClick={() => openCreate(null)}>ایجاد ساختار</button>} />
      ) : view === 'tree' ? (
        <div className="org-layout">
          <div className="card org-tree-panel">{tree.map((node) => renderNode(node))}</div>
          <div className="card org-detail-panel">
            {selected ? (
              <>
                <div className="org-detail-head">
                  <div>
                    <span className="badge badge-info">{typeLabels[selected.type] || 'دپارتمان'}</span>
                    <h2>{selected.name}</h2>
                    <p>{selected.description || 'توضیحی ثبت نشده است'}</p>
                  </div>
                  <div className="org-detail-actions">
                    <button className="btn btn-outline org-detail-action-btn" onClick={() => openEdit(selected)}>ویرایش</button>
                    <button className="btn btn-primary org-detail-action-btn" onClick={() => openMemberModal('add')}><UserPlus size={16} /> افزودن عضو</button>
                  </div>
                </div>

                <div className="org-info-grid">
                  <Info label="مدیر" value={selected.manager?.name || 'بدون مدیر'} />
                  <Info label="بخش بالادستی" value={selected.parentName || 'بدون والد'} />
                  <Info label="تعداد اعضا" value={selectedMembers.length} />
                  <Info label="زیرمجموعه‌ها" value={(selected.children || []).length} />
                  <Info label="پروژه‌های فعال" value={selectedActiveProjects.length} />
                  <Info label="وضعیت" value={selected.is_active ? 'فعال' : 'غیرفعال'} />
                  <Info label="آخرین تغییر مدیر" value={asDateTime(selected.manager_changed_at)} />
                </div>

                <div className="tabs org-tabs">{tabs.map((tab) => <button key={tab} className={`tab ${activeTab === tab ? 'active' : ''}`} onClick={() => setActiveTab(tab)}>{tab}</button>)}</div>
                <DetailTab
                  tab={activeTab}
                  selected={selected}
                  directMembers={directMembers}
                  selectedMembers={selectedMembers}
                  descendants={descendants}
                  projects={selectedProjects}
                  tasks={selectedTasks}
                  sprints={selectedSprints}
                  logs={logs}
                  openTasks={openTasks}
                  delayedTasks={delayedTasks}
                  openMemberModal={openMemberModal}
                  removeMember={removeMember}
                  openCreate={openCreate}
                  openEdit={openEdit}
                  highlightTarget={highlightTarget}
                />
              </>
            ) : <EmptyState icon={Search} title="بخشی انتخاب نشده است" />}
          </div>
        </div>
      ) : view === 'cards' ? (
        <div className="grid grid-3">
          {visibleNodes.map((item) => {
            const Icon = typeIcons[item.type] || Folder;
            return (
              <div key={item.id} className="card org-section-card" onClick={() => { setSelectedId(item.id); setView('tree'); }}>
                <div className="org-section-card-head"><span className="org-node-icon"><Icon size={18} /></span><StatusBadge status={item.is_active ? 'active' : 'inactive'} /></div>
                <h3>{item.name}</h3>
                <p>{typeLabels[item.type] || 'دپارتمان'} · مدیر: {item.manager?.name || 'ندارد'}</p>
                <div className="org-mini-stats"><span>{item.users_count || 0} عضو</span><span>{(item.children || []).length} زیرمجموعه</span></div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="table-container">
            <table>
              <thead><tr><th>نام</th><th>نوع</th><th>مدیر</th><th>والد</th><th>اعضا</th><th>وضعیت</th><th>عملیات</th></tr></thead>
              <tbody>
                {visibleNodes.map((item) => (
                  <tr key={item.id}>
                    <td style={{ fontWeight: 600 }}>{item.name}</td>
                    <td>{typeLabels[item.type] || 'دپارتمان'}</td>
                    <td>{item.manager?.name || '—'}</td>
                    <td>{item.parentName || '—'}</td>
                    <td>{item.users_count || 0}</td>
                    <td><StatusBadge status={item.is_active ? 'active' : 'inactive'} /></td>
                    <td><button className="btn btn-sm btn-outline" onClick={() => { setSelectedId(item.id); setView('tree'); }}>جزئیات</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {sectionModal && (
        <Modal title={editing ? 'ویرایش بخش' : 'بخش جدید'} onClose={() => setSectionModal(false)} size="lg" footer={
          <><button className="btn btn-secondary" onClick={() => setSectionModal(false)}>انصراف</button><button className="btn btn-primary" onClick={saveSection} disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره'}</button></>
        }>
          <form onSubmit={saveSection}>
            <div className="grid grid-2">
              <Field label="نام بخش"><input className="form-input" value={sectionForm.name} onChange={(e) => setSectionForm({ ...sectionForm, name: e.target.value })} /></Field>
              <Field label="نوع بخش"><FormSelect value={sectionForm.type} onChange={(e) => setSectionForm({ ...sectionForm, type: e.target.value })}>{Object.entries(typeLabels).filter(([key]) => key !== 'person').map(([key, label]) => <option key={key} value={key}>{label}</option>)}</FormSelect></Field>
              <Field label="بخش بالادستی"><FormSelect value={sectionForm.parent_id} onChange={(e) => setSectionForm({ ...sectionForm, parent_id: e.target.value })}><option value="">بدون والد</option>{parentOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</FormSelect></Field>
              <Field label="مدیر بخش"><FormSelect data-field="manager_id" value={sectionForm.manager_id} onChange={(e) => setSectionForm({ ...sectionForm, manager_id: e.target.value })}><option value="">بدون مدیر</option>{sortUsersByRolePriority(users).map((user) => <option key={user.id} value={user.id}>{user.name}</option>)}</FormSelect></Field>
            </div>
            <Field label="توضیح کوتاه"><textarea className="form-textarea" value={sectionForm.description} onChange={(e) => setSectionForm({ ...sectionForm, description: e.target.value })} /></Field>
            <label className="org-check"><input type="checkbox" checked={sectionForm.is_active} onChange={(e) => setSectionForm({ ...sectionForm, is_active: e.target.checked })} /> فعال</label>
            <button type="button" className="btn btn-outline btn-sm" onClick={() => setAdvancedOpen(!advancedOpen)}>تنظیمات پیشرفته</button>
            {advancedOpen && <Field label="ترتیب نمایش"><input className="form-input" type="number" value={sectionForm.sort_order} onChange={(e) => setSectionForm({ ...sectionForm, sort_order: Number(e.target.value) || 0 })} /></Field>}
          </form>
        </Modal>
      )}

      {memberModal && (
        <Modal title={memberModal.mode === 'transfer' ? 'انتقال عضو' : memberModal.mode === 'edit' ? 'ویرایش عضویت' : 'افزودن عضو'} onClose={() => setMemberModal(null)} footer={
          <><button className="btn btn-secondary" onClick={() => setMemberModal(null)}>انصراف</button><button className="btn btn-primary" onClick={saveMember} disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره'}</button></>
        }>
          <form onSubmit={saveMember}>
            {memberModal.mode === 'add' ? (
              <Field label="عضو"><FormSelect value={memberForm.user_id} onChange={(e) => setMemberForm({ ...memberForm, user_id: e.target.value })}><option value="">انتخاب عضو</option>{memberOptions.map((user) => <option key={user.id} value={user.id}>{user.name} - {user.email}</option>)}</FormSelect></Field>
            ) : <Info label="عضو" value={memberModal.member?.name} />}
            {memberModal.mode === 'transfer' && <Field label="تیم/بخش مقصد"><FormSelect value={memberForm.target_department_id} onChange={(e) => setMemberForm({ ...memberForm, target_department_id: e.target.value })}><option value="">انتخاب مقصد</option>{flat.filter((item) => item.id !== selected?.id).map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</FormSelect></Field>}
            <Field label="نقش در تیم"><input className="form-input" value={memberForm.role_in_team} onChange={(e) => setMemberForm({ ...memberForm, role_in_team: e.target.value })} placeholder="مثلاً طراح محصول یا توسعه‌دهنده ارشد" /></Field>
            <label className="org-check"><input type="checkbox" checked={memberForm.is_primary} onChange={(e) => setMemberForm({ ...memberForm, is_primary: e.target.checked })} /> این تیم، تیم اصلی عضو باشد</label>
          </form>
        </Modal>
      )}

      {confirmDelete && (
        <ConfirmDialog
          title="حذف بخش"
          danger
          message={`اگر "${confirmDelete.name}" عضو یا زیرمجموعه داشته باشد حذف انجام نمی‌شود. بهتر است ابتدا اعضا، پروژه‌ها و زیرمجموعه‌ها را منتقل کنید یا بخش را غیرفعال کنید.`}
          confirmText="حذف نهایی"
          onConfirm={deleteSection}
          onCancel={() => setConfirmDelete(null)}
        />
      )}
    </div>
  );
}

function Field({ label, children }) {
  return <div className="form-group"><label className="form-label">{label}</label>{children}</div>;
}

function Info({ label, value }) {
  return <div className="org-info"><span>{label}</span><strong>{value ?? '—'}</strong></div>;
}

function DetailTab({ tab, selected, directMembers, selectedMembers, descendants, projects, tasks, sprints, logs, openTasks, delayedTasks, openMemberModal, removeMember, openCreate, openEdit, highlightTarget }) {
  if (tab === 'اعضا') {
    return directMembers.length === 0 ? <EmptyState icon={Users} title="عضوی در این بخش نیست" action={<button className="btn btn-primary" onClick={() => openMemberModal('add')}>افزودن عضو</button>} /> : (
      <div className="org-member-list">
        {directMembers.map((member) => {
          const membership = (member.departments || []).find((dept) => dept.id === selected.id);
          const activeProjects = projects.filter((project) => activeProjectStatuses.includes(project.status) && ((project.members || []).some((m) => m.id === member.id) || project.project_manager_id === member.id));
          return (
            <div id={`org-member-${member.id}`} className={`org-member-row ${highlightTarget === `org-member-${member.id}` ? 'org-highlight' : ''}`} key={member.id}>
              <div className="avatar avatar-sm">{member.name?.[0] || '?'}</div>
              <div><strong>{member.name}</strong><span>{getRoleName(member)} · {membership?.role_in_team || member.job_title || 'نقش تیمی ثبت نشده'}</span></div>
              <StatusBadge status={member.status || 'active'} />
              <span>{asDate(membership?.joined_at || member.created_at)}</span>
              <span>{activeProjects.length} پروژه فعال</span>
              {membership?.is_primary && <span className="badge badge-success">تیم اصلی</span>}
              <button className="btn btn-sm btn-outline" onClick={() => openMemberModal('edit', member)}>نقش</button>
              <button className="btn btn-sm btn-outline" onClick={() => openMemberModal('transfer', member)}>انتقال</button>
              <button className="btn btn-sm btn-danger" onClick={() => removeMember(member)}>حذف</button>
            </div>
          );
        })}
      </div>
    );
  }
  if (tab === 'زیرمجموعه‌ها') {
    return (selected.children || []).length === 0 ? <EmptyState icon={GitBranch} title="زیرمجموعه‌ای وجود ندارد" action={<button className="btn btn-primary" onClick={() => openCreate(selected.id)}>افزودن زیرمجموعه</button>} /> : (
      <div className="grid grid-2">{selected.children.map((child) => <div className="card org-child-card" key={child.id}><strong>{child.name}</strong><span>{typeLabels[child.type] || 'دپارتمان'} · {child.users_count || 0} عضو</span><button className="btn btn-sm btn-outline" onClick={() => openEdit(child)}>ویرایش</button></div>)}</div>
    );
  }
  if (tab === 'پروژه‌ها') {
    return projects.length === 0 ? <EmptyState icon={ClipboardList} title="پروژه‌ای به این بخش متصل نیست" /> : (
      <div className="table-container"><table><thead><tr><th>نام پروژه</th><th>وضعیت</th><th>مدیر پروژه</th><th>پیشرفت</th><th>تسک‌های باز</th><th>آخرین فعالیت</th></tr></thead><tbody>{projects.map((project) => <tr key={project.id}><td>{project.title}</td><td><StatusBadge status={project.status} /></td><td>{project.project_manager?.name || '—'}</td><td>{project.progress || 0}%</td><td>{openTasks.filter((task) => task.project_id === project.id).length}</td><td>{asDateTime(project.updated_at)}</td></tr>)}</tbody></table></div>
    );
  }
  if (tab === 'تسک‌ها') {
    return tasks.length === 0 ? <EmptyState icon={CheckCircle2} title="تسکی برای این بخش نیست" /> : (
      <div><div className="org-report-row"><Info label="تسک‌های باز" value={openTasks.length} /><Info label="تسک‌های عقب‌افتاده" value={delayedTasks.length} /><Info label="کل تسک‌ها" value={tasks.length} /></div><div className="table-container"><table><thead><tr><th>تسک</th><th>پروژه</th><th>مسئول</th><th>وضعیت</th><th>ددلاین</th></tr></thead><tbody>{tasks.slice(0, 12).map((task) => <tr key={task.id}><td>{task.title}</td><td>{task.project?.title || '—'}</td><td>{task.assignee?.name || '—'}</td><td><StatusBadge status={task.status} /></td><td>{asDate(task.due_date)}</td></tr>)}</tbody></table></div></div>
    );
  }
  if (tab === 'Sprintها') {
    return sprints.length === 0 ? <EmptyState icon={TimerReset} title="Sprint مرتبطی وجود ندارد" /> : (
      <div className="table-container"><table><thead><tr><th>نام Sprint</th><th>پروژه</th><th>شروع / پایان</th><th>تسک‌ها</th><th>انجام‌شده</th><th>عقب‌افتاده</th><th>وضعیت</th></tr></thead><tbody>{sprints.map((sprint) => <tr key={sprint.id}><td>{sprint.title}</td><td>{sprint.project?.title || '—'}</td><td>{asDate(sprint.start_date)} تا {asDate(sprint.end_date)}</td><td>{sprint.tasks?.length || 0}</td><td>{(sprint.tasks || []).filter((task) => task.status === 'done').length}</td><td>{(sprint.tasks || []).filter((task) => task.due_date && new Date(task.due_date) < new Date() && task.status !== 'done').length}</td><td><StatusBadge status={sprint.status} /></td></tr>)}</tbody></table></div>
    );
  }
  if (tab === 'گزارش عملکرد') {
    const done = tasks.filter((task) => task.status === 'done').length;
    return <div className="org-performance"><Info label="عملکرد بخش" value={`${tasks.length ? Math.round((done / tasks.length) * 100) : 0}%`} /><Info label="اعضای در محدوده" value={selectedMembers.length} /><Info label="پروژه‌های فعال" value={projects.filter((project) => activeProjectStatuses.includes(project.status)).length} /><Info label="تسک‌های باز" value={openTasks.length} /><Info label="تسک‌های عقب‌افتاده" value={delayedTasks.length} /><Info label="میانگین زمان انجام" value="نیازمند ثبت زمان واقعی" /></div>;
  }
  if (tab === 'تنظیمات') {
    return <div className="org-settings"><p>حذف مستقیم برای بخش‌هایی که عضو، پروژه، تسک یا زیرمجموعه دارند انجام نمی‌شود. ابتدا انتقال انجام دهید یا بخش را غیرفعال کنید.</p><button className="btn btn-outline" onClick={() => openEdit(selected)}><Settings size={16} /> ویرایش تنظیمات بخش</button></div>;
  }
  return logs.length === 0 ? <EmptyState icon={History} title="تاریخچه‌ای ثبت نشده است" /> : (
    <div className="org-history">{logs.map((log) => <div key={log.id}><strong>{log.description || log.action}</strong><span>{log.user?.name || 'سیستم'} · {asDateTime(log.created_at)}</span></div>)}</div>
  );
}
