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

type AuditLog = {
  id: number;
  action: string;
  entityType: string;
  entityId: number | null;
  description: string | null;
  ipAddress: string;
  createdAt: string;
  user: string;
  role: string;
  school: string;
};

type LoginLog = {
  id: number;
  username: string;
  status: string;
  ipAddress: string;
  createdAt: string;
  school: string;
};

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

type Props = {
  schoolFilter: number | null;
  schools: School[];
  logs: AuditLog[];
  loginLogs: LoginLog[];
};

export default function AuditLogs({ schoolFilter, schools, logs, loginLogs }: Props) {
  const [tab, setTab] = useState<'audit' | 'login'>('audit');

  const schoolOptions = [
    { value: '', label: 'همه مدارس' },
    ...schools.map((s) => ({ value: String(s.id), label: s.name })),
  ];

  function handleSchoolFilter(schoolId: string) {
    router.get('/super-admin/audit-logs', schoolId ? { school_id: schoolId } : {}, { preserveState: true });
  }

  return (
    <AppLayout title="لاگ‌های سیستم">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>لاگ‌های امنیتی و فعالیت</h2>
            <p>آخرین ۲۰۰ رکورد فعالیت کاربران و لاگ‌های ورود.</p>
          </div>
          <div style={{ minWidth: 200 }}>
            <SelectInput
              label=""
              options={schoolOptions}
              value={schoolFilter ? String(schoolFilter) : ''}
              onChange={(e) => handleSchoolFilter(e.target.value)}
            />
          </div>
        </section>

        <div className="tab-bar">
          <button className={`tab-btn${tab === 'audit' ? ' active' : ''}`} type="button" onClick={() => setTab('audit')}>
            فعالیت‌ها ({logs.length})
          </button>
          <button className={`tab-btn${tab === 'login' ? ' active' : ''}`} type="button" onClick={() => setTab('login')}>
            لاگ ورود ({loginLogs.length})
          </button>
        </div>

        {tab === 'audit' && (
          <div className="table-wrap">
            {logs.length === 0 ? (
              <div className="panel-card"><p>لاگی ثبت نشده است.</p></div>
            ) : (
              <table className="data-table">
                <thead>
                  <tr>
                    <th>تاریخ</th>
                    <th>کاربر</th>
                    <th>نقش</th>
                    <th>مدرسه</th>
                    <th>اقدام</th>
                    <th>موضوع</th>
                    <th>شرح</th>
                    <th>IP</th>
                  </tr>
                </thead>
                <tbody>
                  {logs.map((log) => (
                    <tr key={log.id}>
                      <td style={{ fontSize: '0.8rem', whiteSpace: 'nowrap' }}>{log.createdAt}</td>
                      <td>{log.user}</td>
                      <td><code style={{ fontSize: '0.75rem' }}>{log.role}</code></td>
                      <td>{log.school}</td>
                      <td><code style={{ fontSize: '0.75rem' }}>{log.action}</code></td>
                      <td style={{ fontSize: '0.85rem' }}>{log.entityType}{log.entityId ? ` #${log.entityId}` : ''}</td>
                      <td style={{ fontSize: '0.85rem', maxWidth: '200px' }}>{log.description ?? '—'}</td>
                      <td style={{ fontSize: '0.78rem' }}>{log.ipAddress}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {tab === 'login' && (
          <div className="table-wrap">
            {loginLogs.length === 0 ? (
              <div className="panel-card"><p>لاگ ورودی ثبت نشده است.</p></div>
            ) : (
              <table className="data-table">
                <thead>
                  <tr>
                    <th>تاریخ</th>
                    <th>نام کاربری</th>
                    <th>مدرسه</th>
                    <th>وضعیت</th>
                    <th>IP</th>
                  </tr>
                </thead>
                <tbody>
                  {loginLogs.map((log) => (
                    <tr key={log.id}>
                      <td style={{ fontSize: '0.8rem', whiteSpace: 'nowrap' }}>{log.createdAt}</td>
                      <td>{log.username}</td>
                      <td>{log.school}</td>
                      <td>
                        <span className={`badge ${log.status === 'success' ? 'badge-success' : 'badge-danger'}`}>
                          {log.status === 'success' ? 'موفق' : 'ناموفق'}
                        </span>
                      </td>
                      <td style={{ fontSize: '0.78rem' }}>{log.ipAddress}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
