'use client';

import { getAge } from '@/lib/utils';
import { CharacterAvatorAndName } from '../CharacterHeader';
import { Tag } from '@/components/ui/tag';
import Image from 'next/image';
import { cn } from '@/lib/utils';
import { Button, IconButton } from '@/components/ui/button';
import React from 'react';
import { Switch } from '@/components/ui/switch';
import { useCharacter } from '@/hooks/services/character';
import { useParams } from 'next/navigation';
import { ActiveTabType } from './index';
import { useStreamChatStore } from '@/app/(main)/chat/[id]/stream-chat';
import { useAsyncFn } from '@/hooks/tools';
import { useRouter } from 'next/navigation';
import { useModels } from '@/hooks/services/chat';
import { toast } from 'sonner';
import { useTranslations } from 'next-intl';

const genderMap = {
  0: '/icons/male.svg',
  1: '/icons/female.svg',
  2: '/icons/gender-neutral.svg',
};

const ChatProfilePersona = React.memo(({ onActiveTab }: ProfileProps) => {
  const t = useTranslations('chat.drawer');
  const tCommon = useTranslations('common');
  const whoAmI = 'whoAmI';

  return (
    <div className="flex w-full flex-col gap-3">
      <div className="flex items-center justify-between gap-3">
        <div className="txt-title-s">{t('maskedIdentityMode')}</div>
        <div
          className="txt-label-m text-primary-variant-normal cursor-pointer"
          onClick={() => onActiveTab('mask')}
        >
          {tCommon('edit')}
        </div>
      </div>

      <div className="bg-surface-element-normal rounded-m py-1">
        <div className="flex items-center justify-between gap-4 px-4 py-3">
          <div className="txt-label-l text-txt-secondary-normal">{t('profile.nickname')}</div>
          <div className="txt-body-l text-txt-primary-normal flex-1 truncate text-right">{''}</div>
        </div>
        <div className="flex items-center justify-between gap-4 px-4 py-3">
          <div className="txt-label-l text-txt-secondary-normal">{t('profile.gender')}</div>
          <div className="txt-body-l text-txt-primary-normal">
            {genderMap[0 as keyof typeof genderMap]}
          </div>
        </div>
        <div className="flex items-center justify-between gap-4 px-4 py-3">
          <div className="txt-label-l text-txt-secondary-normal">{t('profile.age')}</div>
          <div className="txt-body-l text-txt-primary-normal">{getAge(Number(23))}</div>
        </div>
        <div className="flex items-center justify-between gap-4 px-4 py-3">
          <div className="txt-label-l text-txt-secondary-normal">{t('profile.whoAmI')}</div>
          <div
            className={cn(
              'txt-body-l text-txt-primary-normal flex-1 truncate text-right',
              whoAmI ? 'text-txt-primary-normal' : 'text-txt-secondary-normal'
            )}
          >
            {whoAmI || t('profile.unfilled')}
          </div>
        </div>
      </div>
    </div>
  );
});

type SettingItem = {
  onClick: () => void;
  label: string;
  value?: React.ReactNode;
};

type ProfileProps = {
  onActiveTab: (tab: ActiveTabType) => void;
};

