import { useState } from 'react';
import { router } from '@inertiajs/react';
import { postJson } from '@/lib/api';
import { persianDigits } from '@/lib/persianDate';
import { SectionCard } from './shared';

export type ShareTokenInfo = {
  id: number;
  url: string;
  schoolYearId: number | null;
  term: number | null;
  expiresAt: string | null;
  viewCount: number;
};

type Props = {
  studentId: number;
  schoolYearId: number | null;
  term: number | null;
  tokens: ShareTokenInfo[];
};

/** پنل تولید/مدیریت لینک اشتراک‌گذاری کارنامه — فقط برای مدیر/معاون در پنل مدرسه. */
export function ShareLinkPanel({ studentId, schoolYearId, term, tokens }: Props) {
  const [busy, setBusy] = useState(false);
  const [copiedId, setCopiedId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [confirmingRevokeId, setConfirmingRevokeId] = useState<number | null>(null);

  async function generate() {
    setBusy(true);
    setError(null);
    try {
      await postJson('/school/report-card/share', {
        student_id: studentId,
        school_year_id: schoolYearId,
        term,
      });
      router.reload({ only: ['shareTokens'] });
    } catch {
      setError('ایجاد لینک با خطا مواجه شد. دوباره تلاش کنید.');
    } finally {
      setBusy(false);
    }
  }

  async function revoke(id: number) {
    setBusy(true);
    setError(null);
    try {
      const token = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content ?? '';
      await fetch(`/school/report-card/share/${id}`, {
        method: 'DELETE',
        headers: { 'X-CSRF-TOKEN': token, Accept: 'application/json' },
      });
      setConfirmingRevokeId(null);
      router.reload({ only: ['shareTokens'] });
    } catch {
      setError('باطل کردن لینک با خطا مواجه شد.');
    } finally {
      setBusy(false);
    }
  }

  function copy(url: string, id: number) {
    navigator.clipboard.writeText(url).then(() => {
      setCopiedId(id);
      setTimeout(() => setCopiedId((cur) => (cur === id ? null : cur)), 2000);
    });
  }

  return (
    <SectionCard title="لینک اشتراک‌گذاری کارنامه" icon="bi-link-45deg">
      <p className="rc-share-hint">
        این لینک بدون نیاز به رمز عبور باز می‌شود و فقط با دارندگان آن قابل مشاهده است — برای اشتراک با والدین مناسب است.
      </p>

      {tokens.length > 0 && (
        <ul className="rc-share-list">
          {tokens.map((t) => (
            <li key={t.id} className="rc-share-item">
              <code className="rc-share-url">{t.url}</code>
              <div className="rc-share-item-actions">
                <span className="rc-share-meta">
                  {t.viewCount > 0 ? `${persianDigits(t.viewCount)} بازدید` : 'بدون بازدید'}
                  {t.expiresAt ? ` · تا ${t.expiresAt}` : ''}
                </span>
                <button type="button" className="btn btn-soft btn-sm" onClick={() => copy(t.url, t.id)} disabled={busy}>
                  <i className={`bi ${copiedId === t.id ? 'bi-check-lg' : 'bi-clipboard'}`} />
                  {copiedId === t.id ? 'کپی شد' : 'کپی لینک'}
                </button>
                {confirmingRevokeId === t.id ? (
                  <>
                    <span className="rc-share-confirm-text">باطل شود؟</span>
                    <button type="button" className="btn btn-danger btn-sm" onClick={() => revoke(t.id)} disabled={busy}>
                      <i className="bi bi-check-lg" /> بله
                    </button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => setConfirmingRevokeId(null)} disabled={busy}>
                      انصراف
                    </button>
                  </>
                ) : (
                  <button type="button" className="btn btn-ghost btn-sm rc-share-revoke" onClick={() => setConfirmingRevokeId(t.id)} disabled={busy}>
                    <i className="bi bi-x-circle" /> باطل کردن
                  </button>
                )}
              </div>
            </li>
          ))}
        </ul>
      )}

      {error && <p className="rc-share-error">{error}</p>}

      <button type="button" className="btn btn-primary btn-sm" onClick={generate} disabled={busy}>
        <i className="bi bi-link" /> {busy ? 'در حال ایجاد…' : 'ایجاد لینک جدید'}
      </button>
    </SectionCard>
  );
}
