import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import api from '../utils/api'
import TrainingUnitSectionsEditor from '../components/TrainingUnitSectionsEditor'
import FormActionBar from '../components/FormActionBar'
import UnsavedChangesPrompt from '../components/UnsavedChangesPrompt'
import { useBeforeUnloadWhen, useUnsavedChangesBlocker } from '../hooks/useUnsavedChangesBlocker'
import { useAuth } from '../context/AuthContext'
import { useToast } from '../context/ToastContext'
import {
  defaultSection,
  formSectionsFromPlanTemplateRows,
  templateSectionsPayloadFromFormSections,
} from '../utils/trainingUnitSectionsForm'
import {
  activeClubMemberships,
  getDefaultClubIdForGovernanceForms,
  getTenantClubDependencyKey,
} from '../utils/activeClub'

function templateFormSnapshot({ name, description, visibility, clubIdField, sections }) {
  return JSON.stringify({
    name: (name || '').trim(),
    description: (description || '').trim(),
    visibility: visibility || '',
    clubIdField: (clubIdField || '').trim(),
    sections: templateSectionsPayloadFromFormSections(sections),
  })
}

export default function TrainingPlanTemplateEditPage() {
  const { id: routeId } = useParams()
  const navigate = useNavigate()
  const templateId = parseInt(routeId, 10)
  const toast = useToast()
  const { user } = useAuth()
  const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
  const tenantClubDepKey = useMemo(() => getTenantClubDependencyKey(user), [user])

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [visibility, setVisibility] = useState('club')
  const [clubIdField, setClubIdField] = useState('')
  const [sections, setSections] = useState([defaultSection()])
  const [clubsForGovernanceForms, setClubsForGovernanceForms] = useState([])

  const baselineRef = useRef(null)
  const latestFormRef = useRef({})
  const [baselineReady, setBaselineReady] = useState(false)
  const [bypassDirty, setBypassDirty] = useState(false)

  latestFormRef.current = { name, description, visibility, clubIdField, sections }

  const dirtySignature = templateFormSnapshot(latestFormRef.current)
  const formDirtyEffective =
    baselineReady && baselineRef.current != null && !bypassDirty && !loading && dirtySignature !== baselineRef.current

  const blocker = useUnsavedChangesBlocker(Boolean(formDirtyEffective && !saving))
  useBeforeUnloadWhen(Boolean(formDirtyEffective && !saving))

  const membershipClubRows = useMemo(() => activeClubMemberships(user?.clubs ?? []), [user?.clubs])

  const visibilityClubChoices = useMemo(() => {
    if (isPlatformAdmin && clubsForGovernanceForms.length > 0) {
      return [...clubsForGovernanceForms].sort((a, b) =>
        String(a.name || '').localeCompare(String(b.name || ''), 'de')
      )
    }
    return [...membershipClubRows].sort((a, b) =>
      String(a.name || '').localeCompare(String(b.name || ''), 'de')
    )
  }, [isPlatformAdmin, clubsForGovernanceForms, membershipClubRows])

  useEffect(() => {
    if (!isPlatformAdmin) {
      setClubsForGovernanceForms([])
      return undefined
    }
    let cancelled = false
    ;(async () => {
      try {
        const list = await api.listClubs()
        if (!cancelled) setClubsForGovernanceForms(Array.isArray(list) ? list : [])
      } catch {
        if (!cancelled) setClubsForGovernanceForms([])
      }
    })()
    return () => {
      cancelled = true
    }
  }, [isPlatformAdmin, tenantClubDepKey])

  useEffect(() => {
    baselineRef.current = null
    setBaselineReady(false)
    setBypassDirty(false)
  }, [templateId])

  useEffect(() => {
    if (loading) return
    const handle = window.setTimeout(() => {
      baselineRef.current = templateFormSnapshot(latestFormRef.current)
      setBaselineReady(true)
    }, 120)
    return () => clearTimeout(handle)
  }, [loading, templateId])

  useEffect(() => {
    if (!Number.isFinite(templateId) || templateId < 1) {
      setError('Ungültige Vorlagen-ID')
      setLoading(false)
      return undefined
    }
    let cancelled = false
    async function load() {
      setLoading(true)
      setError('')
      try {
        const tpl = await api.getTrainingPlanTemplate(templateId)
        if (cancelled) return
        setName((tpl.name || '').trim())
        setDescription((tpl.description || '').trim())
        setVisibility((tpl.visibility || 'club').trim())
        setClubIdField(tpl.club_id != null ? String(tpl.club_id) : '')
        const nextSections = formSectionsFromPlanTemplateRows(tpl.sections)
        setSections(nextSections.length ? nextSections : [defaultSection()])
      } catch (e) {
        if (!cancelled) setError(e.message || 'Laden fehlgeschlagen')
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    load()
    return () => {
      cancelled = true
    }
  }, [templateId])

  const buildBody = useCallback(() => {
    let cid = null
    if (visibility === 'club') {
      const raw = (clubIdField || '').trim()
      if (raw !== '') {
        const p = parseInt(raw, 10)
        if (Number.isFinite(p) && p >= 1) cid = p
      } else if (visibilityClubChoices.length === 1) {
        cid = visibilityClubChoices[0].id
      }
    }
    return {
      name: name.trim(),
      description: description.trim() || null,
      visibility,
      club_id:
        cid != null && Number.isFinite(cid) && cid >= 1
          ? cid
          : visibility === 'club'
            ? undefined
            : null,
      sections: templateSectionsPayloadFromFormSections(sections),
    }
  }, [name, description, visibility, clubIdField, visibilityClubChoices, sections])

  const performSave = async ({ fromUnsavedDialog = false, closeAfter = false } = {}) => {
    if (!name.trim()) {
      toast.error('Name ist Pflicht.')
      return false
    }
    if (visibility === 'club') {
      const bodyPreview = buildBody()
      if (bodyPreview.club_id === undefined) {
        toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
        return false
      }
    }
    setSaving(true)
    setError('')
    try {
      await api.updateTrainingPlanTemplate(templateId, buildBody())
      baselineRef.current = templateFormSnapshot(latestFormRef.current)
      setBypassDirty(false)
      toast.success('Vorlage gespeichert.')
      if (closeAfter) navigate('/planning/plan-templates')
      return true
    } catch (err) {
      const msg = err.message || 'Speichern fehlgeschlagen'
      setError(msg)
      toast.error(msg)
      return false
    } finally {
      setSaving(false)
    }
  }

  const handleSave = async (e) => {
    e?.preventDefault?.()
    await performSave({ closeAfter: false })
  }

  const handleSaveAndClose = async () => {
    await performSave({ closeAfter: true })
  }

  const handleUnsavedDialogSave = async () => {
    const ok = await performSave({ fromUnsavedDialog: true })
    if (ok) blocker.proceed()
  }

  if (loading) {
    return (
      <div className="app-page" style={{ padding: '2rem 0', textAlign: 'center' }}>
        <div className="spinner" />
        <p>Laden …</p>
      </div>
    )
  }

  return (
    <div className="app-page">
      <p style={{ marginBottom: '0.75rem' }}>
        <Link to="/planning/plan-templates" style={{ color: 'var(--accent-dark)', fontWeight: 600 }}>
          ← Zurück zu Vorlagen
        </Link>
      </p>

      <h1 className="page-title" style={{ marginBottom: '0.35rem' }}>
        Trainingsvorlage bearbeiten
      </h1>
      <p style={{ color: 'var(--text2)', fontSize: '0.95rem', marginBottom: '1.25rem', maxWidth: '42rem', lineHeight: 1.5 }}>
        Nur die <strong>Abschnitts-Gliederung</strong> (inkl. Split-Sessions / parallele Gruppen) — ohne Übungen.
        Beim Anwenden auf eine Einheit wird der Ablauf als Struktur übernommen.
      </p>

      {error ? <p style={{ color: 'var(--danger)', marginBottom: '1rem' }}>{error}</p> : null}

      <form
        id="plan-template-form"
        className="card page-form-shell"
        style={{ padding: 'clamp(14px, 3vw, 1.75rem)', maxWidth: '920px' }}
        onSubmit={handleSave}
      >
        <div className="page-form-shell__scroll">
          <div className="form-row">
            <label className="form-label">Name *</label>
            <input className="form-input" value={name} onChange={(e) => setName(e.target.value)} />
          </div>

          <div className="form-row">
            <label className="form-label">Kurzbeschreibung</label>
            <textarea
              className="form-input"
              rows={2}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Wofür eignet sich diese Gliederung? (optional)"
            />
          </div>

          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 200px), 1fr))',
              gap: '12px',
              marginBottom: '1rem',
            }}
          >
            <div className="form-row" style={{ marginBottom: 0 }}>
              <label className="form-label">Sichtbarkeit</label>
              <select
                className="form-input"
                value={visibility}
                onChange={(e) => {
                  const v = e.target.value
                  setVisibility(v)
                  if (v === 'club' && !(clubIdField || '').trim()) {
                    const fb = getDefaultClubIdForGovernanceForms(user)
                    if (fb != null) setClubIdField(String(fb))
                  }
                }}
              >
                <option value="private">Privat (nur du)</option>
                <option value="club">Verein</option>
                {isPlatformAdmin ? <option value="official">Offiziell (global)</option> : null}
              </select>
            </div>
            {visibility === 'club' ? (
              <div className="form-row" style={{ marginBottom: 0 }}>
                <label className="form-label">Verein</label>
                <select
                  className="form-input"
                  value={clubIdField}
                  onChange={(e) => setClubIdField(e.target.value)}
                >
                  <option value="">— Verein wählen —</option>
                  {visibilityClubChoices.map((c) => (
                    <option key={c.id} value={String(c.id)}>
                      {c.name || `Verein #${c.id}`}
                    </option>
                  ))}
                </select>
              </div>
            ) : null}
          </div>

          <TrainingUnitSectionsEditor
            heading="Abschnitts-Gliederung"
            structureOnly
            enableParallelPhaseControls
            betweenInsertMenus={false}
            enableItemDragReorder={false}
            sections={sections}
            onSectionsChange={(updater) => setSections((prev) => updater(prev))}
          />
        </div>

        <FormActionBar
          placement="bottom"
          variant="page"
          formId="plan-template-form"
          saving={saving}
          onCancel={() => navigate('/planning/plan-templates')}
          onSaveAndClose={handleSaveAndClose}
        />
      </form>

      <UnsavedChangesPrompt
        blocker={blocker}
        isBusy={saving}
        onSave={handleUnsavedDialogSave}
        onDiscardWithoutSave={() => setBypassDirty(true)}
      />
    </div>
  )
}
