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

type TokenRow = {
  id: number;
  name: string;
  abilities: string;
  lastUsedAt: string;
  expiresAt: string;
  createdAt: string;
};

type Props = {
  tokens: TokenRow[];
  plainToken?: string | null;
};

export default function ApiTokens({ tokens, plainToken }: Props) {
  const [name, setName] = useState('');
  const [abilities, setAbilities] = useState<string[]>(['grades:read', 'attendance:read']);

  function toggleAbility(value: string) {
    setAbilities((prev) => prev.includes(value) ? prev.filter((item) => item !== value) : [...prev, value]);
  }

  function createToken(e: React.FormEvent) {
    e.preventDefault();
    router.post('/school/api-tokens', { name, abilities }, {
      preserveScroll: true,
      onSuccess: () => setName(''),
    });
  }

  return (
    <AppLayout title="توکن API">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>API عمومی مدرسه</h2>
            <p>توکن REST برای دریافت نمرات و حضور و غیاب</p>
          </div>
        </section>

        {plainToken && (
          <section className="panel-card" style={{ borderColor: '#0EA678' }}>
            <h3 style={{ marginTop: 0 }}>توکن جدید</h3>
            <code style={{ display: 'block', direction: 'ltr', whiteSpace: 'normal', wordBreak: 'break-all', background: 'var(--color-bg-muted)', padding: '0.8rem', borderRadius: 8 }}>
              {plainToken}
            </code>
            <p style={{ color: 'var(--color-text-muted)', marginBottom: 0 }}>این مقدار فقط همین یک بار نمایش داده می‌شود.</p>
          </section>
        )}

        <form className="panel-card" onSubmit={createToken}>
          <div className="form-grid">
            <label>
              <span>نام توکن</span>
              <input className="form-input" value={name} onChange={(e) => setName(e.target.value)} required placeholder="مثلاً اتصال گزارش‌گیر" />
            </label>
            <div>
              <span style={{ display: 'block', fontWeight: 700, marginBottom: 8 }}>دسترسی‌ها</span>
              <label style={{ marginLeft: 16 }}><input type="checkbox" checked={abilities.includes('grades:read')} onChange={() => toggleAbility('grades:read')} /> نمرات</label>
              <label><input type="checkbox" checked={abilities.includes('attendance:read')} onChange={() => toggleAbility('attendance:read')} /> حضور و غیاب</label>
            </div>
          </div>
          <button className="btn btn-primary" type="submit" style={{ marginTop: 16 }}><i className="bi bi-key" /> ساخت توکن</button>
        </form>

        <section className="panel-card" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="data-table">
            <thead>
              <tr>
                <th>نام</th>
                <th>دسترسی</th>
                <th>آخرین استفاده</th>
                <th>انقضا</th>
                <th>ساخته شده</th>
                <th>عملیات</th>
              </tr>
            </thead>
            <tbody>
              {tokens.map((token) => (
                <tr key={token.id}>
                  <td>{token.name}</td>
                  <td>{token.abilities || '—'}</td>
                  <td>{token.lastUsedAt}</td>
                  <td>{token.expiresAt}</td>
                  <td>{token.createdAt}</td>
                  <td>
                    <button className="btn btn-ghost btn-sm" type="button" onClick={() => confirm('توکن حذف شود؟') && router.delete(`/school/api-tokens/${token.id}`)}>
                      <i className="bi bi-trash" />
                    </button>
                  </td>
                </tr>
              ))}
              {tokens.length === 0 && <tr><td colSpan={6} style={{ textAlign: 'center' }}>توکنی ساخته نشده است.</td></tr>}
            </tbody>
          </table>
        </section>

        <section className="panel-card">
          <h3 style={{ marginTop: 0 }}>نمونه درخواست</h3>
          <code style={{ display: 'block', direction: 'ltr', whiteSpace: 'normal', wordBreak: 'break-all' }}>
            GET /api/public/grades Authorization: Bearer YOUR_TOKEN
          </code>
        </section>
      </div>
    </AppLayout>
  );
}
