import { router, useForm } from '@inertiajs/react';
import { useRef, useState, useEffect, useCallback } from 'react';
import { AppLayout } from '@/Components/Layout/AppLayout';
import { PageHeader } from '@/Components/UI/PageHeader';
import { TextInput } from '@/Components/Forms/TextInput';
import { HelpTip } from '@/Components/UI/HelpTip';
import { avatarColor, initials, roleLabel } from '@/lib/roles';
import { persianDigits } from '@/lib/persianDate';

type Profile = {
  username: string;
  firstName: string;
  lastName: string;
  mobile: string | null;
  email: string | null;
  nationalCode: string | null;
  nationalCodeLocked: boolean;
  roleKey: string;
  schoolName: string | null;
  avatarUrl: string | null;
  lastLoginAt: string | null;
  lastLoginDevice: string | null;
  memberSince: string | null;
  profileCompletion?: {
    required: boolean;
    needsAttention: boolean;
    mustChangePassword: boolean;
    missingFields: Array<{ key: string; label: string }>;
    severity: 'warning' | 'danger';
  };
};

export default function Show({ profile }: { profile: Profile }) {
  const name = `${profile.firstName} ${profile.lastName}`.trim() || profile.username;

  const form = useForm({
    mobile: profile.mobile ?? '',
    email: profile.email ?? '',
    national_code: profile.nationalCode ?? '',
  });

  const passwordForm = useForm({
    current_password: '',
    password: '',
    password_confirmation: '',
  });

  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [avatarError, setAvatarError] = useState<string | null>(null);

  type Session = { id: string; ip: string | null; agent: string; lastActivity: string; isCurrent: boolean };
  const [sessions, setSessions] = useState<Session[]>([]);
  const [sessionsLoaded, setSessionsLoaded] = useState(false);
  const [sessionsLoading, setSessionsLoading] = useState(false);
  const [qrToken, setQrToken] = useState<string | null>(null);
  const [qrLoading, setQrLoading] = useState(false);
  const [qrCopied, setQrCopied] = useState(false);

  const loadSessions = useCallback(() => {
    setSessionsLoading(true);
    fetch('/profile/sessions').then(r => r.json()).then(d => {
      setSessions(d.sessions);
      setSessionsLoaded(true);
      setSessionsLoading(false);
    });
  }, []);

  const revokeOthers = () => {
    if (!confirm('از همه دستگاه‌های دیگر خارج شوید؟')) return;
    router.delete('/profile/sessions/others', { preserveScroll: true, onSuccess: () => loadSessions() });
  };

  const loadQr = () => {
    setQrLoading(true);
    fetch('/profile/qr-token').then(r => r.json()).then(d => { setQrToken(d.token); setQrLoading(false); });
  };

  const refreshQr = () => {
    setQrLoading(true);
    const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    fetch('/profile/qr-token/refresh', { method: 'POST', headers: { 'X-CSRF-TOKEN': csrf, 'Content-Type': 'application/json' }, credentials: 'same-origin' })
      .then(r => r.json())
      .then(d => { setQrToken(d.token); setQrLoading(false); });
  };

  const copyQrLink = () => {
    if (!qrToken) return;
    navigator.clipboard.writeText(`${window.location.origin}/qr-login/${qrToken}`).then(() => {
      setQrCopied(true);
      setTimeout(() => setQrCopied(false), 2500);
    });
  };

  const uploadAvatar = (file: File) => {
    setUploading(true);
    setAvatarError(null);
    router.post('/profile/avatar', { avatar: file }, {
      forceFormData: true,
      preserveScroll: true,
      onError: (errors) => setAvatarError(errors.avatar ?? 'خطا در آپلود عکس.'),
      onFinish: () => {
        setUploading(false);
        if (fileRef.current) fileRef.current.value = '';
      },
    });
  };

  const removeAvatar = () => {
    if (!confirm('عکس پروفایل حذف شود؟')) return;
    router.delete('/profile/avatar', { preserveScroll: true });
  };

  return (
    <AppLayout title="پروفایل من">
      <div className="page-stack">
        <PageHeader
          title="پروفایل من"
          icon="bi-person-circle"
          description="نام، نام خانوادگی و کد ملی توسط مدیر ثبت می‌شود و قابل ویرایش نیست. موبایل، ایمیل، عکس و رمز عبور را می‌توانید تغییر دهید."
        />

        {profile.profileCompletion?.needsAttention && (
          <section
            className={`profile-attention-panel profile-attention-panel--${profile.profileCompletion.severity}`}
            role="status"
          >
            <div className="profile-attention-panel__icon">
              <i className={`bi ${profile.profileCompletion.severity === 'danger' ? 'bi-exclamation-circle-fill' : 'bi-info-circle-fill'}`} />
            </div>
            <div>
              <h2>{profile.profileCompletion.required ? 'تکمیل اطلاعات برای حساب شما لازم است' : 'پروفایل شما چند مورد ناقص دارد'}</h2>
              <p>
                {profile.profileCompletion.required
                  ? 'برای استفاده کامل از سامانه این موارد را تکمیل کنید.'
                  : 'می‌توانید بعداً هم انجامش دهید، اما بهتر است اطلاعات حساب کامل باشد.'}
              </p>
              <div className="profile-attention-panel__items">
                {profile.profileCompletion.mustChangePassword && <span>تغییر رمز عبور</span>}
                {profile.profileCompletion.missingFields.map((field) => <span key={field.key}>{field.label}</span>)}
              </div>
            </div>
          </section>
        )}

        <div className="split-panel">
          <div className="page-stack">
            <form
              className="panel-card"
              onSubmit={(event) => { event.preventDefault(); form.put('/profile', { preserveScroll: true }); }}
            >
              <h2 style={{ marginBottom: '1rem' }}><i className="bi bi-pencil-square" style={{ marginLeft: '0.4rem' }} /> ویرایش اطلاعات</h2>
              <div className="form-grid">
                <div className="form-field">
                  <span>نام <HelpTip text="نام فقط توسط مدیر مدرسه یا مدیر سامانه قابل اصلاح است." /></span>
                  <div className="profile-locked-field">
                    <i className="bi bi-lock-fill" />
                    {profile.firstName || '—'}
                  </div>
                </div>
                <div className="form-field">
                  <span>نام خانوادگی</span>
                  <div className="profile-locked-field">
                    <i className="bi bi-lock-fill" />
                    {profile.lastName || '—'}
                  </div>
                </div>
                <TextInput label="موبایل" value={form.data.mobile} onChange={(e) => form.setData('mobile', e.target.value)} error={form.errors.mobile} placeholder="۰۹۱۲۳۴۵۶۷۸۹" />
                <TextInput label="ایمیل" type="email" value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} error={form.errors.email} />
                {profile.nationalCodeLocked ? (
                  <div className="form-field">
                    <span>کد ملی <HelpTip text="کد ملی بعد از ثبت اولیه قابل تغییر نیست. برای اصلاح با مدیر سامانه تماس بگیرید." /></span>
                    <div className="profile-locked-field">
                      <i className="bi bi-lock-fill" />
                      {persianDigits(profile.nationalCode ?? '')}
                    </div>
                  </div>
                ) : (
                  <TextInput
                    label="کد ملی (فقط یک بار قابل ثبت است)"
                    value={form.data.national_code}
                    onChange={(e) => form.setData('national_code', e.target.value)}
                    error={form.errors.national_code}
                    maxLength={10}
                  />
                )}
              </div>
              <button className="btn btn-primary" disabled={form.processing} type="submit">
                {form.processing
                  ? <><i className="bi bi-arrow-repeat btn-spin-icon" /> در حال ذخیره...</>
                  : <><i className="bi bi-check-lg" /> ذخیره اطلاعات</>}
              </button>
            </form>

            <form
              className="panel-card"
              onSubmit={(event) => {
                event.preventDefault();
                passwordForm.put('/profile/password', { preserveScroll: true, onSuccess: () => passwordForm.reset() });
              }}
            >
              <h2 style={{ marginBottom: '1rem' }}><i className="bi bi-shield-lock" style={{ marginLeft: '0.4rem' }} /> تغییر رمز عبور</h2>
              <div className="form-grid">
                <TextInput label="رمز فعلی" type="password" value={passwordForm.data.current_password} onChange={(e) => passwordForm.setData('current_password', e.target.value)} error={passwordForm.errors.current_password} />
                <TextInput label="رمز جدید (حداقل ۸ کاراکتر)" type="password" value={passwordForm.data.password} onChange={(e) => passwordForm.setData('password', e.target.value)} error={passwordForm.errors.password} />
                <TextInput label="تکرار رمز جدید" type="password" value={passwordForm.data.password_confirmation} onChange={(e) => passwordForm.setData('password_confirmation', e.target.value)} />
              </div>
              <button className="btn btn-soft" disabled={passwordForm.processing} type="submit">
                {passwordForm.processing
                  ? <><i className="bi bi-arrow-repeat btn-spin-icon" /> در حال ذخیره...</>
                  : <><i className="bi bi-key" /> تغییر رمز</>}
              </button>
            </form>
          </div>

          <aside style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            <div className="panel-card profile-side">
              {profile.avatarUrl ? (
                <span className="profile-avatar profile-avatar--photo">
                  <img src={profile.avatarUrl} alt={name} />
                </span>
              ) : (
                <span className="profile-avatar" style={{ background: avatarColor(name) }}>{initials(name)}</span>
              )}

              <div className="profile-avatar-actions">
                <input
                  ref={fileRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  style={{ display: 'none' }}
                  onChange={(e) => { const f = e.target.files?.[0]; if (f) uploadAvatar(f); }}
                />
                <button type="button" className="btn btn-soft btn-sm" disabled={uploading} onClick={() => fileRef.current?.click()}>
                  {uploading ? <><i className="bi bi-arrow-repeat" /> در حال آپلود...</> : <><i className="bi bi-camera" /> تغییر عکس</>}
                </button>
                {profile.avatarUrl && (
                  <button type="button" className="btn btn-danger-ghost btn-sm" onClick={removeAvatar}>
                    <i className="bi bi-trash" /> حذف
                  </button>
                )}
              </div>
              {avatarError && <small style={{ color: 'var(--color-danger)' }}>{avatarError}</small>}

              <h3>{name}</h3>
              <span className="badge badge-success">{roleLabel(profile.roleKey)}</span>
              <ul className="profile-meta">
                <li><i className="bi bi-person" /> <span>نام کاربری:</span> <strong>{profile.username}</strong></li>
                {profile.schoolName && <li><i className="bi bi-building" /> <span>مدرسه:</span> <strong>{profile.schoolName}</strong></li>}
                {profile.memberSince && <li><i className="bi bi-calendar3" /> <span>عضویت از:</span> <strong>{profile.memberSince}</strong></li>}
                {profile.lastLoginAt && (
                  <li>
                    <i className="bi bi-box-arrow-in-left" />
                    <span>آخرین ورود:</span>
                    <strong>{profile.lastLoginAt}</strong>
                    {profile.lastLoginDevice && (
                      <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginRight: '0.4rem' }}>
                        · <i className="bi bi-laptop" style={{ marginLeft: '0.2rem' }} />{profile.lastLoginDevice}
                      </span>
                    )}
                  </li>
                )}
              </ul>
            </div>

            {/* کد QR ورود */}
            <div className="panel-card" style={{ textAlign: 'center' }}>
              <h3 style={{ fontSize: '0.95rem', fontWeight: 700, marginBottom: '0.65rem' }}>
                <i className="bi bi-qr-code" style={{ marginLeft: '0.3rem' }} /> کد QR ورود
              </h3>
              <p style={{ fontSize: '0.8rem', color: 'var(--color-text-soft)', marginBottom: '0.75rem' }}>
                با اسکن کد QR بدون تایپ رمز وارد می‌شوید. ۳۰ روز اعتبار دارد.
              </p>
              {qrToken ? (
                <div>
                  <img
                    src={`https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(window.location.origin + '/qr-login/' + qrToken)}&size=180x180&format=svg`}
                    alt="QR ورود"
                    style={{ width: 160, height: 160, border: '1px solid var(--color-border)', borderRadius: 8, padding: 4 }}
                  />
                  <p style={{ fontSize: '0.72rem', color: 'var(--color-text-soft)', marginTop: '0.5rem' }}>
                    این کد را به کسی نشان ندهید.
                  </p>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', marginTop: '0.5rem' }}>
                    <div style={{ display: 'flex', gap: '0.4rem', justifyContent: 'center', flexWrap: 'wrap' }}>
                      <a
                        href="/profile/qr-download"
                        download="qr-login.png"
                        className="btn btn-soft btn-sm"
                      >
                        <i className="bi bi-download" /> دانلود
                      </a>
                      <button className="btn btn-ghost btn-sm" type="button" onClick={copyQrLink}>
                        {qrCopied
                          ? <><i className="bi bi-check2" /> کپی شد!</>
                          : <><i className="bi bi-link-45deg" /> کپی لینک</>}
                      </button>
                    </div>
                    <button className="btn btn-ghost btn-sm" type="button" onClick={refreshQr} disabled={qrLoading}>
                      {qrLoading
                        ? <><i className="bi bi-arrow-repeat btn-spin-icon" /> در حال بارگذاری...</>
                        : <><i className="bi bi-arrow-repeat" /> تجدید کد</>}
                    </button>
                  </div>
                </div>
              ) : (
                <button className="btn btn-soft btn-sm" type="button" onClick={loadQr} disabled={qrLoading}>
                  {qrLoading ? 'در حال بارگذاری...' : <><i className="bi bi-qr-code" /> نمایش کد QR</>}
                </button>
              )}
            </div>

            {/* دستگاه‌های فعال */}
            <div className="panel-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem' }}>
                <h3 style={{ fontSize: '0.95rem', fontWeight: 700 }}>
                  <i className="bi bi-laptop" style={{ marginLeft: '0.3rem' }} /> نشست‌ها و آخرین فعالیت
                </h3>
                {!sessionsLoaded ? (
                  <button className="btn btn-ghost btn-sm" type="button" onClick={loadSessions} disabled={sessionsLoading}>
                    {sessionsLoading ? <><i className="bi bi-arrow-repeat btn-spin-icon" /> بارگذاری...</> : 'نمایش'}
                  </button>
                ) : (
                  <button className="btn btn-danger-ghost btn-sm" type="button" onClick={revokeOthers}>
                    <i className="bi bi-box-arrow-right" /> خروج از سایر
                  </button>
                )}
              </div>
              {sessionsLoaded && (
                sessions.length === 0 ? (
                  <p style={{ fontSize: '0.82rem', color: 'var(--color-text-soft)' }}>نشست دیگری یافت نشد.</p>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                    {sessions.map(s => (
                      <div
                        key={s.id}
                        style={{
                          padding: '0.5rem 0.65rem',
                          borderRadius: 8,
                          background: s.isCurrent ? 'var(--color-primary-soft, #D9F3EA)' : 'var(--color-bg, #F1F5F9)',
                          fontSize: '0.8rem',
                        }}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                          <i className={`bi bi-${s.agent.includes('موبایل') ? 'phone' : 'pc-display'}`} />
                          <strong style={{ flex: 1 }}>{s.agent}</strong>
                          {s.isCurrent && <span style={{ fontSize: '0.7rem', color: 'var(--color-primary, #0EA678)' }}>دستگاه شما</span>}
                        </div>
                        <div style={{ color: 'var(--color-text-soft)', marginTop: '0.2rem' }}>
                          {s.ip ?? '—'} · آخرین آنلاین: {s.lastActivity}
                        </div>
                      </div>
                    ))}
                  </div>
                )
              )}
            </div>
          </aside>
        </div>
      </div>
    </AppLayout>
  );
}
