/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  defaultElementRenderers,
  PayloadLexicalReactRenderer,
} from '@atelier-disko/payload-lexical-react-renderer'
import { UploadNode } from '@payloadcms/richtext-lexical/client'
import React from 'react'
import { cn } from './cn'

export interface ReachTextType {
  root: {
    type: string
    children: {
      type: string
      version: number
      [k: string]: unknown
    }[]
    direction: ('ltr' | 'rtl') | null
    format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | ''
    indent: number
    version: number
  }
  [k: string]: unknown
}

interface Props {
  title: ReachTextType | string
  excludeImages?: boolean
  closeLineWrap?: boolean
  imageClassname?: string
  log?: boolean
  colorType?: 'primary' | 'secondary'
  isSmoothText?: string | null
  boldClass?: string
}

export const MarkComponent: React.FC<Props> = ({
  title,
  closeLineWrap = false,
  imageClassname = '',
  log = false,
  colorType,
  isSmoothText = null,
  boldClass,
}) => {
  if (!title) {
    return <></>
  }

  return (
    <>
      {typeof title === 'string' ? (
        title
      ) : (
        <PayloadLexicalReactRenderer<typeof title>
          content={title as any}
          elementRenderers={{
            ...defaultElementRenderers,
            upload: (props: { node: UploadNode } | any) => {
              const { node } = props
              if (props.value) {
                if (props.value.mimeType?.startsWith('image/')) {
                  return (
                    <div className="inline-flex items-center">
                      <img
                        src={props.value.url || props.value.sizes?.thumbnail?.url || ''}
                        alt={props.value.alt || ''}
                        className={imageClassname}
                      />
                      {props.value.caption && (
                        <p className="mt-2 text-sm text-gray-500 text-center">
                          {props.value.caption}
                        </p>
                      )}
                    </div>
                  )
                }
              }

              // Проверяем, что это изображение
              if (node.mimeType?.startsWith('image/')) {
                return (
                  <div className="inline-flex items-center">
                    <img
                      src={node.fields?.url || node.fields?.sizes?.thumbnail?.url || ''}
                      alt={node.fields?.alt || ''}
                      className="max-w-full h-auto rounded-lg"
                      style={{
                        width: node.fields?.width || '100%',
                        height: node.fields?.height || 'auto',
                      }}
                    />
                    {node.fields?.caption && (
                      <p className="mt-2 text-sm text-gray-500 text-center">
                        {node.fields?.caption}
                      </p>
                    )}
                  </div>
                )
              }

              // Для других типов файлов (если нужно)
              return null
            },
            link: (props) => {
              const { fields, children } = props
              // @ts-ignore
              const href = fields?.url || fields?.doc?.value?.slug || '#'
              const rel = fields?.newTab ? 'noopener noreferrer' : undefined
              const target = fields?.newTab ? '_blank' : undefined
              return (
                <a
                  href={href}
                  target={target}
                  rel={rel}
                  className="text-blue-600 hover:text-blue-800 hover:underline"
                >
                  {children}
                </a>
              )
            },
            paragraph: (props) => {
              const children = Array.isArray(props.children)
                ? props.children.join('')
                : props.children

              if (typeof children === 'string' && children.trim() === '') {
                if (closeLineWrap) {
                  return
                }
                return (
                  <>
                    <br />
                  </>
                )
              }

              return (
                <>
                  <span className="b1-reg text-basic-gray-txt">{props.children}</span>{' '}
                  {closeLineWrap ? null : <br />}
                </>
              )
            },
            list: (props) => {
              if (props.listType === 'bullet')
                return (
                  <ul
                    style={{
                      paddingLeft: '20px',
                    }}
                    className="blog-ul b1-reg ulll pl-[20px] list-outside text-lg text-gray-700 !list-disc"
                  >
                    {props.children}
                  </ul>
                )
              if (props.listType === 'number')
                return (
                  <ol
                    style={{
                      paddingLeft: '20px',
                    }}
                    className="b1-reg olll flex flex-col gap-y-[20px] list-decimal list-outside text-lg text-gray-700"
                  >
                    {props.children}
                  </ol>
                )
            },

            heading: (props) => {
              switch (props.tag) {
                case 'h1':
                  return <h1 className="h1">{props.children}</h1>
                case 'h2':
                  return <h2 className="h2">{props.children}</h2>
                case 'h3':
                  return <h3 className="h3 !text-basic-black">{props.children}</h3>
                case 'h4':
                  return <h4 className="h4">{props.children}</h4>
                case 'h5':
                  return <h5 className="h5">{props.children}</h5>
                case 'h6':
                  return <h6 className="h6">{props.children}</h6>
                default:
                  return <p>{props.children}</p>
              }
            },
          }}
          renderMark={(mark) => {
            if (isSmoothText) {
              return (
                <>
                  {mark.text.split('').map((char: string, i: number) => {
                    return (
                      <span
                        className={cn(isSmoothText, 'transition-all duration-300', {
                          'bold-text': mark.bold,
                        })}
                        key={i}
                      >
                        {char}
                      </span>
                    )
                  })}
                </>
              )
            }

            if (mark.bold) {
              if (colorType === 'primary') {
                return <span className={cn('font-semibold text-basic-white', boldClass)}>{mark.text}</span>
              }

              return <span className={cn('font-semibold', boldClass)}>{mark.text}</span>
            }
            return <span className="">{mark.text}</span>
          }}
        />
      )}
    </>
  )
}
