import { useState } from 'react'
import { importLegacySecondParents } from '../api/session'

type ImportSummary = {
  created_users?: number
  guardians_linked?: number
  skipped?: number
  total_source?: number
}

export function FamiliesImportLegacyPage() {
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const [summary, setSummary] = useState<ImportSummary | null>(null)

  async function runImport() {
    const confirmed = window.confirm(
      'Run the legacy second-parent import now? This will create users and attach guardians based on legacy records.',
    )
    if (!confirmed) return

    setBusy(true)
    setError(null)
    setMessage(null)

    try {
      const res = await importLegacySecondParents()
      setSummary(res.data ?? null)
      setMessage(res.message ?? 'Legacy import completed.')
    } catch (e) {
      setSummary(null)
      setError(e instanceof Error ? e.message : 'Legacy import failed.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="container-fluid py-3">
      <div className="mb-4">
        <h2 className="h4 mb-1">Import Legacy Families</h2>
        <p className="text-muted mb-0">
          Import second parents from the legacy <code>parents</code> table into the new family
          structure.
        </p>
      </div>

      <div className="row g-3">
        <div className="col-xl-7">
          <div className="card shadow-sm">
            <div className="card-header">Action</div>
            <div className="card-body">
              <div className="alert alert-warning small mb-3">
                This operation can create secondary user accounts, link guardians to families, and
                backfill student-family associations. Run it intentionally.
              </div>

              <ul className="small text-muted mb-4">
                <li>Creates users for email-only second parents when no user already exists.</li>
                <li>Links imported guardians into the family records for the primary parent.</li>
                <li>Ensures students for the primary parent are attached to the same family.</li>
              </ul>

              <button
                type="button"
                className="btn btn-danger"
                onClick={() => void runImport()}
                disabled={busy}
              >
                {busy ? 'Importing…' : 'Run Legacy Import'}
              </button>
            </div>
          </div>
        </div>

        <div className="col-xl-5">
          <div className="card shadow-sm">
            <div className="card-header">Latest Result</div>
            <div className="card-body">
              {error ? <div className="alert alert-danger small">{error}</div> : null}
              {message ? <div className="alert alert-success small">{message}</div> : null}

              {summary ? (
                <dl className="row mb-0">
                  <dt className="col-7">Source rows</dt>
                  <dd className="col-5 text-end">{summary.total_source ?? 0}</dd>

                  <dt className="col-7">Users created</dt>
                  <dd className="col-5 text-end">{summary.created_users ?? 0}</dd>

                  <dt className="col-7">Guardians linked</dt>
                  <dd className="col-5 text-end">{summary.guardians_linked ?? 0}</dd>

                  <dt className="col-7">Skipped rows</dt>
                  <dd className="col-5 text-end">{summary.skipped ?? 0}</dd>
                </dl>
              ) : (
                <p className="text-muted mb-0 small">
                  No import has been run in this session yet.
                </p>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
