import { useState, useRef, useEffect } from 'react';
import { router, usePage } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type ResultRow = {
  id: number;
  type: 'user' | 'student';
  fullName: string;
  username: string;
  mobile: string;
  roleLabel: string;
  classroomName: string | null;
  lastLogin: string;
  mustChangePassword: boolean;
};

type NewCredential = {
  fullName: string;
  username: string;
  password: string;
  qrToken: string;
  loginUrl: string;
};

type Props = {
  results: ResultRow[];
  query: string;
  newCredential: NewCredential | null;
};

function QrImage({ loginUrl }: { loginUrl: string }) {
  const src = `https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(loginUrl)}&size=180x180&format=png&margin=8`;
  return (
    <img
      src={src}
      alt="QR Login"
      style={{ width: 90, height: 90, borderRadius: 8, border: '1px solid var(--color-border)', background: '#fff' }}
    />
  );
}

function CredentialCard({ cred, onDismiss }: { cred: NewCredential; onDismiss: () => void }) {
  return (
    <div style={{
      background: 'linear-gradient(135deg, var(--color-primary-soft) 0%, #e8faf5 100%)',
      border: '2px solid var(--color-primary)',
      borderRadius: 'var(--radius-lg)',
      padding: '1.5rem',
      display: 'flex',
      gap: '1.25rem',
      alignItems: 'flex-start',
      flexWrap: 'wrap',
      position: 'relative',
    }}>
      <button
        onClick={onDismiss}
        style={{ position: 'absolute', top: '0.75rem', left: '0.75rem', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', fontSize: '1.1rem', padding: '0.2rem' }}
        title="بستن"
      >
        <i className="bi bi-x-lg" />
      </button>

      {/* QR */}
      <div style={{ flexShrink: 0 }}>
        <QrImage loginUrl={cred.loginUrl} />
        <div style={{ fontSize: '0.65rem', color: 'var(--color-text-muted)', textAlign: 'center', marginTop: '0.3rem' }}>اسکن برای ورود</div>
      </div>

      {/* Credentials */}
      <div style={{ flex: 1, minWidth: 200 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.75rem' }}>
          <i className="bi bi-check-circle-fill" style={{ color: 'var(--color-primary)', fontSize: '1.1rem' }} />
          <strong style={{ fontSize: '1rem' }}>اطلاعات ورود بازنشانی شد</strong>
        </div>
        <div style={{ display: 'grid', gap: '0.5rem' }}>
          <CredRow icon="bi-person" label="نام" value={cred.fullName} />
          <CredRow icon="bi-at" label="نام کاربری" value={cred.username} mono />
          <CredRow icon="bi-key" label="رمز عبور جدید" value={cred.password} mono highlight />
        </div>
        <p style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)', marginTop: '0.75rem', marginBottom: 0 }}>
          <i className="bi bi-info-circle" style={{ marginLeft: '0.3rem' }} />
          QR کد یک‌بارمصرف — ۳۰ روز اعتبار — پس از اسکن اول باطل می‌شود.
        </p>
      </div>
    </div>
  );
}

function CredRow({ icon, label, value, mono, highlight }: { icon: string; label: string; value: string; mono?: boolean; highlight?: boolean }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(value).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); });
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: highlight ? 'rgba(14,166,120,0.12)' : 'rgba(255,255,255,0.6)', borderRadius: 8, padding: '0.4rem 0.7rem' }}>
      <i className={`bi ${icon}`} style={{ color: 'var(--color-primary)', flexShrink: 0 }} />
      <span style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)', flexShrink: 0 }}>{label}:</span>
      <span style={{ fontFamily: mono ? 'monospace' : 'inherit', fontWeight: highlight ? 800 : 600, fontSize: highlight ? '1rem' : '0.875rem', letterSpacing: mono ? '0.05em' : undefined, flex: 1 }}>{value}</span>
      <button onClick={copy} style={{ background: 'none', border: 'none', cursor: 'pointer', color: copied ? 'var(--color-primary)' : 'var(--color-text-muted)', fontSize: '0.85rem', padding: '0.1rem 0.3rem' }}>
        <i className={`bi ${copied ? 'bi-check2' : 'bi-copy'}`} />
      </button>
    </div>
  );
}

