import type {
  AbsenceTypeOut,
  AbsenceOut,
  UserListItem,
  VacationBalanceOut,
  OvertimeBalanceOut,
} from '../../types/absence'

// ── BalanceEditModal ──────────────────────────────────────────────────────────

interface BalanceEditModalProps {
  year: number
  balance: VacationBalanceOut
  balanceForm: { entitled_days: number; special_days: number; carried_over: number }
  setBalanceForm: React.Dispatch<React.SetStateAction<{ entitled_days: number; special_days: number; carried_over: number }>>
  balanceSaving: boolean
  onSave: () => Promise<void>
  onClose: () => void
}

export function BalanceEditModal({
  year,
  balanceForm,
  setBalanceForm,
  balanceSaving,
  onSave,
  onClose,
}: BalanceEditModalProps) {
  return (
    <div className='fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4'>
      <div className='bg-white rounded-xl shadow-xl w-full max-w-sm p-6 space-y-4'>
        <h2 className='text-lg font-semibold text-gray-800'>Urlaubskonto {year} bearbeiten</h2>
        <div className='space-y-3'>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>Grundurlaub (Tage)</span>
            <input
              type='number' min={0} max={365} value={balanceForm.entitled_days}
              onChange={e => setBalanceForm(f => ({ ...f, entitled_days: Number(e.target.value) }))}
              className='mt-1 w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
            />
          </label>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>Sondertage (Tage)</span>
            <p className='text-xs text-gray-400 mb-1'>z.B. Betriebsurlaub, Jubiläum, individuelle Zusatztage</p>
            <input
              type='number' min={0} max={365} value={balanceForm.special_days}
              onChange={e => setBalanceForm(f => ({ ...f, special_days: Number(e.target.value) }))}
              className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
            />
          </label>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>Resturlaub aus {year - 1} (Tage)</span>
            <p className='text-xs text-gray-400 mb-1'>Wird automatisch aus dem Vorjahr berechnet</p>
            <input
              type='number' min={0} max={365} value={balanceForm.carried_over}
              onChange={e => setBalanceForm(f => ({ ...f, carried_over: Number(e.target.value) }))}
              className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
            />
          </label>
          <div className='bg-blue-50 rounded-lg p-3 text-sm text-blue-700'>
            Gesamt: <strong>{balanceForm.entitled_days + balanceForm.special_days + balanceForm.carried_over} Tage</strong>
          </div>
        </div>
        <div className='flex gap-2 pt-1'>
          <button
            disabled={balanceSaving}
            onClick={onSave}
            className='flex-1 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50'
          >
            {balanceSaving ? 'Speichern…' : 'Speichern'}
          </button>
          <button
            onClick={onClose}
            className='px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50'
          >
            Abbrechen
          </button>
        </div>
      </div>
    </div>
  )
}

// ── EditAbsenceModal ──────────────────────────────────────────────────────────

interface EditAbsenceModalProps {
  editAbsence: AbsenceOut
  editForm: {
    type_id: string
    start_date: string
    end_date: string
    half_day_start: boolean
    half_day_end: boolean
    note: string
    correction_note: string
  }
  setEditForm: React.Dispatch<React.SetStateAction<{
    type_id: string
    start_date: string
    end_date: string
    half_day_start: boolean
    half_day_end: boolean
    note: string
    correction_note: string
  }>>
  types: AbsenceTypeOut[]
  isManager: boolean
  submitting: boolean
  error: string
  onSave: () => void
  onClose: () => void
}

