'use client'

import { useParams } from 'next/navigation'
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle
} from '@/shared/components/ui/card'
import { Skeleton } from '@/shared/components/ui/skeleton'
import { buttonVariants } from '@/shared/components/ui/variants/button'
import { Undo2Icon } from 'lucide-react'
import { ProgressBarLink } from '@/shared/components'
import { getRelativeTimeString } from '@/shared/lib/datetime'
import { useGetNotificationById } from '../hooks/use-get-notification-by-id'
import { useEffect, useTransition, type ReactNode } from 'react'
import { useReadNotification } from '../hooks/use-read-notification'
import type { NotificationType } from '../types/notification'

const NOTIFICATION_TYPE_LABELS: Record<NotificationType, string> = {
  SITE_NEW_ORDER: 'Новый заказ на сайте',
  SYSTEM: 'Системное',
  SITE_NEW_FORM: 'Новая форма на сайте',
  SITE_CUSTOM: 'Пользовательское',
  UNKNOWN: 'Неизвестно'
}

// Long words from sites (emails, links, order numbers) wrap instead of being cut off
const Field = ({ label, children }: { label: string; children: ReactNode }) => (
  <div className='min-w-0'>
    <dt className='text-sm text-muted-foreground'>{label}</dt>
    <dd className='mt-1 text-base font-medium [overflow-wrap:anywhere]'>
      {children}
    </dd>
  </div>
)

export const NotificationCard = () => {
  const { id } = useParams<{ id: string }>()
  const { mutateAsync } = useReadNotification()
  const [isPendingA, startTransition] = useTransition()
  const {
    data: notification,
    isPending,
    isSuccess
  } = useGetNotificationById(id)

  useEffect(() => {
    startTransition(async () => {
      await mutateAsync(id)
    })
  }, [id, mutateAsync])

  if (isPending || isPendingA) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className='h-4 w-2/3' />
          <Skeleton className='h-4 w-1/2' />
        </CardHeader>
        <CardContent>
          <Skeleton className='aspect-square w-full' />
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      {isSuccess && (
        <>
          <CardHeader>
            <CardTitle>Уведомление #{notification.id.split('-')[0]}</CardTitle>
            <CardDescription>
              Получено {getRelativeTimeString(new Date(notification.createdAt))}{' '}
              (
              {new Intl.DateTimeFormat('ru-RU', {
                dateStyle: 'medium',
                timeStyle: 'medium'
              }).format(new Date(notification.createdAt))}
              )
            </CardDescription>
          </CardHeader>
          <CardContent>
            <dl className='grid gap-5'>
              <Field label='Заголовок'>{notification.title}</Field>
              <Field label='Тело'>{notification.body}</Field>
              {notification.description && (
                <Field label='Описание'>
                  {/* HTML comes from the site: keep it inside the card on narrow screens */}
                  <div
                    className='prose prose-sm sm:prose-base dark:prose-invert max-w-none font-normal [&_img]:h-auto [&_img]:max-w-full [&_table]:block [&_table]:overflow-x-auto'
                    dangerouslySetInnerHTML={{ __html: notification.description }}
                  />
                </Field>
              )}
              <Field label='Тип'>
                {NOTIFICATION_TYPE_LABELS[notification.type] ??
                  NOTIFICATION_TYPE_LABELS.UNKNOWN}
              </Field>
              <Field label='Связанный сайт'>
                {notification.siteId ? (
                  <ProgressBarLink
                    href={`/app/sites/${notification.siteId}`}
                    className='text-primary underline underline-offset-4'
                  >
                    Открыть
                  </ProgressBarLink>
                ) : (
                  '—'
                )}
              </Field>
            </dl>
          </CardContent>
          <CardFooter>
            <ProgressBarLink
              href='/app/notifications'
              className={buttonVariants({ variant: 'outline' })}
            >
              <Undo2Icon />
              Вернуться к списку
            </ProgressBarLink>
          </CardFooter>
        </>
      )}
    </Card>
  )
}