function ResetForm({ row, onCancel, query }: { row: ResultRow; onCancel: () => void; query: string }) {
  const [useCustom, setUseCustom] = useState(false);
  const [password, setPassword] = useState('');
  const [newUsername, setNewUsername] = useState('');
  const [processing, setProcessing] = useState(false);
  const { errors } = usePage().props as { errors: Record<string, string> };

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (processing) return;
    setProcessing(true);
    router.post(
      `/school/password-reset/${row.id}`,
      {
        password: useCustom ? password : '',
        new_username: newUsername || '',
        q: query,
      },
      {
        onFinish: () => setProcessing(false),
      }
    );
  }

  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', paddingTop: '0.5rem' }}>
      {/* Username change */}
      <div>
        <label className="form-label">نام کاربری جدید <span style={{ fontWeight: 400, color: 'var(--color-text-muted)' }}>(خالی بگذارید تا بدون تغییر بماند)</span></label>
        <input
          className="form-control"
          value={newUsername}
          onChange={e => setNewUsername(e.target.value)}
          placeholder={row.username}
          style={{ fontFamily: 'monospace', letterSpacing: '0.04em' }}
        />
        {errors.new_username && <div className="form-error">{errors.new_username}</div>}
      </div>

      {/* Password */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '0.4rem' }}>
          <label className="form-label" style={{ margin: 0 }}>رمز عبور جدید</label>
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.3rem', fontSize: '0.82rem', cursor: 'pointer', color: 'var(--color-text-muted)' }}>
            <input type="checkbox" checked={useCustom} onChange={e => setUseCustom(e.target.checked)} style={{ accentColor: 'var(--color-primary)' }} />
            رمز دستی
          </label>
        </div>
        {useCustom ? (
          <input
            className="form-control"
            type="text"
            value={password}
            onChange={e => setPassword(e.target.value)}
            placeholder="حداقل ۶ کاراکتر"
            minLength={6}
            style={{ fontFamily: 'monospace', letterSpacing: '0.05em' }}
          />
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'var(--color-bg-soft)', border: '1px dashed var(--color-border)', borderRadius: 'var(--radius-md)', padding: '0.65rem 0.9rem', fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
            <i className="bi bi-shuffle" />
            رمز تصادفی خوانا — ۸ کاراکتر — بعد از بازنشانی نمایش داده می‌شود
          </div>
        )}
      </div>

      <div style={{ display: 'flex', gap: '0.5rem' }}>
        <button className="btn btn-primary btn-sm" type="submit" disabled={processing}>
          <i className={`bi ${processing ? 'bi-hourglass-split' : 'bi-arrow-repeat'}`} />
          {processing ? 'در حال بازنشانی...' : 'بازنشانی و تولید QR جدید'}
        </button>
        <button className="btn btn-ghost btn-sm" type="button" onClick={onCancel}>انصراف</button>
      </div>
    </form>
  );
}

