import { useState } from 'react';
import { Head, Link } from '@inertiajs/react';

type Card = {
  fullName: string;
  role: string;
  username: string;
  password: string;
};

type Props = {
  schoolName: string;
  loginUrl: string;
  cards: Card[];
};

function CardEl({
  card,
  perRow,
  buildQrUrl,
  schoolName,
  loginUrl,
}: {
  card: Card;
  perRow: 2 | 3;
  buildQrUrl: (card: Card) => string;
  schoolName: string;
  loginUrl: string;
}) {
  const sz = perRow === 3 ? 'sm' : 'md';
  return (
    <div className={`cred-card cred-card--${sz}`}>
      <div className="cred-card__head">
        <div className="cred-card__brand">
          <span className="cred-card__brand-mark">د</span>
          <div>
            <div className="cred-card__brand-name">دانشیار من</div>
            <div className="cred-card__brand-sub">اتوماسیون هوشمند مدارس</div>
          </div>
        </div>
        <div className="cred-card__school">{schoolName}</div>
      </div>
      <div className="cred-card__main">
        <div className="cred-card__qr-box">
          <img src={buildQrUrl(card)} alt="QR صفحه ورود" className="cred-card__qr" />
          <span>اسکن صفحه ورود</span>
        </div>
        <div className="cred-card__body">
          <div>
            <div className="cred-card__name">{card.fullName}</div>
            <div className="cred-card__role">{card.role}</div>
          </div>
          <div className="cred-card__row">
            <span>نام کاربری</span>
            <code>{card.username}</code>
          </div>
          <div className="cred-card__row cred-card__row--strong">
            <span>رمز اولیه</span>
            <code>{card.password}</code>
          </div>
          <div className="cred-card__row cred-card__url">
            <span>آدرس ورود</span>
            <code>{loginUrl}</code>
          </div>
        </div>
      </div>
      <div className="cred-card__foot">
        QR فقط صفحه ورود را باز می‌کند؛ ورود با نام کاربری و رمز چاپ‌شده انجام می‌شود. پس از اولین ورود رمز را تغییر دهید.
      </div>
    </div>
  );
}

