import { useState } from 'react';
import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type Log = {
  id: number;
  username: string;
  school: string;
  status: 'success' | 'failed';
  ip: string;
  createdAt: string;
};

type School = { id: number; name: string };

type Props = {
  logs: Log[];
  total: number;
  page: number;
  perPage: number;
  schools: School[];
  filters: { status: string | null; search: string | null; schoolId: number | null };
};

export default function LoginLogs({ logs, total, page, perPage, schools, filters }: Props) {
  const [search, setSearch] = useState(filters.search ?? '');
  const [status, setStatus] = useState(filters.status ?? '');
  const [schoolId, setSchoolId] = useState(filters.schoolId ? String(filters.schoolId) : '');
  const [deleteDays, setDeleteDays] = useState('30');

  function applyFilters() {
    router.get('/super-admin/login-logs', {
      ...(search ? { search } : {}),
      ...(status ? { status } : {}),
      ...(schoolId ? { school_id: schoolId } : {}),
    }, { preserveScroll: true });
  }

  function deleteOld() {
    if (!confirm(`لاگ‌های قدیمی‌تر از ${deleteDays} روز حذف شوند؟`)) return;
    router.delete('/super-admin/login-logs/delete-old', { data: { days: deleteDays }, preserveScroll: true });
  }

  const totalPages = Math.ceil(total / perPage);

  return (
    <AppLayout title="لاگ ورود کاربران">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-shield-lock" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />لاگ ورود کاربران</h2>
            <p>سابقه ورود و خروج همه کاربران سامانه</p>
          </div>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
            <input
              className="form-control"
              style={{ width: 140 }}
              placeholder="جستجو نام کاربری"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && applyFilters()}
            />
            <select className="form-control" style={{ width: 120 }} value={status} onChange={(e) => { setStatus(e.target.value); }}>
              <option value="">همه</option>
              <option value="success">موفق</option>
              <option value="failed">ناموفق</option>
            </select>
            <select className="form-control" style={{ width: 160 }} value={schoolId} onChange={(e) => setSchoolId(e.target.value)}>
              <option value="">همه مدارس</option>
              {schools.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
            </select>
            <button className="btn btn-primary btn-sm" onClick={applyFilters}>
              <i className="bi bi-search" />
            </button>
          </div>
        </section>

        <div className="panel-card" style={{ background: 'var(--color-bg-soft)', display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap' }}>
          <span style={{ fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
            <i className="bi bi-trash" style={{ marginLeft: '0.3rem' }} />
            حذف لاگ‌های قدیمی‌تر از
          </span>
          <input
            type="number"
            className="form-control"
            style={{ width: 80 }}
            value={deleteDays}
            min={1}
            max={365}
            onChange={(e) => setDeleteDays(e.target.value)}
          />
          <span style={{ fontSize: '0.875rem' }}>روز</span>
          <button className="btn btn-danger btn-sm" onClick={deleteOld}>
            <i className="bi bi-trash" /> حذف لاگ‌های قدیمی
          </button>
          <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginRight: 'auto' }}>
            مجموع: {total} لاگ
          </span>
        </div>

        {logs.length === 0 ? (
          <div className="panel-card" style={{ textAlign: 'center', color: 'var(--color-text-muted)', padding: '2rem' }}>
            <i className="bi bi-inbox" style={{ fontSize: '2rem', display: 'block', marginBottom: '0.5rem' }} />
            لاگی یافت نشد.
          </div>
        ) : (
          <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ width: '100%' }}>
                <thead>
                  <tr>
                    <th>کاربر</th>
                    <th>مدرسه</th>
                    <th>وضعیت</th>
                    <th>نشانی IP</th>
                    <th>زمان</th>
                  </tr>
                </thead>
                <tbody>
                  {logs.map((log) => (
                    <tr key={log.id}>
                      <td style={{ fontWeight: 600 }}>{log.username}</td>
                      <td style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>{log.school}</td>
                      <td>
                        <span className={`badge ${log.status === 'success' ? 'badge-success' : 'badge-danger'}`}>
                          {log.status === 'success' ? <><i className="bi bi-check-lg" /> موفق</> : <><i className="bi bi-x-lg" /> ناموفق</>}
                        </span>
                      </td>
                      <td style={{ fontFamily: 'monospace', fontSize: '0.82rem', direction: 'ltr', textAlign: 'right' }}>{log.ip}</td>
                      <td style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>{log.createdAt}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}

        {totalPages > 1 && (
          <div style={{ display: 'flex', gap: '0.4rem', justifyContent: 'center', flexWrap: 'wrap' }}>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
              <button
                key={p}
                className={`btn btn-sm ${p === page ? 'btn-primary' : 'btn-ghost'}`}
                onClick={() => router.get('/super-admin/login-logs', { ...filters, page: p }, { preserveScroll: true })}
              >
                {p}
              </button>
            ))}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
