import { FormLayout } from '@/constants/form';
import { DocumentParserType } from '@/constants/knowledge';
import { useTranslate } from '@/hooks/common-hooks';
import { cn } from '@/lib/utils';
import { LLMModelItem } from '@/pages/dataset/dataset-setting/configuration/common-item';
import {
  GenerateLogButton,
  GenerateType,
  IGenerateLogButtonProps,
} from '@/pages/dataset/dataset/generate-button/generate';
import { upperFirst } from 'lodash';
import { useCallback, useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { EntityTypesFormField } from '../entity-types-form-field';
import { FormContainer } from '../form-container';
import { SliderInputFormField } from '../slider-input-form-field';
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../ui/form';
import { RAGFlowSelect } from '../ui/select';
import { Switch } from '../ui/switch';

const excludedTagParseMethods = [
  DocumentParserType.Table,
  DocumentParserType.KnowledgeGraph,
  DocumentParserType.Tag,
];

export const showTagItems = (parserId: DocumentParserType) => {
  return !excludedTagParseMethods.includes(parserId);
};

const enum MethodValue {
  General = 'general',
  Light = 'light',
  NER = 'ner',
}

export const excludedParseMethods = [
  DocumentParserType.Table,
  DocumentParserType.Resume,
  DocumentParserType.Picture,
  DocumentParserType.KnowledgeGraph,
  DocumentParserType.Qa,
  DocumentParserType.Tag,
];

export const showGraphRagItems = (parserId: DocumentParserType | undefined) => {
  return !excludedParseMethods.some((x) => x === parserId);
};

type GraphRagItemsProps = {
  marginBottom?: boolean;
  className?: string;
  data: IGenerateLogButtonProps;
  onDelete?: () => void;
};

export function UseGraphRagFormField({
  data,
  onDelete,
}: {
  data: IGenerateLogButtonProps;
  onDelete?: () => void;
}) {
  const form = useFormContext();
  const { t } = useTranslate('knowledgeConfiguration');

  return (
    <FormField
      control={form.control}
      name="parser_config.graphrag.use_graphrag"
      render={() => (
        <FormItem defaultChecked={false} className=" items-center space-y-0 ">
          <div className="flex items-center gap-1">
            <FormLabel
              tooltip={t('useGraphRagTip')}
              className="text-sm whitespace-break-spaces w-1/4"
            >
              {t('useGraphRag')}
            </FormLabel>
            <div className="w-3/4">
              <FormControl>
                {/* <Switch
                  checked={field.value}
                  onCheckedChange={field.onChange}
                ></Switch> */}
                <GenerateLogButton
                  {...data}
                  onDelete={onDelete}
                  className="w-full text-text-secondary"
                  status={1}
                  type={GenerateType.KnowledgeGraph}
                />
              </FormControl>
            </div>
          </div>
          <div className="flex pt-1">
            <div className="w-1/4"></div>
            <FormMessage />
          </div>
        </FormItem>
      )}
    />
  );
}

// The three types "table", "resume" and "one" do not display this configuration.
const GraphRagItems = ({
  marginBottom = false,
  className = 'p-10',
  data,
  onDelete,
}: GraphRagItemsProps) => {
  const { t } = useTranslate('knowledgeConfiguration');
  const form = useFormContext();

  const useRaptor = useWatch({
    control: form.control,
    name: 'parser_config.graphrag.use_graphrag',
  });

  const methodOptions = useMemo(() => {
    return [MethodValue.Light, MethodValue.General /*, MethodValue.NER*/].map(
      (x) => ({
        value: x,
        label: x === MethodValue.NER ? 'NER' : upperFirst(x),
      }),
    );
  }, []);

  const renderWideTooltip = useCallback(
    (title: React.ReactNode | string) => {
      return typeof title === 'string' ? t(title) : title;
    },
    [t],
  );

  return (
    <FormContainer className={cn({ 'mb-4': marginBottom }, className)}>
      <LLMModelItem
        label={t('globalIndexModel')}
        name={'parser_config.llm_id'}
      />
      <UseGraphRagFormField
        data={data}
        onDelete={onDelete}
      ></UseGraphRagFormField>
      {useRaptor && (
        <>
          <EntityTypesFormField
            name="parser_config.graphrag.entity_types"
            addButtonTestId="ds-settings-graph-entity-types-add-btn"
            inputTestId="ds-settings-graph-entity-types-input"
          ></EntityTypesFormField>
          <FormField
            control={form.control}
            name="parser_config.graphrag.method"
            render={({ field }) => (
              <FormItem className=" items-center space-y-0 ">
                <div className="flex items-center">
                  <FormLabel
                    className="text-sm whitespace-nowrap w-1/4"
                    tooltip={renderWideTooltip(
                      <div
                        dangerouslySetInnerHTML={{
                          __html: t('graphRagMethodTip'),
                        }}
                      ></div>,
                    )}
                  >
                    {t('graphRagMethod')}
                  </FormLabel>
                  <div className="w-3/4">
                    <FormControl>
                      <RAGFlowSelect
                        {...field}
                        options={methodOptions}
                        triggerTestId="ds-settings-graph-method-select"
                      ></RAGFlowSelect>
                    </FormControl>
                  </div>
                </div>
                <div className="flex pt-1">
                  <div className="w-1/4"></div>
                  <FormMessage />
                </div>
              </FormItem>
            )}
          />

          <SliderInputFormField
            name="parser_config.graphrag.batch_chunk_token_size"
            label={t('graphRagBatchChunkTokenSize')}
            tooltip={t('graphRagBatchChunkTokenSizeTip')}
            max={8196}
            min={512}
            step={1}
            defaultValue={4096}
            layout={FormLayout.Horizontal}
            sliderTestId="ds-settings-graph-batch-chunk-token-size-slider"
            numberInputTestId="ds-settings-graph-batch-chunk-token-size-input"
          ></SliderInputFormField>

          <FormField
            control={form.control}
            name="parser_config.graphrag.resolution"
            render={({ field }) => (
              <FormItem className=" items-center space-y-0 ">
                <div className="flex items-center">
                  <FormLabel
                    tooltip={renderWideTooltip('resolutionTip')}
                    className="text-sm whitespace-nowrap w-1/4"
                  >
                    {t('resolution')}
                  </FormLabel>
                  <div className="w-3/4">
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                        data-testid="ds-settings-graph-entity-resolution-switch"
                      ></Switch>
                    </FormControl>
                  </div>
                </div>
                <div className="flex pt-1">
                  <div className="w-1/4"></div>
                  <FormMessage />
                </div>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="parser_config.graphrag.community"
            render={({ field }) => (
              <FormItem className=" items-center space-y-0 ">
                <div className="flex items-center">
                  <FormLabel
                    tooltip={renderWideTooltip('communityTip')}
                    className="text-sm whitespace-nowrap w-1/4"
                  >
                    {t('community')}
                  </FormLabel>
                  <div className="w-3/4">
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                        data-testid="ds-settings-graph-community-reports-switch"
                      ></Switch>
                    </FormControl>
                  </div>
                </div>
                <div className="flex pt-1">
                  <div className="w-1/4"></div>
                  <FormMessage />
                </div>
              </FormItem>
            )}
          />
          {/* {showGenerateItem && (
            <div className="w-full flex items-center">
              <div className="text-sm whitespace-nowrap w-1/4">
                {t('extractKnowledgeGraph')}
              </div>
              <GenerateLogButton
                className="w-3/4 text-text-secondary"
                status={1}
                type={GenerateType.KnowledgeGraph}
              />
            </div>
          )} */}
        </>
      )}
    </FormContainer>
  );
};

export default GraphRagItems;
