import { Link } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { PageHeader } from '@/Components/UI/PageHeader';
import { EmptyState } from '@/Components/UI/EmptyState';
import { avatarColor, initials, roleLabel } from '@/lib/roles';
import { persianDigits } from '@/lib/persianDate';

type UserRow = {
  id: number;
  name: string;
  username: string;
  roleKey: string;
  status: string;
  schoolName: string | null;
  lastLoginAt: string | null;
  grantCount: number;
  grantable: boolean;
};

export default function Users({ users }: { users: UserRow[]; query: string }) {
  const [filter, setFilter] = useState('');

  const filtered = useMemo(() => {
    const q = filter.trim();
    if (!q) return users;
    return users.filter((u) =>
      u.name.includes(q)
      || u.username.includes(q)
      || (u.schoolName ?? '').includes(q)
      || roleLabel(u.roleKey).includes(q));
  }, [users, filter]);

  return (
    <AppLayout title="کاربران سامانه">
      <div className="page-stack">
        <PageHeader
          title="کاربران سامانه"
          icon="bi-people-fill"
          description="همه کاربران تمام مدارس. برای نقش‌های قابل‌تنظیم (معاون، معلم، پشتیبانی، مالی) می‌توانید دسترسی‌ها را با تیک تعیین کنید."
        />

        <div className="panel-card" style={{ padding: '0.9rem 1.1rem' }}>
          <div className="sidebar-search" style={{ margin: 0, background: 'var(--color-bg-soft)', borderColor: 'var(--color-border)' }}>
            <i className="bi bi-search" style={{ color: 'var(--color-text-soft)' }} />
            <input
              style={{ color: 'var(--color-text)' }}
              placeholder="جستجو بر اساس نام، نام کاربری، مدرسه یا نقش..."
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
            />
            {filter && (
              <button type="button" className="sidebar-search-clear" style={{ color: 'var(--color-text-soft)' }} onClick={() => setFilter('')}>
                <i className="bi bi-x-lg" />
              </button>
            )}
          </div>
        </div>

        {filtered.length === 0 ? (
          <div className="panel-card">
            <EmptyState icon="bi-people" title="کاربری پیدا نشد" description="عبارت دیگری جستجو کنید." />
          </div>
        ) : (
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>کاربر</th>
                  <th>مدرسه</th>
                  <th>نقش</th>
                  <th>وضعیت</th>
                  <th>آخرین ورود</th>
                  <th>دسترسی‌ها</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((user) => (
                  <tr key={user.id}>
                    <td>
                      <span style={{ alignItems: 'center', display: 'inline-flex', gap: '0.55rem' }}>
                        <span
                          className="topbar-avatar"
                          style={{ background: avatarColor(user.name), fontSize: '0.7rem', height: 30, width: 30 }}
                        >
                          {initials(user.name)}
                        </span>
                        <span style={{ display: 'grid', lineHeight: 1.4 }}>
                          <strong style={{ fontSize: '0.87rem' }}>{user.name}</strong>
                          <small style={{ color: 'var(--color-text-soft)', direction: 'ltr', textAlign: 'right' }}>{user.username}</small>
                        </span>
                      </span>
                    </td>
                    <td>{user.schoolName ?? '—'}</td>
                    <td><span className="badge badge-muted">{roleLabel(user.roleKey)}</span></td>
                    <td>
                      {user.status === 'active'
                        ? <span className="badge badge-success">فعال</span>
                        : <span className="badge badge-danger">غیرفعال</span>}
                    </td>
                    <td style={{ fontSize: '0.82rem', whiteSpace: 'nowrap' }}>{user.lastLoginAt ?? '—'}</td>
                    <td>
                      {user.grantable
                        ? <span className="badge badge-warning">{persianDigits(String(user.grantCount))} دسترسی</span>
                        : <span className="badge badge-muted">دسترسی کامل نقش</span>}
                    </td>
                    <td>
                      {user.grantable ? (
                        <Link className="btn btn-soft btn-sm" href={`/super-admin/users/${user.id}/permissions`}>
                          <i className="bi bi-person-lock" /> تنظیم دسترسی
                        </Link>
                      ) : (
                        <span style={{ color: 'var(--color-text-soft)', fontSize: '0.8rem' }}>—</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
