'use client';

import { type FormGroupItemType } from '@lobehub/ui';
import { Form, Icon, Skeleton, Tooltip } from '@lobehub/ui';
import { Select } from '@lobehub/ui/base-ui';
import { Switch } from 'antd';
import isEqual from 'fast-deep-equal';
import { Loader2Icon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { FORM_STYLE } from '@/const/layoutTokens';
import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';

import { sttOptions } from './const';

const STT = memo(() => {
  const { t } = useTranslation('setting');
  const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
  const [form] = Form.useForm();
  const { tts } = useUserStore(settingsSelectors.currentSettings, isEqual);
  const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
  const [loading, setLoading] = useState(false);

  if (!isUserStateInit) return <Skeleton active paragraph={{ rows: 5 }} title={false} />;

  const stt: FormGroupItemType = {
    children: [
      {
        children: (
          <Tooltip title={reason}>
            <Select disabled={!canManageServiceModel} options={sttOptions} style={{ width: 448 }} />
          </Tooltip>
        ),
        desc: t('settingTTS.sttService.desc'),
        label: t('settingTTS.sttService.title'),
        name: 'sttServer',
      },
      {
        children: (
          <Tooltip title={reason}>
            <Switch disabled={!canManageServiceModel} />
          </Tooltip>
        ),
        desc: t('settingTTS.sttAutoStop.desc'),
        label: t('settingTTS.sttAutoStop.title'),
        layout: 'horizontal',
        name: 'sttAutoStop',
        valuePropName: 'checked',
      },
    ],
    extra: loading && <Icon spin icon={Loader2Icon} size={16} style={{ opacity: 0.5 }} />,
    title: t('settingTTS.stt'),
  };

  return (
    <Form
      collapsible={false}
      form={form}
      initialValues={tts}
      items={[stt]}
      itemsType={'group'}
      variant={'filled'}
      onValuesChange={async (values) => {
        if (!canManageServiceModel) return;

        setLoading(true);
        await setSettings({
          tts: values,
        });
        setLoading(false);
      }}
      {...FORM_STYLE}
      itemMinWidth={undefined}
    />
  );
});

export default STT;