export default function PasswordReset({ results, query: initialQuery, newCredential }: Props) {
  const [query, setQuery] = useState(initialQuery);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const [cred, setCred] = useState<NewCredential | null>(newCredential);
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Update cred when page reloads with new credential
  useEffect(() => {
    if (newCredential) {
      setCred(newCredential);
      setExpandedId(null);
    }
  }, [newCredential]);

  function handleSearch(val: string) {
    setQuery(val);
    if (searchTimeout.current) clearTimeout(searchTimeout.current);
    searchTimeout.current = setTimeout(() => {
      if (val.trim().length >= 2) {
        router.get('/school/password-reset', { q: val }, { preserveState: true, replace: true });
      }
    }, 400);
  }

  return (
    <AppLayout title="بازنشانی رمز عبور">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2><i className="bi bi-key" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />بازنشانی رمز عبور</h2>
            <p>جستجو بر اساس نام، نام کاربری، موبایل، کد ملی یا کلاس — رمز و QR جدید بسازید</p>
          </div>
        </section>

        {/* New credential flash card */}
        {cred && (
          <section>
            <CredentialCard cred={cred} onDismiss={() => setCred(null)} />
          </section>
        )}

        {/* Search */}
        <section className="panel-card" style={{ padding: '1rem 1.25rem' }}>
          <div style={{ position: 'relative' }}>
            <i className="bi bi-search" style={{ position: 'absolute', right: '0.85rem', top: '50%', transform: 'translateY(-50%)', color: 'var(--color-text-muted)', pointerEvents: 'none' }} />
            <input
              ref={inputRef}
              className="form-control"
              value={query}
              onChange={e => handleSearch(e.target.value)}
              placeholder="نام، نام کاربری، موبایل، کد ملی یا کلاس..."
              style={{ paddingRight: '2.4rem' }}
              autoFocus
            />
          </div>
          {query.trim().length > 0 && query.trim().length < 2 && (
            <p style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginTop: '0.35rem', marginBottom: 0 }}>حداقل ۲ کاراکتر وارد کنید</p>
          )}
        </section>

        {/* Results */}
        {results.length > 0 ? (
          <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>موبایل</th>
                    <th>آخرین ورود</th>
                    <th style={{ width: 140 }}></th>
                  </tr>
                </thead>
                <tbody>
                  {results.map(row => (
                    <>
                      <tr key={row.id} style={{ background: expandedId === row.id ? 'var(--color-primary-soft)' : undefined }}>
                        <td style={{ fontWeight: 600 }}>
                          {row.mustChangePassword && (
                            <span title="باید رمز عبور تغییر دهد" style={{ color: '#f59e0b', marginLeft: '0.35rem' }}>
                              <i className="bi bi-exclamation-triangle-fill" />
                            </span>
                          )}
                          {row.fullName}
                        </td>
                        <td>
                          <span style={{ fontSize: '0.82rem' }}>{row.roleLabel}</span>
                          {row.classroomName && (
                            <span style={{ display: 'block', fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
                              <i className="bi bi-door-open" style={{ marginLeft: '0.2rem' }} />{row.classroomName}
                            </span>
                          )}
                        </td>
                        <td style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{row.username}</td>
                        <td style={{ direction: 'ltr', textAlign: 'right', fontSize: '0.85rem' }}>{row.mobile || '—'}</td>
                        <td style={{ fontSize: '0.82rem', color: 'var(--color-text-muted)' }}>{row.lastLogin}</td>
                        <td>
                          <button
                            className={`btn btn-sm ${expandedId === row.id ? 'btn-ghost' : 'btn-primary'}`}
                            onClick={() => setExpandedId(expandedId === row.id ? null : row.id)}
                          >
                            {expandedId === row.id
                              ? <><i className="bi bi-x" /> بستن</>
                              : <><i className="bi bi-key" /> بازنشانی</>
                            }
                          </button>
                        </td>
                      </tr>
                      {expandedId === row.id && (
                        <tr key={`${row.id}-form`}>
                          <td colSpan={6} style={{ background: 'var(--color-bg-soft)', padding: '1rem 1.25rem' }}>
                            <ResetForm row={row} onCancel={() => setExpandedId(null)} query={query} />
                          </td>
                        </tr>
                      )}
                    </>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ) : query.trim().length >= 2 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>
              <i className="bi bi-person-x" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.5rem', opacity: 0.35 }} />
              نتیجه‌ای یافت نشد
            </div>
          </section>
        ) : query.trim().length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--color-text-muted)' }}>
              <i className="bi bi-search" style={{ fontSize: '2.5rem', display: 'block', marginBottom: '0.5rem', opacity: 0.3 }} />
              <p style={{ margin: 0 }}>برای جستجو نام، نام کاربری، موبایل، کد ملی یا کلاس را وارد کنید</p>
            </div>
          </section>
        ) : null}
      </div>
    </AppLayout>
  );
}
