/**
 * RPRO3: Rubrik unter „Hilfe" für den RennmausPro-III-Backup-Import.
 * Laienverständlicher 3-Schritt-Ablauf:
 *   1) .backup (+ optional _bilder.zip) auswählen → „Auswerten" (schreibt nichts)
 *   2) Auswertung: Zählungen, Dubletten, mehrdeutige Namen, neu/vorhanden
 *   3) „Import durchführen" → Ergebnis
 * Alle Texte aus de.ts.
 */
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { de } from '../strings/de'
import { ApiError } from '../api/client'
import {
  analyzeRpro3,
  executeRpro3,
  type Rpro3AnalyzeResult,
  type Rpro3ExecuteResult,
} from '../api/rpro3'
import './rpro3-import.css'

const t = de.pages.rpro3Import

type Phase = 'select' | 'analyzing' | 'analyzed' | 'executing' | 'done'

export default function RennmausProImportPage() {
  const [backup, setBackup] = useState<File | null>(null)
  const [images, setImages] = useState<File | null>(null)
  const [phase, setPhase] = useState<Phase>('select')
  const [analysis, setAnalysis] = useState<Rpro3AnalyzeResult | null>(null)
  const [result, setResult] = useState<Rpro3ExecuteResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  function reset() {
    setBackup(null)
    setImages(null)
    setPhase('select')
    setAnalysis(null)
    setResult(null)
    setError(null)
  }

  async function handleAnalyze() {
    if (!backup) {
      setError(t.noBackup)
      return
    }
    setError(null)
    setPhase('analyzing')
    try {
      const res = await analyzeRpro3(backup, images)
      setAnalysis(res)
      setPhase('analyzed')
    } catch (err) {
      setError(err instanceof ApiError ? err.message : de.api.errors.unknown)
      setPhase('select')
    }
  }

  async function handleExecute() {
    if (!backup) return
    setError(null)
    setPhase('executing')
    try {
      const res = await executeRpro3(backup, images)
      setResult(res)
      setPhase('done')
    } catch (err) {
      setError(err instanceof ApiError ? err.message : de.api.errors.unknown)
      setPhase('analyzed')
    }
  }

  return (
    <section className="page rpro3-page">
      <h2>{t.title}</h2>
      <p className="rpro3-subtitle">{t.subtitle}</p>
      <p className="rpro3-intro">{t.intro}</p>

      {/* Umfang: was wird übernommen, was (noch) nicht */}
      <div className="rpro3-card rpro3-scope">
        <h3>{t.scope.title}</h3>
        <div className="rpro3-scope-cols">
          <div>
            <h4>{t.scope.importedTitle}</h4>
            <ul>
              {t.scope.imported.map((s, i) => (
                <li key={i}>{s}</li>
              ))}
            </ul>
          </div>
          <div>
            <h4>{t.scope.notImportedTitle}</h4>
            <ul>
              {t.scope.notImported.map((s, i) => (
                <li key={i}>{s}</li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      {error && (
        <div className="rpro3-error" role="alert">
          <strong>{t.errorTitle}:</strong> {error}
        </div>
      )}

      {/* Schritt 1: Dateien auswählen */}
      {phase !== 'done' && (
        <div className="rpro3-card">
          <h3>{t.step1Title}</h3>
          <div className="rpro3-field">
            <label htmlFor="rpro3-backup">{t.backupLabel}</label>
            <input
              id="rpro3-backup"
              type="file"
              accept=".backup,.zip,.db"
              disabled={phase === 'analyzing' || phase === 'executing'}
              onChange={(e) => setBackup(e.target.files?.[0] ?? null)}
            />
            <small>{t.backupHint}</small>
          </div>
          <div className="rpro3-field">
            <label htmlFor="rpro3-images">{t.imagesLabel}</label>
            <input
              id="rpro3-images"
              type="file"
              accept=".zip"
              disabled={phase === 'analyzing' || phase === 'executing'}
              onChange={(e) => setImages(e.target.files?.[0] ?? null)}
            />
            <small>{t.imagesHint}</small>
          </div>
          <button
            type="button"
            className="rpro3-btn rpro3-btn-primary"
            disabled={!backup || phase === 'analyzing' || phase === 'executing'}
            onClick={handleAnalyze}
          >
            {phase === 'analyzing' ? t.analyzing : t.analyzeButton}
          </button>
        </div>
      )}

      {/* Schritt 2: Auswertung */}
      {analysis && phase !== 'done' && (
        <AnalysisView analysis={analysis} />
      )}

      {/* Schritt 3: Import durchführen */}
      {analysis && (phase === 'analyzed' || phase === 'executing') && (
        <div className="rpro3-card">
          <h3>{t.step3Title}</h3>
          <p className="rpro3-warning">{t.executeWarning}</p>
          <button
            type="button"
            className="rpro3-btn rpro3-btn-primary"
            disabled={phase === 'executing'}
            onClick={handleExecute}
          >
            {phase === 'executing' ? t.executing : t.executeButton}
          </button>
        </div>
      )}

      {/* Ergebnis */}
      {result && phase === 'done' && (
        <div className="rpro3-card rpro3-success">
          <h3>{t.successTitle}</h3>
          <ul className="rpro3-result-list">
            <li><strong>{result.gerbilsImported}</strong> {t.resultCounts.gerbils}</li>
            <li><strong>{result.littersImported}</strong> {t.resultCounts.litters}</li>
            <li><strong>{result.contactsImported}</strong> {t.resultCounts.contacts}</li>
            <li><strong>{result.healthRecordsImported}</strong> {t.resultCounts.health}</li>
            <li><strong>{result.weightRecordsImported}</strong> {t.resultCounts.weights}</li>
            <li><strong>{result.photosImported}</strong> {t.resultCounts.photos}</li>
          </ul>
          <div className="rpro3-actions">
            <Link to="/rennmaeuse" className="rpro3-btn">{de.nav.gerbils}</Link>
            <button type="button" className="rpro3-btn" onClick={reset}>{t.restart}</button>
          </div>
        </div>
      )}
    </section>
  )
}

function AnalysisView({ analysis }: { analysis: Rpro3AnalyzeResult }) {
  const c = analysis.counts
  return (
    <div className="rpro3-card">
      <h3>{t.step2Title}</h3>

      <h4>{t.overviewTitle}</h4>
      <dl className="rpro3-counts">
        <Count label={t.counts.ownAnimals} value={c.ownAnimals} />
        <Count label={t.counts.externalAfterDedup} value={c.externalAfterDedup} />
        <Count label={t.counts.litters} value={c.litters} />
        <Count label={t.counts.contacts} value={c.contacts} />
        <Count label={t.counts.genotypes} value={c.genotypes} />
        <Count label={t.counts.duplicatesMerged} value={c.duplicatesMerged} />
      </dl>

      <p className="rpro3-hint">{t.dedupExplain}</p>

      <h4>{t.newVsExistingTitle}</h4>
      <p>
        <span className="rpro3-badge rpro3-badge-new">{t.newCount(analysis.newVsCurrentNew)}</span>{' '}
        <span className="rpro3-badge">{t.existingCount(analysis.newVsCurrentExisting)}</span>
      </p>

      <p className="rpro3-photos-note">
        {analysis.photosProvided ? t.photosNote(analysis.photoFilesAvailable) : t.photosNoneNote}
      </p>

      {analysis.topMerges.length > 0 && (
        <details className="rpro3-details">
          <summary>{t.topMergesTitle}</summary>
          <div className="rpro3-table-wrap">
            <table className="rpro3-table">
              <thead>
                <tr>
                  <th>{t.topMergesCol.name}</th>
                  <th>{t.topMergesCol.count}</th>
                  <th>{t.topMergesCol.dob}</th>
                  <th>{t.topMergesCol.farbe}</th>
                  <th>{t.topMergesCol.origin}</th>
                </tr>
              </thead>
              <tbody>
                {analysis.topMerges.map((m, i) => (
                  <tr key={i}>
                    <td>{m.name}</td>
                    <td>{m.recordCount}</td>
                    <td>{m.dob || '—'}</td>
                    <td>{m.farbe || '—'}</td>
                    <td>{m.origin || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </details>
      )}

      {analysis.ambiguousNames.length > 0 && (
        <details className="rpro3-details">
          <summary>{t.ambiguousTitle}</summary>
          <p className="rpro3-hint">{t.ambiguousIntro}</p>
          <ul className="rpro3-ambiguous">
            {analysis.ambiguousNames.map((a, i) => (
              <li key={i}>
                <strong>{a.name}</strong>
                <ul>
                  {a.variants.map((v, j) => (
                    <li key={j}>
                      {v.isOwn && <span className="rpro3-star" title={t.ambiguousOwn}>★ </span>}
                      {t.ambiguousVariant(v.count, v.dob, v.farbe, v.origin)}
                    </li>
                  ))}
                </ul>
              </li>
            ))}
          </ul>
        </details>
      )}
    </div>
  )
}

function Count({ label, value }: { label: string; value: number }) {
  return (
    <div className="rpro3-count">
      <dt>{label}</dt>
      <dd>{value}</dd>
    </div>
  )
}
