'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
  RenterAuthError,
  loadRenterNotifications,
  markAllRenterNotificationsRead,
  markRenterNotificationRead,
  type RenterNotification,
} from '@/lib/renter'
import { useStorefrontPreferences } from '@/components/StorefrontShell'

export default function RenterNotificationsPage() {
  const router = useRouter()
  const { language } = useStorefrontPreferences()
  const dict = {
    en: {
      load: 'Could not load notifications.',
      updateOne: 'Could not update the notification.',
      updateAll: 'Could not update notifications.',
      renter: 'Renter',
      title: 'Notifications',
      markAll: 'Mark all read',
      back: 'Back to dashboard',
      loading: 'Loading notifications…',
      empty: 'No renter notifications yet.',
      read: 'Read',
      markRead: 'Mark read',
    },
    fr: {
      load: 'Impossible de charger les notifications.',
      updateOne: 'Impossible de mettre à jour la notification.',
      updateAll: 'Impossible de mettre à jour les notifications.',
      renter: 'Client',
      title: 'Notifications',
      markAll: 'Tout marquer comme lu',
      back: 'Retour au tableau de bord',
      loading: 'Chargement des notifications…',
      empty: 'Aucune notification client pour le moment.',
      read: 'Lu',
      markRead: 'Marquer comme lu',
    },
    ar: {
      load: 'تعذر تحميل الإشعارات.',
      updateOne: 'تعذر تحديث الإشعار.',
      updateAll: 'تعذر تحديث الإشعارات.',
      renter: 'المستأجر',
      title: 'الإشعارات',
      markAll: 'تعيين الكل كمقروء',
      back: 'العودة إلى بوابة المستأجر',
      loading: 'جارٍ تحميل الإشعارات…',
      empty: 'لا توجد إشعارات للمستأجر حالياً.',
      read: 'مقروء',
      markRead: 'تعيين كمقروء',
    },
  }[language]
  const [notifications, setNotifications] = useState<RenterNotification[]>([])
  const [errorMsg, setErrorMsg] = useState('')
  const [loading, setLoading] = useState(true)
  const [updating, setUpdating] = useState(false)

  useEffect(() => {
    loadRenterNotifications()
      .then((items) => setNotifications(items))
      .catch((err) => {
        if (err instanceof RenterAuthError) {
          router.replace('/')
          return
        }
        setErrorMsg(err instanceof Error ? err.message : dict.load)
      })
      .finally(() => setLoading(false))
  }, [router])

  async function markRead(id: string) {
    setUpdating(true)
    try {
      await markRenterNotificationRead(id)
      setNotifications((current) =>
        current.map((item) => (item.id === id ? { ...item, readAt: item.readAt ?? new Date().toISOString() } : item)),
      )
    } catch (err) {
      setErrorMsg(err instanceof Error ? err.message : dict.updateOne)
    } finally {
      setUpdating(false)
    }
  }

  async function markAllRead() {
    setUpdating(true)
    try {
      await markAllRenterNotificationsRead()
      setNotifications((current) => current.map((item) => ({ ...item, readAt: item.readAt ?? new Date().toISOString() })))
    } catch (err) {
      setErrorMsg(err instanceof Error ? err.message : dict.updateAll)
    } finally {
      setUpdating(false)
    }
  }

  return (
    <div className="shell space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <h1 className="text-3xl font-black tracking-tight text-blue-900">{dict.title}</h1>
        <button
          type="button"
          onClick={markAllRead}
          disabled={loading || updating}
          className="rounded-full border border-stone-200 bg-white px-5 py-2.5 text-sm font-semibold text-stone-700"
        >
          {dict.markAll}
        </button>
      </div>

      {loading ? <div className="card p-8 text-sm text-stone-500">{dict.loading}</div> : null}
      {!loading && errorMsg ? <div className="card p-8 text-sm text-rose-600">{errorMsg}</div> : null}

      {!loading && !errorMsg && notifications.length === 0 ? (
        <div className="card p-10 text-center text-sm text-stone-500">{dict.empty}</div>
      ) : null}

      {!loading && !errorMsg && notifications.length > 0 ? (
        <div className="space-y-4">
          {notifications.map((notification) => (
            <article key={notification.id} className="card p-6">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.16em] text-orange-700">{notification.type.replaceAll('_', ' ')}</p>
                  <h2 className="mt-2 text-lg font-bold text-blue-900">{notification.title}</h2>
                </div>
                {notification.readAt ? (
                  <span className="rounded-full bg-stone-100 px-3 py-1 text-xs font-semibold text-stone-600">{dict.read}</span>
                ) : (
                  <button
                    type="button"
                    onClick={() => markRead(notification.id)}
                    disabled={updating}
                    className="rounded-full bg-orange-100 px-3 py-1 text-xs font-semibold text-orange-800"
                  >
                    {dict.markRead}
                  </button>
                )}
              </div>
              <p className="mt-3 text-sm leading-7 text-stone-600">{notification.body}</p>
              <p className="mt-4 text-xs text-stone-400">{new Date(notification.createdAt).toLocaleString()}</p>
            </article>
          ))}
        </div>
      ) : null}
    </div>
  )
}
