import { useEffect, useState, useCallback } from 'react'
import { api } from '../../api/client'
import { useAuth } from '../../context/AuthContext'

interface UserOut {
  id: string
  first_name: string
  last_name: string
  email: string
  role: string
  personnel_number: string | null
}

interface OvertimeBalance {
  total_hours: number
  taken_hours: number
  available_hours: number
}

interface HoursPayoutOut {
  id: string
  hours: number
  period_year: number | null
  period_month: number | null
  note: string | null
  created_by_name: string
  created_at: string
}

interface HoursPayoutListResponse {
  payouts: HoursPayoutOut[]
  total_count: number
}

const MONTH_NAMES = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun',
                     'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']

const ROLE_LABELS: Record<string, string> = {
  SUPER_ADMIN:   'Super Admin',
  COMPANY_ADMIN: 'Administrator',
  HR:            'HR',
  MANAGER:       'Manager',
  EMPLOYEE:      'Mitarbeiter',
}

export function MobileProfileScreen() {
  const { logout } = useAuth()
  const [user, setUser]                   = useState<UserOut | null>(null)
  const [loading, setLoading]             = useState(true)
  const [error, setError]                 = useState<string | null>(null)
  const [overtime, setOvertime]           = useState<OvertimeBalance | null>(null)
  const [payouts, setPayouts]             = useState<HoursPayoutOut[]>([])

  const load = useCallback(async () => {
    setError(null)
    try {
      const me = await api.get<UserOut>('/auth/me')
      setUser(me)
      // Überstunden-Saldo + eigene Auszahlungen parallel laden
      const [bal, payoutData] = await Promise.all([
        api.get<OvertimeBalance>(`/absences/overtime-balance?user_id=${me.id}`).catch(() => null),
        api.get<HoursPayoutListResponse>(`/hr/payouts?user_id=${me.id}`).catch(() => null),
      ])
      if (bal) setOvertime(bal)
      if (payoutData) setPayouts(payoutData.payouts.slice(0, 5)) // letzte 5
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { load() }, [load])

  if (loading) {
    return (
      <div className='flex flex-col items-center justify-center flex-1 py-20 gap-4'>
        <div className='animate-spin rounded-full h-10 w-10 border-4 border-blue-500 border-t-transparent' />
        <p className='text-sm text-gray-400'>Wird geladen…</p>
      </div>
    )
  }

  const initials = user
    ? `${user.first_name[0] ?? ''}${user.last_name[0] ?? ''}`.toUpperCase()
    : '?'

  return (
    <div className='flex flex-col gap-4 px-4 pt-4'>
      {error && (
        <div className='bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-sm text-red-700'>
          {error}
        </div>
      )}

      {user && (
        <>
          {/* Avatar + Name */}
          <div className='bg-white rounded-2xl border border-gray-200 shadow-sm px-5 py-6 flex flex-col items-center gap-3'>
            <div className='w-20 h-20 rounded-full bg-blue-100 flex items-center justify-center'>
              <span className='text-blue-700 font-bold text-3xl'>{initials}</span>
            </div>
            <div className='text-center'>
              <p className='text-xl font-bold text-gray-800'>
                {user.first_name} {user.last_name}
              </p>
              <p className='text-sm text-gray-500 mt-0.5'>{user.email}</p>
              <span className='inline-block mt-2 px-3 py-1 rounded-full bg-blue-100 text-blue-700 text-xs font-semibold'>
                {ROLE_LABELS[user.role] ?? user.role}
              </span>
            </div>
          </div>

          {/* Detail-Felder */}
          <div className='bg-white rounded-2xl border border-gray-200 shadow-sm divide-y divide-gray-100'>
            <div className='flex items-center justify-between px-5 py-4'>
              <span className='text-sm text-gray-500'>E-Mail</span>
              <span className='text-sm font-medium text-gray-800'>{user.email}</span>
            </div>
            <div className='flex items-center justify-between px-5 py-4'>
              <span className='text-sm text-gray-500'>Rolle</span>
              <span className='text-sm font-medium text-gray-800'>{ROLE_LABELS[user.role] ?? user.role}</span>
            </div>
            {user.personnel_number && (
              <div className='flex items-center justify-between px-5 py-4'>
                <span className='text-sm text-gray-500'>Personalnummer</span>
                <span className='text-sm font-mono font-medium text-gray-800'>{user.personnel_number}</span>
              </div>
            )}
          </div>

          {/* Überstunden-Saldo */}
          {overtime !== null && (
            <div className='bg-white rounded-2xl border border-gray-200 shadow-sm px-5 py-4'>
              <p className='text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3'>Überstunden-Konto</p>
              <div className='grid grid-cols-3 gap-2 text-center'>
                <div>
                  <p className='text-lg font-bold text-gray-800'>{overtime.total_hours.toFixed(1)}</p>
                  <p className='text-xs text-gray-400'>Gesamt</p>
                </div>
                <div>
                  <p className='text-lg font-bold text-orange-600'>{overtime.taken_hours.toFixed(1)}</p>
                  <p className='text-xs text-gray-400'>Entnommen</p>
                </div>
                <div>
                  <p className={`text-lg font-bold ${overtime.available_hours >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    {overtime.available_hours.toFixed(1)}
                  </p>
                  <p className='text-xs text-gray-400'>Verfügbar</p>
                </div>
              </div>
            </div>
          )}

          {/* Stunden-Auszahlungen */}
          {payouts.length > 0 && (
            <div className='bg-white rounded-2xl border border-gray-200 shadow-sm px-5 py-4'>
              <p className='text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3'>
                💸 Stunden-Auszahlungen
              </p>
              <div className='divide-y divide-gray-100'>
                {payouts.map(p => (
                  <div key={p.id} className='flex items-center justify-between py-3 first:pt-0 last:pb-0'>
                    <div>
                      <p className='text-sm font-semibold text-purple-700'>{p.hours.toFixed(2)} h</p>
                      <p className='text-xs text-gray-400'>
                        {p.period_year && p.period_month
                          ? `${MONTH_NAMES[p.period_month - 1]} ${p.period_year}`
                          : new Date(p.created_at).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })}
                      </p>
                      {p.note && <p className='text-xs text-gray-500 mt-0.5 truncate max-w-[180px]'>{p.note}</p>}
                    </div>
                    <p className='text-xs text-gray-400 text-right'>{p.created_by_name}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Desktop-Version Link */}
          <a
            href='/dashboard'
            className='bg-white rounded-2xl border border-gray-200 shadow-sm px-5 py-4 flex items-center justify-between min-h-[56px] active:bg-gray-50 transition-colors'
          >
            <span className='text-sm font-medium text-gray-700'>Desktop-Version öffnen</span>
            <svg className='w-5 h-5 text-gray-400' fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={1.75}>
              <path strokeLinecap='round' strokeLinejoin='round' d='M9 5l7 7-7 7' />
            </svg>
          </a>

          {/* Abmelden */}
          <button
            onClick={logout}
            className='min-h-[56px] w-full rounded-2xl border border-red-200 text-red-600 font-semibold text-base active:bg-red-50 transition-colors flex items-center justify-center gap-2'
          >
            <svg className='w-5 h-5' fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={1.75}>
              <path strokeLinecap='round' strokeLinejoin='round' d='M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1' />
            </svg>
            Abmelden
          </button>
        </>
      )}
    </div>
  )
}
