import React, { useEffect, useState, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import FormActionBar from '../FormActionBar'
import FormModalOverlay from '../FormModalOverlay'
import api from '../../utils/api'
import { useToast } from '../../context/ToastContext'
import { useAuth } from '../../context/AuthContext'
import { activeClubMemberships } from '../../utils/activeClub'

/**
 * Übernimmt den gespeicherten Ablauf einer geplanten Trainingseinheit in ein Rahmenprogramm (neu oder bestehend, Slot wählbar).
 */
export default function TrainingPublishToFrameworkModal({
  open,
  onClose,
  unitId,
  planningModalClubId,
  onSuccess,
}) {
  const navigate = useNavigate()
  const toast = useToast()
  const { user } = useAuth()
  const memberClubs = useMemo(() => activeClubMemberships(user?.clubs), [user?.clubs])
  const roleLc = String(user?.role || '').toLowerCase()
  const isSuperadmin = roleLc === 'superadmin'

  const [scope, setScope] = useState('existing')
  const [programs, setPrograms] = useState([])
  const [programsLoading, setProgramsLoading] = useState(false)
  const [fwProgramId, setFwProgramId] = useState('')
  const [fwDetail, setFwDetail] = useState(null)
  const [fwDetailLoading, setFwDetailLoading] = useState(false)

  const [slotMode, setSlotMode] = useState('new_slot')
  const [insertAt, setInsertAt] = useState('')
  const [existingSlotId, setExistingSlotId] = useState('')

  const [newTitle, setNewTitle] = useState('')
  const [newVisibility, setNewVisibility] = useState('private')
  const [newClubId, setNewClubId] = useState('')
  const [newGoalTitle, setNewGoalTitle] = useState('Aus geplanter Einheit')

  const [slotTitle, setSlotTitle] = useState('')
  const [slotNotes, setSlotNotes] = useState('')

  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (!open) {
      return
    }
    if (planningModalClubId != null && planningModalClubId !== '') {
      setNewClubId(String(planningModalClubId))
    } else if (memberClubs.length === 1) {
      setNewClubId(String(memberClubs[0].id))
    }
    setProgramsLoading(true)
    api
      .listTrainingFrameworkPrograms()
      .then((list) => {
        setPrograms(Array.isArray(list) ? list : [])
      })
      .catch(() => setPrograms([]))
      .finally(() => setProgramsLoading(false))
  }, [open, planningModalClubId, memberClubs])

  useEffect(() => {
    if (!open || scope !== 'existing' || !fwProgramId) {
      setFwDetail(null)
      return
    }
    const id = parseInt(fwProgramId, 10)
    if (!Number.isFinite(id) || id < 1) {
      setFwDetail(null)
      return
    }
    setFwDetailLoading(true)
    api
      .getTrainingFrameworkProgram(id)
      .then(setFwDetail)
      .catch(() => setFwDetail(null))
      .finally(() => setFwDetailLoading(false))
  }, [open, scope, fwProgramId])

  const sortedSlots = useMemo(() => {
    const sl = fwDetail?.slots
    if (!Array.isArray(sl)) return []
    return [...sl].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
  }, [fwDetail])

  const resetAndClose = () => {
    onClose()
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    if (!unitId || submitting) return

    setSubmitting(true)
    try {
      if (scope === 'new') {
        const tit = (newTitle || '').trim()
        if (!tit) {
          toast.error('Bitte einen Titel für das neue Rahmenprogramm angeben.')
          setSubmitting(false)
          return
        }
        const gt = (newGoalTitle || '').trim() || 'Entwicklungsziel'
        let club_id =
          newVisibility === 'club' && newClubId ? parseInt(newClubId, 10) : null
        if (newVisibility === 'club' && (!Number.isFinite(club_id) || club_id < 1)) {
          toast.error('Bitte einen Verein wählen (Sichtbarkeit „Verein“).')
          setSubmitting(false)
          return
        }
        if (newVisibility !== 'club') club_id = null

        const st = (slotTitle || '').trim()
        const sn = (slotNotes || '').trim()
        const created = await api.publishTrainingUnitToFramework(unitId, {
          new_framework: {
            title: tit,
            visibility: newVisibility,
            club_id,
            goals: [{ sort_order: 0, title: gt, notes: null }],
          },
          mode: 'new_slot',
          insert_at_index: null,
          ...(st ? { slot_title: st } : {}),
          ...(sn ? { slot_notes: slotNotes } : {}),
        })
        toast.success('Ablauf wurde im Rahmenprogramm gespeichert.')
        if (created?.id) {
          navigate(`/planning/framework-programs/${created.id}`)
        }
        onSuccess?.()
        resetAndClose()
        return
      } else {
        const fid = parseInt(fwProgramId, 10)
        if (!Number.isFinite(fid) || fid < 1) {
          toast.error('Bitte ein Rahmenprogramm auswählen.')
          setSubmitting(false)
          return
        }

        const payload = {
          framework_program_id: fid,
          mode: slotMode,
        }
        const st = (slotTitle || '').trim()
        const sn = (slotNotes || '').trim()
        if (st) payload.slot_title = st
        if (sn) payload.slot_notes = slotNotes
        if (slotMode === 'new_slot') {
          if (insertAt.trim() === '') {
            payload.insert_at_index = null
          } else {
            const n = parseInt(insertAt, 10)
            if (!Number.isFinite(n) || n < 0) {
              toast.error('Position: nicht negative Ganzzahl oder leer (anhängen).')
              setSubmitting(false)
              return
            }
            payload.insert_at_index = n
          }
        } else {
          const sid = parseInt(existingSlotId, 10)
          if (!Number.isFinite(sid) || sid < 1) {
            toast.error('Bitte einen Session-Slot zum Überschreiben wählen.')
            setSubmitting(false)
            return
          }
          payload.framework_slot_id = sid
        }

        const updated = await api.publishTrainingUnitToFramework(unitId, payload)
        toast.success('Ablauf wurde im Rahmenprogramm gespeichert.')
        if (updated?.id) {
          navigate(`/planning/framework-programs/${updated.id}`)
        }
        onSuccess?.()
        resetAndClose()
        return
      }
    } catch (err) {
      toast.error(err.message || 'Speichern fehlgeschlagen')
    } finally {
      setSubmitting(false)
    }
  }

  if (!open) return null

  return (
    <FormModalOverlay open={open} raised onBackdropClick={resetAndClose}>
      <div className="card modal-panel--form modal-panel--narrow">
        <h2 className="modal-panel__title">Ablauf ins Rahmenprogramm übernehmen</h2>
        <p className="modal-panel__intro">
          Es wird der <strong>zuletzt gespeicherte</strong> Ablauf dieser Einheit aus der Datenbank übernommen.
          Nicht gespeicherte Änderungen im Formular sind nicht enthalten — bitte vorher die Einheit speichern.
        </p>

        <form id="publish-framework-form" className="modal-form-shell" onSubmit={handleSubmit}>
          <div className="modal-form-shell__body">
          <div style={{ marginBottom: '1rem' }}>
            <span className="form-label">Ziel</span>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', marginTop: '0.35rem' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                <input
                  type="radio"
                  name="pf_scope"
                  checked={scope === 'existing'}
                  onChange={() => setScope('existing')}
                />
                Bestehendes Rahmenprogramm
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                <input
                  type="radio"
                  name="pf_scope"
                  checked={scope === 'new'}
                  onChange={() => setScope('new')}
                />
                Neues Rahmenprogramm
              </label>
            </div>
          </div>

          {scope === 'existing' ? (
            <>
              <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                <label className="form-label">Rahmenprogramm</label>
                <select
                  className="form-input"
                  value={fwProgramId}
                  onChange={(e) => {
                    setFwProgramId(e.target.value)
                    setExistingSlotId('')
                  }}
                  required
                >
                  <option value="">{programsLoading ? 'Laden…' : '— Wählen —'}</option>
                  {programs.map((p) => (
                    <option key={p.id} value={String(p.id)}>
                      {(p.title || '').trim() || `Rahmen #${p.id}`}
                    </option>
                  ))}
                </select>
              </div>

              <div style={{ marginBottom: '0.85rem' }}>
                <span className="form-label">Session-Platz</span>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: '0.35rem' }}>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                    <input
                      type="radio"
                      name="pf_slot"
                      checked={slotMode === 'new_slot'}
                      onChange={() => setSlotMode('new_slot')}
                    />
                    Neuen Session-Slot anlegen
                  </label>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                    <input
                      type="radio"
                      name="pf_slot"
                      checked={slotMode === 'existing_slot'}
                      onChange={() => setSlotMode('existing_slot')}
                    />
                    Bestehenden Slot überschreiben (Ablauf ersetzen)
                  </label>
                </div>
              </div>

              {slotMode === 'new_slot' ? (
                <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                  <label className="form-label">Position (0 = erste Stelle)</label>
                  <input
                    className="form-input"
                    type="text"
                    inputMode="numeric"
                    placeholder="Leer = ans Ende anhängen"
                    value={insertAt}
                    onChange={(e) => setInsertAt(e.target.value)}
                  />
                  <p style={{ fontSize: '0.78rem', color: 'var(--text3)', margin: '0.35rem 0 0' }}>
                    Die Reihenfolge der Slots kannst du in der Rahmen-Bearbeitung jederzeit ändern (Ziehen oder
                    Pfeile).
                  </p>
                </div>
              ) : (
                <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                  <label className="form-label">Slot</label>
                  <select
                    className="form-input"
                    value={existingSlotId}
                    onChange={(e) => setExistingSlotId(e.target.value)}
                    required={slotMode === 'existing_slot'}
                  >
                    <option value="">
                      {fwDetailLoading ? 'Laden…' : '— Session wählen —'}
                    </option>
                    {sortedSlots.map((s, i) => (
                      <option key={s.id} value={String(s.id)}>
                        {(s.title || '').trim() || `Session ${i + 1}`}
                      </option>
                    ))}
                  </select>
                </div>
              )}
            </>
          ) : (
            <>
              <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                <label className="form-label">Titel Rahmenprogramm</label>
                <input
                  className="form-input"
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                  placeholder="z. B. Saisonvorbereitung"
                  required
                />
              </div>
              <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                <label className="form-label">Erstes Entwicklungsziel (Pflichtfeld Rahmen)</label>
                <input
                  className="form-input"
                  value={newGoalTitle}
                  onChange={(e) => setNewGoalTitle(e.target.value)}
                />
              </div>
              <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                <label className="form-label">Sichtbarkeit</label>
                <select
                  className="form-input"
                  value={newVisibility}
                  onChange={(e) => {
                    const v = e.target.value
                    setNewVisibility(v)
                    if (v === 'club' && !newClubId && planningModalClubId != null) {
                      setNewClubId(String(planningModalClubId))
                    }
                  }}
                >
                  <option value="private">Privat</option>
                  <option value="club">Verein</option>
                  {isSuperadmin ? <option value="official">Offiziell</option> : null}
                </select>
              </div>
              {newVisibility === 'club' ? (
                <div className="form-row" style={{ marginBottom: '0.85rem' }}>
                  <label className="form-label">Verein</label>
                  <select
                    className="form-input"
                    value={newClubId}
                    onChange={(e) => setNewClubId(e.target.value)}
                  >
                    <option value="">— Verein wählen —</option>
                    {memberClubs.map((c) => (
                      <option key={c.id} value={String(c.id)}>
                        {c.name || `Verein #${c.id}`}
                      </option>
                    ))}
                  </select>
                </div>
              ) : null}
            </>
          )}

          <div className="form-row" style={{ marginBottom: '0.85rem' }}>
            <label className="form-label">Session-Titel (optional)</label>
            <input
              className="form-input"
              value={slotTitle}
              onChange={(e) => setSlotTitle(e.target.value)}
              placeholder="z. B. Woche 3 — Technik"
            />
          </div>
          <div className="form-row" style={{ marginBottom: '1.1rem' }}>
            <label className="form-label">Notizen zur Session (optional)</label>
            <textarea
              className="form-input"
              rows={2}
              value={slotNotes}
              onChange={(e) => setSlotNotes(e.target.value)}
            />
          </div>

          </div>

          <FormActionBar
            placement="bottom"
            variant="modal"
            formId="publish-framework-form"
            saving={submitting}
            showSave={false}
            saveAndCloseLabel="In Rahmen übernehmen"
            saveAndCloseShortLabel="Übernehmen"
            onCancel={resetAndClose}
          />
        </form>
      </div>
    </FormModalOverlay>
  )
}