export default function PrintCredentials({ schoolName, loginUrl, cards }: Props) {
  const [perRow, setPerRow] = useState<2 | 3>(2);

  const buildQrUrl = (card: Card) => {
    const url = new URL(loginUrl, window.location.origin);
    url.searchParams.set('u', card.username);

    return (
      `https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(
        url.toString()
      )}&size=140x140&format=svg&margin=2`
    );
  };

  const unsafeQrCount = cards.filter((card) => 'qrToken' in card).length;

  // Group into A4 pages: 2-per-row → 3 rows = 6 cards; 3-per-row → 3 rows = 9 cards
  const perPage = perRow === 2 ? 6 : 9;
  const pages: Card[][] = [];
  for (let i = 0; i < cards.length; i += perPage) {
    pages.push(cards.slice(i, i + perPage));
  }

  return (
    <div className="cred-root" dir="rtl">
      <Head title="چاپ کارت ورود" />

      {/* ---- Toolbar (screen only) ---- */}
      <div className="cred-toolbar no-print">
        <div>
          <strong>{cards.length} کارت آماده چاپ</strong>
          <small> — QR کارت‌ها ورود خودکار انجام نمی‌دهد؛ رمزها فقط همین یک بار نمایش داده می‌شوند.</small>
          {unsafeQrCount > 0 && <small className="cred-toolbar__warn"> داده قدیمی QR ورود خودکار نادیده گرفته شد.</small>}
        </div>
        <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
          <div className="layout-toggle">
            <span className="layout-toggle__label">چیدمان:</span>
            <button
              className={`layout-toggle__btn${perRow === 2 ? ' active' : ''}`}
              onClick={() => setPerRow(2)}
              type="button"
            >
              <i className="bi bi-layout-split" /> ۲ تایی
            </button>
            <button
              className={`layout-toggle__btn${perRow === 3 ? ' active' : ''}`}
              onClick={() => setPerRow(3)}
              type="button"
            >
              <i className="bi bi-grid-3x2-gap" /> ۳ تایی
            </button>
          </div>
          <div style={{ width: 1, height: 24, background: '#e2e8f0', margin: '0 0.25rem' }} />
          <button className="btn btn-primary" type="button" onClick={() => window.print()}>
            <i className="bi bi-printer" /> چاپ
          </button>
          <Link href="/school/credentials" className="btn btn-ghost">بازگشت</Link>
        </div>
      </div>

      {/* ---- Screen preview: A4 pages with shadow ---- */}
      <div className="pages-preview no-print">
        {pages.map((pageCards, pi) => (
          <div className="a4-wrap" key={pi}>
            {pages.length > 1 && (
              <div className="a4-label">صفحه {pi + 1} از {pages.length}</div>
            )}
            <div className="a4-paper">
              <div className={`cred-grid cred-grid--${perRow}`}>
                {pageCards.map((card, i) => (
                  <CardEl key={i} card={card} perRow={perRow} buildQrUrl={buildQrUrl} schoolName={schoolName} loginUrl={loginUrl} />
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ---- Print output: flat, browser paginates ---- */}
      <div className="print-output print-only">
        <div className={`cred-grid cred-grid--${perRow}`}>
          {cards.map((card, i) => (
            <CardEl key={i} card={card} perRow={perRow} buildQrUrl={buildQrUrl} schoolName={schoolName} loginUrl={loginUrl} />
          ))}
        </div>
      </div>

      <style>{`
        /* root */
        .cred-root { background: #eef2f7; min-height: 100vh; }

        /* toolbar */
        .cred-toolbar {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 1rem;
          padding: 0.75rem 1.25rem;
          background: #fff;
          border-bottom: 1px solid #e2e8f0;
          position: sticky;
          top: 0;
          z-index: 10;
          font-family: 'Estedad', 'Vazirmatn', sans-serif;
        }
        .cred-toolbar__warn {
          display: block;
          color: #b45309;
          margin-top: 0.15rem;
        }

        /* layout toggle */
        .layout-toggle {
          display: flex;
          align-items: center;
          gap: 0.3rem;
          background: #f1f5f9;
          border-radius: 8px;
          padding: 0.2rem;
        }
        .layout-toggle__label {
          font-size: 0.8rem;
          color: #64748b;
          padding: 0 0.4rem 0 0.2rem;
        }
        .layout-toggle__btn {
          display: flex;
          align-items: center;
          gap: 0.3rem;
          background: none;
          border: none;
          border-radius: 6px;
          padding: 0.3rem 0.7rem;
          font-size: 0.82rem;
          cursor: pointer;
          color: #64748b;
          font-family: inherit;
          transition: background 0.12s, color 0.12s;
        }
        .layout-toggle__btn.active {
          background: #fff;
          color: #0ea678;
          font-weight: 700;
          box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        .layout-toggle__btn:not(.active):hover { background: #e2e8f0; }

        /* preview area */
        .pages-preview {
          padding: 2rem 1.5rem;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 2.5rem;
        }
        .a4-wrap { width: 100%; max-width: 220mm; }
        .a4-label {
          text-align: center;
          font-size: 0.72rem;
          color: #94a3b8;
          margin-bottom: 0.5rem;
          font-family: 'Estedad', 'Vazirmatn', sans-serif;
          letter-spacing: 0.05em;
        }
        .a4-paper {
          background: #fff;
          box-shadow: 0 6px 32px rgba(0,0,0,0.14), 0 1px 4px rgba(0,0,0,0.07);
          border-radius: 2px;
          padding: 8mm 10mm;
          box-sizing: border-box;
          width: 100%;
        }

        /* grid */
        .cred-grid {
          display: grid;
          gap: 5mm;
          box-sizing: border-box;
        }
        .cred-grid--2 { grid-template-columns: 1fr 1fr; }
        .cred-grid--3 { grid-template-columns: 1fr 1fr 1fr; }

        /* card base */
        .cred-card {
          border: 1.2px solid #12352d;
          border-radius: 8px;
          overflow: hidden;
          font-family: 'Estedad', 'Vazirmatn', sans-serif;
          background: #fff;
          break-inside: avoid;
          page-break-inside: avoid;
          box-shadow: 0 1px 0 rgba(15, 23, 42, 0.06);
        }

        /* card — md (2-per-row) */
        .cred-card--md { font-size: 11px; }
        .cred-card--md .cred-card__head { padding: 8px 10px; }
        .cred-card--md .cred-card__brand-mark { width: 28px; height: 28px; font-size: 15px; }
        .cred-card--md .cred-card__brand-name { font-size: 14px; }
        .cred-card--md .cred-card__brand-sub { font-size: 8.5px; }
        .cred-card--md .cred-card__school { font-size: 10px; }
        .cred-card--md .cred-card__main { grid-template-columns: 86px minmax(0, 1fr); padding: 9px 10px; gap: 10px; }
        .cred-card--md .cred-card__qr { width: 74px; height: 74px; }
        .cred-card--md .cred-card__qr-box span { font-size: 8px; }
        .cred-card--md .cred-card__body { gap: 4px; }
        .cred-card--md .cred-card__name { font-size: 13.5px; }
        .cred-card--md .cred-card__role { font-size: 10px; }
        .cred-card--md .cred-card__row code { font-size: 11px; padding: 1px 4px; }
        .cred-card--md .cred-card__url code { font-size: 9px; max-width: 150px; }
        .cred-card--md .cred-card__foot { padding: 6px 10px; font-size: 8.5px; }

        /* card — sm (3-per-row) */
        .cred-card--sm { font-size: 9.5px; }
        .cred-card--sm .cred-card__head { padding: 6px 8px; }
        .cred-card--sm .cred-card__brand-mark { width: 22px; height: 22px; font-size: 12px; }
        .cred-card--sm .cred-card__brand-name { font-size: 11.5px; }
        .cred-card--sm .cred-card__brand-sub { font-size: 7px; }
        .cred-card--sm .cred-card__school { font-size: 8.5px; }
        .cred-card--sm .cred-card__main { grid-template-columns: 62px minmax(0, 1fr); padding: 7px 8px; gap: 7px; }
        .cred-card--sm .cred-card__qr { width: 54px; height: 54px; }
        .cred-card--sm .cred-card__qr-box span { font-size: 6.8px; }
        .cred-card--sm .cred-card__body { gap: 3px; }
        .cred-card--sm .cred-card__name { font-size: 10.5px; }
        .cred-card--sm .cred-card__role { font-size: 8.5px; }
        .cred-card--sm .cred-card__row code { font-size: 9px; padding: 1px 3px; }
        .cred-card--sm .cred-card__url code { font-size: 7.5px; max-width: 105px; }
        .cred-card--sm .cred-card__foot { padding: 4px 8px; font-size: 7px; }

        /* shared card parts */
        .cred-card__head {
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: linear-gradient(135deg, #06362d 0%, #0ea678 100%);
          color: #fff;
          gap: 8px;
          border-bottom: 1px solid rgba(15, 23, 42, 0.18);
        }
        .cred-card__brand { display: flex; align-items: center; gap: 7px; min-width: 0; }
        .cred-card__brand-mark {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          border-radius: 7px;
          background: rgba(255,255,255,0.16);
          border: 1px solid rgba(255,255,255,0.28);
          font-weight: 900;
          line-height: 1;
          flex-shrink: 0;
        }
        .cred-card__brand-name { font-weight: 900; color: #fff; line-height: 1.15; white-space: nowrap; }
        .cred-card__brand-sub { color: rgba(255,255,255,0.78); line-height: 1.25; white-space: nowrap; }
        .cred-card__school {
          font-weight: 700;
          color: rgba(255,255,255,0.92);
          line-height: 1.35;
          text-align: left;
          max-width: 48%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .cred-card__main {
          display: grid;
          align-items: center;
          direction: ltr;
          background:
            linear-gradient(180deg, rgba(14,166,120,0.06), rgba(255,255,255,0) 58%),
            #fff;
        }
        .cred-card__qr-box {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 3px;
          direction: rtl;
          color: #64748b;
        }
        .cred-card__qr {
          border-radius: 6px;
          background: #fff;
          padding: 3px;
          border: 1px solid #d7eee7;
          flex-shrink: 0;
        }
        .cred-card__body { display: flex; flex-direction: column; }
        .cred-card__body { direction: rtl; min-width: 0; }
        .cred-card__name { font-weight: 900; color: #0f172a; line-height: 1.25; }
        .cred-card__role { color: #0f766e; font-weight: 700; margin-top: 1px; margin-bottom: 2px; }
        .cred-card__row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 4px;
          border: 1px solid #e8f1ee;
          background: rgba(248, 250, 252, 0.76);
          border-radius: 5px;
          padding: 2px 5px;
        }
        .cred-card__row span { color: #64748b; white-space: nowrap; }
        .cred-card__row code {
          font-family: 'Courier New', monospace;
          color: #0f172a;
          background: #fff;
          border: 1px solid #e2e8f0;
          border-radius: 3px;
          direction: ltr;
          text-align: left;
          font-weight: 800;
          min-width: 0;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .cred-card__row--strong {
          border-color: rgba(14, 166, 120, 0.28);
          background: rgba(14, 166, 120, 0.08);
        }
        .cred-card__row--strong code { color: #065f46; border-color: rgba(14, 166, 120, 0.25); }
        .cred-card__url code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .cred-card__foot {
          background: #f7fbfa;
          border-top: 1px solid #dcebe7;
          color: #475569;
          text-align: center;
          line-height: 1.5;
        }

        @media (max-width: 760px) {
          .cred-toolbar {
            align-items: stretch;
            flex-direction: column;
          }
          .cred-toolbar > div:last-child {
            flex-wrap: wrap;
          }
          .cred-grid--2,
          .cred-grid--3 {
            grid-template-columns: 1fr;
          }
          .a4-paper { padding: 5mm; }
        }

        /* print */
        .print-output { display: none; }

        @media print {
          body { margin: 0; background: #fff !important; }
          .no-print { display: none !important; }
          .cred-root { background: #fff !important; }
          .print-output { display: block; }
          .cred-grid { gap: 5mm; }
        }

        @page { size: A4; margin: 8mm; }
      `}</style>
    </div>
  );
}
