import { useEffect, useState, useRef, useCallback } from 'react'
import { api } from '../../api/client'

interface TodayStatus {
  today_open: boolean
  today_start: string | null
  today_hours_so_far: number | null
  break_start?: string | null
  break_minutes?: number
}

interface CompanySettings {
  mobile_stamping_enabled: boolean
}

interface TimeEntryWithWarnings {
  entry: { id: string }
  warnings: string[]
}

interface BalanceResponse {
  overtime_hours: number
  total_hours_worked: number
  expected_hours: number
  period_start: string
  period_end: string
}

function getMondayOfCurrentWeek(): string {
  const now = new Date()
  const day = now.getDay()
  const diff = day === 0 ? -6 : 1 - day
  const monday = new Date(now)
  monday.setDate(now.getDate() + diff)
  return monday.toISOString().slice(0, 10)
}

function fmtHMS(seconds: number): string {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}

function fmtMS(seconds: number): string {
  const m = Math.floor(seconds / 60)
  const s = seconds % 60
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}

function fmtH(h: number | null): string {
  if (h === null || h === undefined) return '–'
  const sign = h < 0 ? '-' : h > 0 ? '+' : ''
  const abs = Math.abs(h)
  const hrs = Math.floor(abs)
  const min = Math.round((abs - hrs) * 60)
  return `${sign}${hrs}h ${min}m`
}

function fmtTime(iso: string | null): string {
  if (!iso) return '–'
  if (/^\d{2}:\d{2}(:\d{2})?$/.test(iso)) return iso.slice(0, 5)
  const d = new Date(iso)
  if (isNaN(d.getTime())) return iso.slice(0, 5)
  return d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })
}

