'use client'

import SearchBox from '@/components/input/SearchBox'
import { ScrollArea } from '@/components/ui/scrollarea'
import { Radar2, Trash } from 'iconsax-react'
import { Check, CheckCheck } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
  LongPressCallbackMeta,
  LongPressReactEvents,
  useLongPress
} from 'use-long-press'
import { useRouter } from 'next/navigation'
import useToggle from '@/hooks/helpers/useToggle'
import Prompt from '@/components/utils/Prompt'
import { glassSurfaceFlat } from '@/lib/styles/glassSurface'

type Props = object

type ChatEntryModel = {
  id: string
  username: string
  avatarUrl: string
  update?: {
    time: string
    content: string
    count?: number
    seen?: boolean
  }
}

function ChatIndex ({}: Props) {
  const { t } = useTranslation('chat')
  const { t: tDeleteModal } = useTranslation('common', {
    keyPrefix: 'DeleteChatModal'
  })
  const [search, setSearch] = useState('')
  const [selectedChats, setSelectedChats] = useState<Array<string>>([])
  const router = useRouter()
  const { state: deleteModal, toggle: toggleDeleteModal } = useToggle()

  const [chatsList, setChatList] = useState<Array<ChatEntryModel>>([
    {
      id: '0',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        count: 2
      }
    },
    {
      id: '1',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        count: 2
      }
    },
    {
      id: '2',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        seen: true
      }
    },
    {
      id: '3',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        seen: true
      }
    },
    {
      id: '4',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        seen: true
      }
    },
    {
      id: '5',
      username: 'علی مصلحی',
      avatarUrl: '/assets/images/user-avatar.png',
      update: {
        time: '12:03',
        content: 'چه خبر',
        seen: false
      }
    }
  ])

  const toggleDeleteModalVisiblity = (e?: React.MouseEvent) => {
    e?.preventDefault()
    e?.stopPropagation()
    if (deleteModal) {
      setSelectedChats([])
    }
    toggleDeleteModal()
  }

  const deleteSelectedChats = () => {
    if (setSelectedChats.length <= 0) return
    setChatList(prev => {
      return prev.filter(x => !selectedChats.includes(x.id))
    })
    toggleDeleteModalVisiblity()
  }

  const longPressCallback = useCallback(
    (e: LongPressReactEvents<Element>, ctx: LongPressCallbackMeta<unknown>) => {
      e.preventDefault()
      if (!ctx?.context) return
      const id = String(ctx.context)
      setSelectedChats(prev => {
        if (prev.includes(id)) return prev.filter(x => x !== id)
        return [...prev, id]
      })
    },
    []
  )

  const longPressCancelledCallback = useCallback(
    (id: string, reason?: string) => {
      if (reason && reason !== 'cancelled-by-release') return
      if (selectedChats.length > 0) {
        setSelectedChats(prev => {
          if (prev.includes(id)) return prev.filter(x => x !== id)
          return [...prev, id]
        })
      } else {
        router.push(`chat/${id}`)
      }
    },
    [router, selectedChats.length]
  )

  const longPress = useLongPress(longPressCallback, {
    onCancel: (event, ctx) =>
      longPressCancelledCallback(String(ctx.context), String(ctx.reason)),
    threshold: 500, // In milliseconds
    captureEvent: true, // Event won't get cleared after React finish processing it
    cancelOnMovement: 100, // Square side size (in pixels) inside which movement won't cancel long press
    cancelOutsideElement: true // Cancel long press when moved mouse / pointer outside element while pressing
  })

  return (
    <div className='pt-8 mb-8'>
      <section className='flex justify-between items-center gap-x-4'>
        <SearchBox
          placeholder={t('InputSearch.Placeholder')}
          value={search}
          onChange={e => setSearch(e.target.value)}
        />

        {selectedChats.length > 0 ? (
          <span
            onClick={toggleDeleteModal}
            className={glassSurfaceFlat('p-2 rounded-xl active:brightness-95 cursor-pointer')}
          >
            <Trash
              size={24}
              className='stroke-primary dark:stroke-disabled-text'
            />
          </span>
        ) : (
          <Link
            href={'chat/nearby'}
            className={glassSurfaceFlat('p-2 rounded-xl active:brightness-95 cursor-pointer')}
          >
            <Radar2
              size={24}
              className='stroke-primary dark:stroke-disabled-text'
            />
          </Link>
        )}
      </section>

      <section>
        <ScrollArea dir='rtl' className='w-full h-full'>
          <ul className='pt-4'>
            {chatsList.map((chat, i) => {
              return (
                <li
                  key={i}
                  {...longPress(chat.id)}
                  className={glassSurfaceFlat('select-none flex items-center gap-x-2 hover:brightness-105 cursor-default active:brightness-102 p-2 rounded-xl')}
                >
                  <div className='size-[49px] min-w-[49px]'>
                    {selectedChats.includes(chat.id) ? (
                      <div className='size-[49px] relative bg-primary rounded-full'>
                        <Check className='absolute top-1/2 left-1/2 -translate-1/2 stroke-white' />
                      </div>
                    ) : (
                      <Image
                        src={chat.avatarUrl}
                        height={49}
                        width={49}
                        alt={`${chat.username}'s avatar`}
                        unoptimized
                      />
                    )}
                  </div>

                  <div className='flex flex-col justify-between w-full gap-2'>
                    <h5 className='text-sm2 font-medium'>{chat.username}</h5>
                    <p className='text-xs'>{chat.update?.content}</p>
                  </div>

                  <div className='flex flex-col justify-between items-end gap-2'>
                    <span className='text-sm2 text-disabled2'>
                      {chat.update?.time}
                    </span>
                    {chat.update?.count !== undefined &&
                    chat.update?.count > 0 ? (
                      <span className='text-xs w-5 h-5 relative bg-foreground dark:bg-neutral-700 text-white rounded-full'>
                        <span className='absolute top-1/2 left-1/2 -translate-1/2 pt-1'>
                          {chat.update?.count}
                        </span>
                      </span>
                    ) : chat.update?.seen !== undefined && chat.update?.seen ? (
                      <CheckCheck className='stroke-foreground' size={16} />
                    ) : (
                      <Check className='stroke-foreground' size={16} />
                    )}
                  </div>
                </li>
              )
            })}
          </ul>
        </ScrollArea>
      </section>

      <Prompt
        title={tDeleteModal('Heading')}
        description={tDeleteModal('Description').replace(
          '{count}',
          String(selectedChats.length)
        )}
        textConfirm={tDeleteModal('ButtonOk')}
        textCancel={tDeleteModal('ButtonCancel')}
        onConfirm={deleteSelectedChats}
        onCancel={toggleDeleteModalVisiblity}
        onClick={toggleDeleteModalVisiblity}
        visible={deleteModal}
      />
    </div>
  )
}

export default ChatIndex