export default function Profile({ onActiveTab }: ProfileProps) {
  const t = useTranslations('chat.drawer.profile');
  const tCommon = useTranslations('common');
  const { id } = useParams<{ id: string }>();
  const characterId = id.split('-')[2];
  const {} = useModels();
  const router = useRouter();
  const { data: character = {} } = useCharacter(characterId);
  const chatSetting = useStreamChatStore((s) => s.chatSetting);
  const setChatSetting = useStreamChatStore((s) => s.setChatSetting);
  const createChannel = useStreamChatStore((s) => s.createChannel);
  const deleteChannel = useStreamChatStore((s) => s.deleteChannel);

  const { loading: creating, run: createChannelAndPush } = useAsyncFn(async () => {
    const { result, channelId, error } = await createChannel(characterId);
    if (result === 'error') {
      toast.error(error);
      return;
    }
    router.push(`/chat/${channelId}`);
  });

  const { run: deleteChannelAsync, loading: deleting } = useAsyncFn(async () => {
    const { result, newChannels } = await deleteChannel([id]);
    if (result === 'ok') {
      if (newChannels?.length) {
        router.push(`/chat/${newChannels[0].id}`);
      } else {
        router.push(`/`);
      }
    }
  });

  const chatSettingItems: SettingItem[][] = [
    [
      {
        onClick: () => onActiveTab('model'),
        label: t('chatModel'),
        value: chatSetting?.chatModel,
      },
      {
        onClick: () => null,
        label: t('longText'),
        value: (
          <Switch
            onCheckedChange={() => setChatSetting({ longText: chatSetting.longText ? 0 : 1 })}
            checked={chatSetting.longText === 0}
          />
        ),
      },
    ],
    [
      {
        onClick: () => onActiveTab('max_token'),
        label: t('maximumReplies'),
        value: String(chatSetting?.maximumReplies),
      },
    ],
    [
      {
        onClick: () => onActiveTab('font'),
        label: t('font'),
        value: String(chatSetting?.font),
      },
      {
        onClick: () => onActiveTab('background'),
        label: t('chatBackground'),
        value: String(chatSetting?.background),
      },
    ],
  ];

  const voiceSettingItems: SettingItem[][] = [
    [
      {
        onClick: () => onActiveTab('voice_actor'),
        label: t('voiceArtist'),
        value: tCommon('default'),
      },
    ],
  ];

  const bundleRender = (title: string, items: SettingItem[][]) => {
    return (
      <div className="flex w-full flex-col items-start justify-start gap-3">
        <div className="txt-title-s w-full text-left">{title}</div>
        <div className="flex w-full flex-col items-start justify-start gap-4">
          {items.map((list, index) => (
            <div key={`group_${index}`} className="bg-surface-element-normal rounded-m w-full py-1">
              {list.map((item, itemIndex) => (
                <div
                  key={`item_${itemIndex}`}
                  className={cn(
                    'flex h-12 cursor-pointer items-center justify-between mx-4 py-3',
                    itemIndex < list.length - 1 && 'border-b border-outline-normal'
                  )}
                  onClick={item.onClick}
                >
                  <div className="txt-label-l">{item.label}</div>
                  <div className="flex min-w-0 flex-1 cursor-pointer items-center justify-end gap-2">
                    {item.value && (
                      <div className="txt-body-l flex items-center text-txt-primary-normal truncate">
                        {item.value}
                      </div>
                    )}
                    {typeof item.value === 'string' && (
                      <IconButton iconfont="icon-arrow-right-border" size="small" variant="ghost" />
                    )}
                  </div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="flex h-full flex-col">
      <div className="flex flex-1 overflow-y-auto pr-1 show-scrollbar flex-col gap-4">
        <CharacterAvatorAndName
          id={characterId}
          avator={character?.headPortrait}
          name={character?.name}
        />

        {/* Tags */}
        <div className="flex w-full flex-col items-start justify-start gap-4">
          <div className="flex w-full flex-wrap items-start justify-center gap-2">
            {character?.tags?.map((tag: any) => (
              <Tag key={tag.tagId}>{tag.name}</Tag>
            ))}
          </div>
        </div>

        <ChatProfilePersona onActiveTab={onActiveTab} />

        {bundleRender(t('chatSetting'), chatSettingItems)}

        {bundleRender(t('voiceSetting'), voiceSettingItems)}
      </div>
      <div className="flex flex-col gap-2 mt-2">
        <Button
          variant="tertiary"
          className="w-full"
          loading={deleting}
          onClick={deleteChannelAsync}
        >
          {t('delete')}
        </Button>
        <Button
          variant="primary"
          loading={creating}
          onClick={createChannelAndPush}
          className="w-full"
        >
          + {t('newChat')}
        </Button>
      </div>
    </div>
  );
}