export function MobileStampScreen() {
  const [dashboard, setDashboard] = useState<TodayStatus | null>(null)
  const [balance, setBalance] = useState<BalanceResponse | null>(null)
  const [stampingAllowed, setStampingAllowed] = useState(true)
  const [loading, setLoading] = useState(true)
  const [stamping, setStamping] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [warnings, setWarnings] = useState<string[]>([])

  const [liveSeconds, setLiveSeconds] = useState(0)
  const [breakSeconds, setBreakSeconds] = useState(0)
  const tickerRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const breakTickerRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const load = useCallback(async () => {
    setError(null)
    try {
      const monday = getMondayOfCurrentWeek()
      const [dash, bal, company] = await Promise.all([
        api.get<TodayStatus>('/dashboard/me'),
        api.get<BalanceResponse>(`/time/balance/me?period_start=${monday}`),
        api.get<CompanySettings>('/companies/me'),
      ])
      setDashboard(dash)
      setBalance(bal)
      setStampingAllowed(company.mobile_stamping_enabled ?? true)
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Laden')
    } finally {
      setLoading(false)
    }
  }, [])

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

  // Live-Ticker: läuft nur wenn eingestempelt und keine Pause
  useEffect(() => {
    if (tickerRef.current) clearInterval(tickerRef.current)
    if (dashboard?.today_open && dashboard.today_start && !dashboard.break_start) {
      const startStr = dashboard.today_start
      const today = new Date()
      const [h, m, s] = startStr.split(':').map(Number)
      const startMs = new Date(today.getFullYear(), today.getMonth(), today.getDate(), h, m, s || 0).getTime()
      const pausedMs = (dashboard.break_minutes ?? 0) * 60 * 1000
      const update = () => setLiveSeconds(Math.max(0, Math.floor((Date.now() - startMs - pausedMs) / 1000)))
      update()
      tickerRef.current = setInterval(update, 1000)
    } else {
      setLiveSeconds(0)
    }
    return () => { if (tickerRef.current) clearInterval(tickerRef.current) }
  }, [dashboard?.today_open, dashboard?.today_start, dashboard?.break_start, dashboard?.break_minutes])

  // Pausen-Ticker
  useEffect(() => {
    if (breakTickerRef.current) clearInterval(breakTickerRef.current)
    if (dashboard?.today_open && dashboard.break_start) {
      const breakStartMs = new Date(dashboard.break_start).getTime()
      const update = () => setBreakSeconds(Math.max(0, Math.floor((Date.now() - breakStartMs) / 1000)))
      update()
      breakTickerRef.current = setInterval(update, 1000)
    } else {
      setBreakSeconds(0)
    }
    return () => { if (breakTickerRef.current) clearInterval(breakTickerRef.current) }
  }, [dashboard?.today_open, dashboard?.break_start])

  const stampIn = async () => {
    setStamping(true); setError(null); setWarnings([])
    try {
      const res = await api.post<TimeEntryWithWarnings>('/time/stamp-in', {})
      if (res.warnings.length) setWarnings(res.warnings)
      await load()
    } catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setStamping(false) }
  }

  const stampOut = async () => {
    setStamping(true); setError(null); setWarnings([])
    try {
      const res = await api.post<TimeEntryWithWarnings>('/time/stamp-out', {})
      if (res.warnings.length) setWarnings(res.warnings)
      await load()
    } catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setStamping(false) }
  }

  const breakStart = async () => {
    setStamping(true); setError(null)
    try { await api.post('/time/break-start', {}); await load() }
    catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setStamping(false) }
  }

  const breakEnd = async () => {
    setStamping(true); setError(null)
    try { await api.post('/time/break-end', {}); await load() }
    catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setStamping(false) }
  }

  const isOpen = dashboard?.today_open ?? false
  const isOnBreak = isOpen && !!dashboard?.break_start

  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>
    )
  }

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

      {/* Warnungen */}
      {warnings.length > 0 && (
        <div className='bg-yellow-50 border border-yellow-200 rounded-xl px-4 py-3'>
          <p className='text-sm font-semibold text-yellow-800 mb-1'>Hinweise</p>
          <ul className='text-sm text-yellow-700 list-disc list-inside space-y-0.5'>
            {warnings.map((w, i) => <li key={i}>{w}</li>)}
          </ul>
        </div>
      )}

      {/* Stempeln deaktiviert */}
      {!stampingAllowed && (
        <div className='bg-amber-50 border border-amber-200 rounded-xl px-4 py-4 flex gap-3 items-start'>
          <span className='text-xl mt-0.5'>🔒</span>
          <div>
            <p className='text-sm font-semibold text-amber-800'>Einstempeln nicht verfügbar</p>
            <p className='text-xs text-amber-700 mt-0.5'>
              Dein Unternehmen hat die Zeiterfassung über die mobile Ansicht deaktiviert.
              Bitte nutze das Kiosk-Terminal oder die Desktop-Version.
            </p>
          </div>
        </div>
      )}

      {/* Status-Karte */}
      <div className='bg-white rounded-2xl border border-gray-200 shadow-sm px-5 py-5 flex flex-col items-center gap-3'>
        {/* Status-Label */}
        <div className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-semibold ${
          isOnBreak
            ? 'bg-yellow-100 text-yellow-700'
            : isOpen
            ? 'bg-green-100 text-green-700'
            : 'bg-gray-100 text-gray-500'
        }`}>
          <span className={`w-2 h-2 rounded-full ${isOnBreak ? 'bg-yellow-400' : isOpen ? 'bg-green-500' : 'bg-gray-400'}`} />
          {isOnBreak
            ? `In Pause seit ${fmtTime(dashboard?.break_start ?? null)}`
            : isOpen
            ? `Eingestempelt seit ${fmtTime(dashboard?.today_start ?? null)}`
            : 'Nicht eingestempelt'
          }
        </div>

        {/* Live-Uhr */}
        {isOpen && (
          <div className='text-center py-2'>
            {isOnBreak ? (
              <>
                <p className='text-xs font-medium text-yellow-500 uppercase tracking-widest mb-1'>Pause</p>
                <p className='text-5xl font-mono font-bold text-yellow-500 tabular-nums'>{fmtMS(breakSeconds)}</p>
                <p className='text-xs text-gray-400 mt-2'>
                  Pause gesamt: {(dashboard?.break_minutes ?? 0) + Math.floor(breakSeconds / 60)} min
                </p>
              </>
            ) : (
              <>
                <p className='text-xs font-medium text-green-600 uppercase tracking-widest mb-1'>Arbeitszeit</p>
                <p className='text-5xl font-mono font-bold text-gray-800 tabular-nums'>{fmtHMS(liveSeconds)}</p>
                {(dashboard?.break_minutes ?? 0) > 0 && (
                  <p className='text-xs text-gray-400 mt-2'>Pause: {dashboard!.break_minutes} min</p>
                )}
              </>
            )}
          </div>
        )}

        {/* Haupt-Button – nur wenn Stempeln erlaubt */}
        {stampingAllowed && !isOpen ? (
          <button
            onClick={stampIn}
            disabled={stamping}
            className='w-4/5 min-h-[80px] rounded-3xl bg-green-500 active:bg-green-700 text-white text-2xl font-bold shadow-md transition-all disabled:opacity-50 flex items-center justify-center'
          >
            {stamping ? (
              <span className='animate-spin rounded-full h-7 w-7 border-4 border-white border-t-transparent' />
            ) : 'EINSTEMPELN'}
          </button>
        ) : stampingAllowed && isOnBreak ? (
          <button
            onClick={breakEnd}
            disabled={stamping}
            className='w-4/5 min-h-[80px] rounded-3xl bg-yellow-400 active:bg-yellow-600 text-white text-2xl font-bold shadow-md transition-all disabled:opacity-50 flex items-center justify-center'
          >
            {stamping ? (
              <span className='animate-spin rounded-full h-7 w-7 border-4 border-white border-t-transparent' />
            ) : 'PAUSE BEENDEN'}
          </button>
        ) : stampingAllowed ? (
          <button
            onClick={stampOut}
            disabled={stamping}
            className='w-4/5 min-h-[80px] rounded-3xl bg-red-500 active:bg-red-700 text-white text-2xl font-bold shadow-md transition-all disabled:opacity-50 flex items-center justify-center'
          >
            {stamping ? (
              <span className='animate-spin rounded-full h-7 w-7 border-4 border-white border-t-transparent' />
            ) : 'AUSSTEMPELN'}
          </button>
        ) : null}

        {/* Sekundärer Button: Pause starten */}
        {stampingAllowed && isOpen && !isOnBreak && (
          <button
            onClick={breakStart}
            disabled={stamping}
            className='min-h-[48px] px-6 rounded-xl border border-yellow-300 text-yellow-600 font-semibold text-base active:bg-yellow-50 transition-colors disabled:opacity-50 flex items-center gap-2'
          >
            <span>☕</span>
            Pause starten
          </button>
        )}
      </div>

      {/* Wochen-Statistik */}
      {balance && (
        <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-widest mb-3'>
            Aktuelle Woche
          </p>
          <div className='grid grid-cols-3 gap-2'>
            <div className='flex flex-col items-center gap-1'>
              <p className='text-xs text-gray-400'>Gearbeitet</p>
              <p className='text-xl font-bold text-gray-800'>{fmtH(balance.total_hours_worked).replace('+', '')}</p>
            </div>
            <div className='flex flex-col items-center gap-1 border-x border-gray-100'>
              <p className='text-xs text-gray-400'>Erwartet</p>
              <p className='text-xl font-bold text-gray-800'>{fmtH(balance.expected_hours).replace('+', '')}</p>
            </div>
            <div className='flex flex-col items-center gap-1'>
              <p className='text-xs text-gray-400'>Überstunden</p>
              <p className={`text-xl font-bold ${
                balance.overtime_hours > 0 ? 'text-green-600' :
                balance.overtime_hours < 0 ? 'text-red-500' : 'text-gray-800'
              }`}>
                {fmtH(balance.overtime_hours)}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
