'use client'

import { useState, useEffect } from 'react'
import { classMaxHoursDayApi, classNoGapsApi, classesApi } from '@/lib/stundenplan/api'
import type {
  ClassMaxHoursDay, ClassNoGaps, TimetableClass,
} from '@/app/stundenplan/types'
import { useConstraintCrud, ConstraintShell, useShellStyles } from './_shell'

function useClasses() {
  const [classes, setClasses] = useState<TimetableClass[]>([])
  useEffect(() => { classesApi.list().then(setClasses).catch(() => setClasses([])) }, [])
  return classes
}

function cLabel(classes: TimetableClass[], id: string): string {
  const c = classes.find(x => x.id === id)
  return c ? c.name : id.slice(0, 8) + '…'
}

// ---------- Max Hours / Day ----------

type DayForm = Omit<ClassMaxHoursDay, 'id' | 'created_by_user_id' | 'created_at'>
const initialDay: DayForm = { class_id: '', max_hours: 6, is_hard: true, weight: 100, active: true, note: '' }

export function ClassMaxHoursDayEditor() {
  const styles = useShellStyles()
  const classes = useClasses()
  const crud = useConstraintCrud<ClassMaxHoursDay, DayForm>(classMaxHoursDayApi, initialDay)

  return (
    <ConstraintShell
      testId="class-max-hours-day-editor"
      title="Klasse: Max. Stunden / Tag"
      description={"Beispiel: „5a hoechstens 6 Stunden pro Tag" (jugendgerecht)."}
      newLabel="+ Neue Regel"
      newDisabled={classes.length === 0}
      prereqWarning={classes.length === 0 ? 'Zuerst Klassen anlegen.' : null}
      emptyText="Keine Regeln vorhanden."
      tableHeaders={['Klasse', 'Max. Std/Tag', 'Hart', 'Weight']}
      state={crud}
      formBody={
        <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
          <div>
            <label className="block text-sm mb-1 opacity-70">Klasse</label>
            <select required value={crud.form.class_id} onChange={e => crud.setForm({ ...crud.form, class_id: e.target.value })} className={`w-full px-3 py-2 rounded-lg border ${styles.inputClass}`}>
              <option value="">— bitte waehlen —</option>
              {classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm mb-1 opacity-70">Max. Stunden (1-12)</label>
            <input type="number" min={1} max={12} required value={crud.form.max_hours} onChange={e => crud.setForm({ ...crud.form, max_hours: parseInt(e.target.value) || 1 })} className={`w-full px-3 py-2 rounded-lg border ${styles.inputClass}`} />
          </div>
          <div>
            <label className="block text-sm mb-1 opacity-70">Weight (0-100)</label>
            <input type="number" min={0} max={100} value={crud.form.weight} onChange={e => crud.setForm({ ...crud.form, weight: parseInt(e.target.value) || 0 })} className={`w-full px-3 py-2 rounded-lg border ${styles.inputClass}`} />
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" id="is_hard_cmhd" checked={crud.form.is_hard} onChange={e => crud.setForm({ ...crud.form, is_hard: e.target.checked })} className="w-5 h-5" />
            <label htmlFor="is_hard_cmhd" className="text-sm">Harte Regel</label>
          </div>
          <div className="md:col-span-4 flex items-end">
            <button type="submit" disabled={crud.submitting} className={styles.submitBtn}>{crud.submitting ? 'Speichert...' : 'Anlegen'}</button>
          </div>
        </div>
      }
      renderRow={(item) => {
        const c = item as ClassMaxHoursDay
        return (
          <tr key={c.id} className={styles.rowClass}>
            <td className="px-4 py-3 font-medium">{cLabel(classes, c.class_id)}</td>
            <td className="px-4 py-3">{c.max_hours}</td>
            <td className="px-4 py-3">{c.is_hard ? '✓' : '—'}</td>
            <td className="px-4 py-3">{c.weight}</td>
            <td className="px-4 py-3 text-right"><button onClick={() => crud.remove(c.id)} className={styles.deleteBtn}>Loeschen</button></td>
          </tr>
        )
      }}
    />
  )
}

// ---------- No Gaps ----------

type GapForm = Omit<ClassNoGaps, 'id' | 'created_by_user_id' | 'created_at'>
const initialGap: GapForm = { class_id: '', is_hard: false, weight: 80, active: true, note: '' }

export function ClassNoGapsEditor() {
  const styles = useShellStyles()
  const classes = useClasses()
  const crud = useConstraintCrud<ClassNoGaps, GapForm>(classNoGapsApi, initialGap)

  return (
    <ConstraintShell
      testId="class-no-gaps-editor"
      title="Klasse: Keine Freistunden"
      description={"Soft-Regel: Klasse soll keine Loecher zwischen Lessons haben."}
      newLabel="+ Neue Regel"
      newDisabled={classes.length === 0}
      prereqWarning={classes.length === 0 ? 'Zuerst Klassen anlegen.' : null}
      emptyText="Keine Regeln vorhanden."
      tableHeaders={['Klasse', 'Hart', 'Weight']}
      state={crud}
      formBody={
        <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
          <div>
            <label className="block text-sm mb-1 opacity-70">Klasse</label>
            <select required value={crud.form.class_id} onChange={e => crud.setForm({ ...crud.form, class_id: e.target.value })} className={`w-full px-3 py-2 rounded-lg border ${styles.inputClass}`}>
              <option value="">— bitte waehlen —</option>
              {classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm mb-1 opacity-70">Weight (0-100)</label>
            <input type="number" min={0} max={100} value={crud.form.weight} onChange={e => crud.setForm({ ...crud.form, weight: parseInt(e.target.value) || 0 })} className={`w-full px-3 py-2 rounded-lg border ${styles.inputClass}`} />
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" id="is_hard_cng" checked={crud.form.is_hard} onChange={e => crud.setForm({ ...crud.form, is_hard: e.target.checked })} className="w-5 h-5" />
            <label htmlFor="is_hard_cng" className="text-sm">Harte Regel</label>
          </div>
          <div className="flex items-end">
            <button type="submit" disabled={crud.submitting} className={styles.submitBtn}>{crud.submitting ? 'Speichert...' : 'Anlegen'}</button>
          </div>
        </div>
      }
      renderRow={(item) => {
        const c = item as ClassNoGaps
        return (
          <tr key={c.id} className={styles.rowClass}>
            <td className="px-4 py-3 font-medium">{cLabel(classes, c.class_id)}</td>
            <td className="px-4 py-3">{c.is_hard ? '✓' : '—'}</td>
            <td className="px-4 py-3">{c.weight}</td>
            <td className="px-4 py-3 text-right"><button onClick={() => crud.remove(c.id)} className={styles.deleteBtn}>Loeschen</button></td>
          </tr>
        )
      }}
    />
  )
}
