import { useState } from 'react';
import { useForm, router, usePage } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { TextInput } from '@/Components/Forms/TextInput';
import { SelectInput } from '@/Components/Forms/SelectInput';
import { Pagination } from '@/Components/Pagination';

type User = {
  id: number;
  username: string;
  firstName: string;
  lastName: string;
  fullName: string;
  mobile: string;
  email: string;
  role: string;
  roleLabel: string;
  status: string;
  lastLogin: string;
  mustChangePassword: boolean;
};

type Props = {
  users: User[];
  roles: Array<{ value: string; label: string }>;
  pagination: { total: number; perPage: number; currentPage: number; lastPage: number };
  filters: { q: string };
};

const statusLabel: Record<string, string> = {
  active: 'فعال',
  inactive: 'غیرفعال',
  blocked: 'مسدود',
};

const statusBadge: Record<string, string> = {
  active: 'badge-success',
  inactive: 'badge-muted',
  blocked: 'badge-danger',
};

export default function SchoolUsers({ users, roles, pagination, filters }: Props) {
  const { props } = usePage<{ flash?: { temp_password?: string } }>();
  const tempPassword = (props as { flash?: { temp_password?: string } }).flash?.temp_password;

  const [showForm, setShowForm] = useState(false);
  const [search, setSearch] = useState(filters.q);

  function doSearch(q: string) {
    setSearch(q);
    router.get('/school/users', { q, page: 1 }, { preserveScroll: true, replace: true });
  }
  const form = useForm({
    username: '',
    national_code: '',
    first_name: '',
    last_name: '',
    mobile: '',
    email: '',
    role_key: '',
    password: '',
  });

  function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    form.post('/school/users', {
      onSuccess: () => {
        form.reset();
        setShowForm(false);
      },
    });
  }

  function handleStatusChange(user: User, status: string) {
    if (!confirm(`تغییر وضعیت «${user.fullName}» به «${statusLabel[status]}»؟`)) return;
    router.put(`/school/users/${user.id}`, { status }, { preserveScroll: true });
  }

  function handleResetPassword(user: User) {
    if (!confirm(`بازنشانی رمز «${user.fullName}»؟ رمز موقت تولید می‌شود.`)) return;
    router.post(`/school/users/${user.id}/reset-password`, {}, { preserveScroll: true });
  }

  return (
    <AppLayout title="کاربران مدرسه">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>کاربران مدرسه</h2>
            <p>مدیریت نقش‌ها، وضعیت و رمز عبور کاربران.</p>
          </div>
          <div className="action-row">
            <input
              type="search"
              className="input-base"
              placeholder="جستجو (نام / نام کاربری)..."
              value={search}
              onChange={(e) => doSearch(e.target.value)}
              style={{ minWidth: 220 }}
            />
            <button className="btn btn-primary" onClick={() => setShowForm(!showForm)} type="button">
              <i className="bi bi-person-plus" /> کاربر جدید
            </button>
          </div>
        </section>

        {tempPassword && (
          <section className="panel-card" style={{ background: '#fef9c3', border: '1px solid #fde68a' }}>
            <h2><i className="bi bi-key" /> رمز موقت تولید شد</h2>
            <p style={{ fontFamily: 'monospace', fontSize: '1.1rem', fontWeight: 700 }}>{tempPassword}</p>
            <p>این رمز فقط یک بار نمایش داده می‌شود. آن را برای کاربر ارسال کنید.</p>
          </section>
        )}

        {showForm && (
          <form className="panel-card" onSubmit={handleSubmit}>
            <h2>کاربر جدید</h2>
            <div className="form-grid">
              <TextInput label="کد ملی" value={form.data.national_code} onChange={(e) => form.setData('national_code', e.target.value)} error={form.errors.national_code} dir="ltr" />
              <TextInput label="نام کاربری (خالی = کد ملی)" value={form.data.username} onChange={(e) => form.setData('username', e.target.value)} error={form.errors.username} />
              <TextInput label="نام" value={form.data.first_name} onChange={(e) => form.setData('first_name', e.target.value)} error={form.errors.first_name} />
              <TextInput label="نام خانوادگی" value={form.data.last_name} onChange={(e) => form.setData('last_name', e.target.value)} error={form.errors.last_name} />
              <TextInput label="موبایل" value={form.data.mobile} onChange={(e) => form.setData('mobile', e.target.value)} />
              <TextInput label="ایمیل" type="email" value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} />
              <SelectInput label="نقش" value={form.data.role_key} onChange={(e) => form.setData('role_key', e.target.value)} options={[{ value: '', label: 'انتخاب نقش' }, ...roles]} />
              <TextInput label="رمز اولیه" type="password" value={form.data.password} onChange={(e) => form.setData('password', e.target.value)} error={form.errors.password} />
            </div>
            <div className="action-row">
              <button className="btn btn-primary" disabled={form.processing} type="submit">ذخیره</button>
              <button className="btn btn-ghost" type="button" onClick={() => setShowForm(false)}>لغو</button>
            </div>
          </form>
        )}

        {users.length > 0 ? (
          <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>
                {users.map((user) => (
                  <tr key={user.id}>
                    <td>
                      {user.fullName}
                      {user.mustChangePassword && (
                        <span className="badge badge-warning" style={{ marginRight: '0.5rem' }}>رمز موقت</span>
                      )}
                    </td>
                    <td>{user.username}</td>
                    <td>{user.roleLabel}</td>
                    <td>{user.mobile || '—'}</td>
                    <td>{user.lastLogin}</td>
                    <td>
                      <span className={`badge ${statusBadge[user.status] || 'badge-muted'}`}>
                        {statusLabel[user.status] || user.status}
                      </span>
                    </td>
                    <td>
                      <div className="action-row--compact">
                        {user.status === 'active' ? (
                          <button
                            className="btn btn-ghost btn-sm"
                            type="button"
                            onClick={() => handleStatusChange(user, 'inactive')}
                          >
                            غیرفعال
                          </button>
                        ) : (
                          <button
                            className="btn btn-soft btn-sm"
                            type="button"
                            onClick={() => handleStatusChange(user, 'active')}
                          >
                            فعال‌سازی
                          </button>
                        )}
                        <button
                          className="btn btn-ghost btn-sm"
                          type="button"
                          onClick={() => handleResetPassword(user)}
                        >
                          <i className="bi bi-key" />
                        </button>
                        {user.role === 'moaven' && (
                          <a
                            className="btn btn-ghost btn-sm"
                            href={`/school/users/${user.id}/permissions`}
                            title="مدیریت دسترسی‌ها"
                          >
                            <i className="bi bi-shield-lock" />
                          </a>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <section className="panel-card">
            <h2>کاربری ثبت نشده</h2>
            <p>از دکمه «کاربر جدید» معاون، مدیر اجرایی یا کاربر دیگری اضافه کنید.</p>
          </section>
        )}

        <Pagination {...pagination} url="/school/users" extraParams={{ q: filters.q }} />
      </div>
    </AppLayout>
  );
}