export function EditAbsenceModal({
  editAbsence,
  editForm,
  setEditForm,
  types,
  isManager,
  submitting,
  error,
  onSave,
  onClose,
}: EditAbsenceModalProps) {
  return (
    <div className='fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50'>
      <div className='bg-white rounded-xl shadow-xl w-full max-w-md'>
        <div className='px-6 py-4 border-b border-gray-200'>
          <h2 className='text-lg font-semibold text-gray-800'>Antrag bearbeiten</h2>
        </div>
        <div className='px-6 py-4 space-y-4'>
          {error && <p className='text-sm text-red-600'>{error}</p>}
          {editAbsence.status === 'approved' && !isManager && (
            <div className='bg-orange-50 border border-orange-200 rounded-lg p-3 text-sm text-orange-700'>
              Der Antrag wurde bereits genehmigt. Nach der Änderung wird er zur erneuten Genehmigung eingereicht.
            </div>
          )}
          <div>
            <label className='block text-sm font-medium text-gray-700 mb-1'>Abwesenheitsart *</label>
            <select
              value={editForm.type_id}
              onChange={e => setEditForm(f => ({ ...f, type_id: e.target.value }))}
              className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
            >
              <option value=''>Bitte wählen…</option>
              {types.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
          </div>
          <div className='grid grid-cols-2 gap-3'>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Von *</label>
              <input
                type='date' value={editForm.start_date}
                onChange={e => setEditForm(f => ({ ...f, start_date: e.target.value }))}
                className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
              />
            </div>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Bis *</label>
              <input
                type='date' value={editForm.end_date} min={editForm.start_date}
                onChange={e => setEditForm(f => ({ ...f, end_date: e.target.value }))}
                className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'
              />
            </div>
          </div>
          <div className='flex gap-4'>
            <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
              <input
                type='checkbox' checked={editForm.half_day_start}
                onChange={e => setEditForm(f => ({ ...f, half_day_start: e.target.checked }))}
                className='rounded'
              />
              Erster Tag halbtags
            </label>
            <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
              <input
                type='checkbox' checked={editForm.half_day_end}
                onChange={e => setEditForm(f => ({ ...f, half_day_end: e.target.checked }))}
                className='rounded'
              />
              Letzter Tag halbtags
            </label>
          </div>
          <div>
            <label className='block text-sm font-medium text-gray-700 mb-1'>Notiz</label>
            <textarea
              value={editForm.note}
              onChange={e => setEditForm(f => ({ ...f, note: e.target.value }))}
              rows={2}
              className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none'
            />
          </div>
          {editAbsence.status === 'approved' && !isManager && (
            <div>
              <label className='block text-sm font-medium text-red-600 mb-1'>Änderungsgrund *</label>
              <input
                type='text' value={editForm.correction_note}
                onChange={e => setEditForm(f => ({ ...f, correction_note: e.target.value }))}
                placeholder='z. B. Urlaub wurde verkürzt'
                className='w-full border border-red-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400'
              />
              <p className='text-xs text-gray-400 mt-1'>Wird im Änderungsprotokoll gespeichert.</p>
            </div>
          )}
        </div>
        <div className='px-6 py-4 border-t border-gray-200 flex justify-end gap-2'>
          <button
            onClick={onClose}
            className='px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50'
          >
            Abbrechen
          </button>
          <button
            onClick={onSave}
            disabled={submitting}
            className='px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50'
          >
            {submitting
              ? 'Wird gespeichert…'
              : (editAbsence.status === 'approved' && !isManager ? 'Änderung einreichen' : 'Speichern')
            }
          </button>
        </div>
      </div>
    </div>
  )
}

// ── CreateAbsenceModal ────────────────────────────────────────────────────────

interface CreateAbsenceModalProps {
  form: {
    type_id: string
    start_date: string
    end_date: string
    half_day_start: boolean
    half_day_end: boolean
    note: string
    for_user_id: string
    substitute_id: string
  }
  setForm: React.Dispatch<React.SetStateAction<{
    type_id: string
    start_date: string
    end_date: string
    half_day_start: boolean
    half_day_end: boolean
    note: string
    for_user_id: string
    substitute_id: string
  }>>
  types: AbsenceTypeOut[]
  colleagues: UserListItem[]
  isManager: boolean
  submitting: boolean
  error: string
  overtimeBalance: OvertimeBalanceOut | null
  fzaMode: 'days' | 'hours'
  setFzaMode: React.Dispatch<React.SetStateAction<'days' | 'hours'>>
  fzaHours: number
  setFzaHours: React.Dispatch<React.SetStateAction<number>>
  isFzaType: (typeId: string) => boolean
  onCreate: () => void
  onClose: () => void
}

export function CreateAbsenceModal({
  form,
  setForm,
  types,
  colleagues,
  isManager,
  submitting,
  error,
  overtimeBalance,
  fzaMode,
  setFzaMode,
  fzaHours,
  setFzaHours,
  isFzaType,
  onCreate,
  onClose,
}: CreateAbsenceModalProps) {
  const showFzaToggle = form.type_id ? isFzaType(form.type_id) : false
  const inputClass = 'w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'

  return (
    <div className='fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50'>
      <div className='bg-white rounded-xl shadow-xl w-full max-w-md'>
        <div className='px-6 py-4 border-b border-gray-200'>
          <h2 className='text-lg font-semibold text-gray-800'>Abwesenheitsantrag</h2>
        </div>
        <div className='px-6 py-4 space-y-4'>
          {error && <p className='text-sm text-red-600'>{error}</p>}
          {isManager && (
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Mitarbeiter</label>
              <select
                value={form.for_user_id}
                onChange={e => setForm(f => ({ ...f, for_user_id: e.target.value }))}
                className={inputClass}
              >
                <option value=''>— Für mich selbst —</option>
                {colleagues.map(c => <option key={c.id} value={c.id}>{c.full_name}{c.email ? ` (${c.email})` : ''}</option>)}
              </select>
            </div>
          )}
          <div>
            <label className='block text-sm font-medium text-gray-700 mb-1'>Vertretung <span className='text-gray-400 font-normal'>(optional)</span></label>
            <select
              value={form.substitute_id}
              onChange={e => setForm(f => ({ ...f, substitute_id: e.target.value }))}
              className={inputClass}
            >
              <option value=''>— Keine —</option>
              {colleagues.filter(c => c.id !== form.for_user_id).map(c => (
                <option key={c.id} value={c.id}>{c.full_name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className='block text-sm font-medium text-gray-700 mb-1'>Abwesenheitsart *</label>
            <select
              value={form.type_id}
              onChange={e => setForm(f => ({ ...f, type_id: e.target.value }))}
              className={inputClass}
            >
              <option value=''>Bitte wählen…</option>
              {types.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
            {form.type_id && types.find(t => t.id === form.type_id)?.affects_overtime_balance && overtimeBalance !== null && (
              <p className='text-xs mt-1 text-purple-600'>
                Überstunden-Konto: <strong>{overtimeBalance.available_hours.toFixed(1)} h verfügbar</strong> (≈ {(overtimeBalance.available_hours / 8).toFixed(1)} Tage)
              </p>
            )}
          </div>

          {showFzaToggle && (
            <div className='flex rounded-lg border border-gray-200 overflow-hidden'>
              <button
                type='button'
                onClick={() => setFzaMode('days')}
                className={`flex-1 py-2 text-sm font-medium transition-colors ${fzaMode === 'days' ? 'bg-blue-600 text-white' : 'text-gray-600 hover:bg-gray-50'}`}
              >
                Tage
              </button>
              <button
                type='button'
                onClick={() => setFzaMode('hours')}
                className={`flex-1 py-2 text-sm font-medium transition-colors ${fzaMode === 'hours' ? 'bg-blue-600 text-white' : 'text-gray-600 hover:bg-gray-50'}`}
              >
                Stunden
              </button>
            </div>
          )}

          {showFzaToggle && fzaMode === 'hours' ? (
            <>
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-1'>Datum *</label>
                <input
                  type='date'
                  value={form.start_date}
                  onChange={e => setForm(f => ({ ...f, start_date: e.target.value, end_date: e.target.value }))}
                  className={inputClass}
                />
              </div>
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-1'>Stunden *</label>
                <input
                  type='number'
                  min={0.25}
                  max={24}
                  step={0.25}
                  value={fzaHours}
                  onChange={e => setFzaHours(Math.max(0.25, Math.min(24, parseFloat(e.target.value) || 0.25)))}
                  className={inputClass}
                />
                <p className='text-xs text-gray-400 mt-1'>{fzaHours} h FZA – entsprechende Überstunden werden verrechnet</p>
              </div>
            </>
          ) : (
            <>
              <div className='grid grid-cols-2 gap-3'>
                <div>
                  <label className='block text-sm font-medium text-gray-700 mb-1'>Von *</label>
                  <input
                    type='date' value={form.start_date}
                    onChange={e => setForm(f => ({ ...f, start_date: e.target.value }))}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className='block text-sm font-medium text-gray-700 mb-1'>Bis *</label>
                  <input
                    type='date' value={form.end_date} min={form.start_date}
                    onChange={e => setForm(f => ({ ...f, end_date: e.target.value }))}
                    className={inputClass}
                  />
                </div>
              </div>
              <div className='flex gap-4'>
                <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
                  <input
                    type='checkbox' checked={form.half_day_start}
                    onChange={e => setForm(f => ({ ...f, half_day_start: e.target.checked }))}
                    className='rounded'
                  />
                  Erster Tag halbtags
                </label>
                <label className='flex items-center gap-2 text-sm text-gray-700 cursor-pointer'>
                  <input
                    type='checkbox' checked={form.half_day_end}
                    onChange={e => setForm(f => ({ ...f, half_day_end: e.target.checked }))}
                    className='rounded'
                  />
                  Letzter Tag halbtags
                </label>
              </div>
            </>
          )}

          <div>
            <label className='block text-sm font-medium text-gray-700 mb-1'>Notiz</label>
            <textarea
              value={form.note}
              onChange={e => setForm(f => ({ ...f, note: e.target.value }))}
              rows={2}
              className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none'
            />
          </div>
        </div>
        <div className='px-6 py-4 border-t border-gray-200 flex justify-end gap-2'>
          <button onClick={onClose} className='px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50'>
            Abbrechen
          </button>
          <button
            onClick={onCreate}
            disabled={submitting}
            className='px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50'
          >
            {submitting ? 'Wird gesendet…' : 'Antrag stellen'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── QuickSickModal ────────────────────────────────────────────────────────────

interface QuickSickModalProps {
  form: { start_date: string; end_date: string }
  setForm: React.Dispatch<React.SetStateAction<{ start_date: string; end_date: string }>>
  submitting: boolean
  error: string
  onSubmit: () => void
  onClose: () => void
}

export function QuickSickModal({ form, setForm, submitting, error, onSubmit, onClose }: QuickSickModalProps) {
  return (
    <div className='fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50'>
      <div className='bg-white rounded-xl shadow-xl w-full max-w-sm'>
        <div className='px-6 py-4 border-b border-gray-200 flex items-center gap-2'>
          <span className='text-2xl'>🤒</span>
          <div>
            <h2 className='text-lg font-semibold text-gray-800'>Krank melden</h2>
            <p className='text-xs text-gray-500'>Wird sofort genehmigt — Attest-Frist wird automatisch berechnet.</p>
          </div>
        </div>
        <div className='px-6 py-4 space-y-4'>
          {error && <p className='text-sm text-red-600'>{error}</p>}
          <div className='grid grid-cols-2 gap-3'>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Von *</label>
              <input
                type='date' value={form.start_date}
                onChange={e => setForm(f => ({ ...f, start_date: e.target.value }))}
                className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500'
              />
            </div>
            <div>
              <label className='block text-sm font-medium text-gray-700 mb-1'>Bis *</label>
              <input
                type='date' value={form.end_date} min={form.start_date}
                onChange={e => setForm(f => ({ ...f, end_date: e.target.value }))}
                className='w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500'
              />
            </div>
          </div>
        </div>
        <div className='px-6 py-4 border-t border-gray-200 flex justify-end gap-2'>
          <button onClick={onClose} className='px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50'>
            Abbrechen
          </button>
          <button
            onClick={onSubmit}
            disabled={submitting || !form.start_date || !form.end_date}
            className='px-4 py-2 bg-orange-600 text-white rounded-lg text-sm font-medium hover:bg-orange-700 disabled:opacity-50'
          >
            {submitting ? 'Wird gesendet…' : 'Krank melden'}
          </button>
        </div>
      </div>
    </div>
  )
}
