import { DataFlowSelect } from '@/components/data-pipeline-select';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import Divider from '@/components/ui/divider';
import { Form } from '@/components/ui/form';
import { FormLayout } from '@/constants/form';
import { DocumentParserType, ParseType } from '@/constants/knowledge';
import { PermissionRole } from '@/constants/permission';
import { IConnector, IDataset } from '@/interfaces/database/dataset';
import { useDataSourceInfo } from '@/pages/user-setting/data-source/constant';
import { IDataSourceBase } from '@/pages/user-setting/data-source/interface';
import { zodResolver } from '@hookform/resolvers/zod';
import { createContext, useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { ChunkMethodForm } from './chunk-method-form';
import ChunkMethodLearnMore from './chunk-method-learn-more';
import LinkDataSource, {
  IDataSourceNodeProps,
} from './components/link-data-source';
import { MainContainer } from './configuration-form-container';
import { ChunkMethodItem, ParseTypeItem } from './configuration/common-item';
import { formSchema } from './form-schema';
import { GeneralForm } from './general-form';
import { useFetchKnowledgeConfigurationOnMount } from './hooks';
import { SavingButton } from './saving-button';
const enum DocumentType {
  DeepDOC = 'DeepDOC',
  PlainText = 'Plain Text',
}
export const DataSetContext = createContext<{
  loading: boolean;
  knowledgeDetails: IDataset;
}>({ loading: false, knowledgeDetails: {} as IDataset });

const initialEntityTypes = [
  'organization',
  'person',
  'geo',
  'event',
  'category',
];

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

export default function DatasetSettings() {
  const { t } = useTranslation();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
      chunk_method: DocumentParserType.Naive,
      permission: PermissionRole.Me,
      language: 'English',
      parser_config: {
        layout_recognize: DocumentType.DeepDOC,
        chunk_token_num: 512,
        delimiter: `\n`,
        enable_children: false,
        children_delimiter: `\n`,
        auto_keywords: 0,
        auto_questions: 0,
        html4excel: false,
        topn_tags: 3,
        toc_extraction: false,
        image_table_context_window: 0,
        overlapped_percent: 0,
        // MinerU-specific defaults
        mineru_parse_method: 'auto',
        mineru_formula_enable: true,
        mineru_table_enable: true,
        mineru_lang: 'English',
        raptor: {
          use_raptor: true,
          max_token: 256,
          threshold: 0.1,
          max_cluster: 64,
          random_seed: 0,
          scope: 'file',
          clustering_method: 'gmm',
          tree_builder: 'raptor',
          prompt: t('knowledgeConfiguration.promptText'),
        },
        graphrag: {
          use_graphrag: true,
          entity_types: initialEntityTypes,
          method: MethodValue.Light,
          batch_chunk_token_size: 4096,
        },
        metadata: {
          type: 'object',
          properties: {},
          additionalProperties: false,
        },
        built_in_metadata: [],
        compilation_template_group_id: [],
        enable_metadata: false,
        llm_id: '',
      },
      pipeline_id: '',
      parse_type: ParseType.BuiltIn,
      pagerank: 0,
      connectors: [],
    },
  });
  const { dataSourceInfo } = useDataSourceInfo();
  const { knowledgeDetails, loading: datasetSettingLoading } =
    useFetchKnowledgeConfigurationOnMount(form);
  // const [pipelineData, setPipelineData] = useState<IDataPipelineNodeProps>();
  const [sourceData, setSourceData] = useState<IDataSourceNodeProps[]>();

  useEffect(() => {
    if (knowledgeDetails) {
      // const data: IDataPipelineNodeProps = {
      //   id: knowledgeDetails.pipeline_id,
      //   name: knowledgeDetails.pipeline_name,
      //   avatar: knowledgeDetails.pipeline_avatar,
      //   linked: true,
      // };
      // setPipelineData(data);

      const source_data: IDataSourceNodeProps[] = (
        knowledgeDetails?.connectors ?? []
      ).map((connector: IConnector) => {
        return {
          ...connector,
          icon:
            dataSourceInfo[connector.source as keyof typeof dataSourceInfo]
              ?.icon || '',
        };
      });

      setSourceData(source_data);

      form.setValue(
        'parse_type',
        knowledgeDetails.pipeline_id ? ParseType.Pipeline : ParseType.BuiltIn,
      );
      form.setValue('pipeline_id', knowledgeDetails.pipeline_id || '');
    }
  }, [knowledgeDetails, form]);

  async function onSubmit(data: z.infer<typeof formSchema>) {
    try {
      console.log('Form validation passed, submit data', data);
    } catch (error) {
      console.error('An error occurred during submission:', error);
    }
  }
  // const handleLinkOrEditSubmit = (
  //   data: IDataPipelineSelectNode | undefined,
  // ) => {
  //   console.log('🚀 ~ DatasetSettings ~ data:', data);
  //   if (data) {
  //     setPipelineData(data);
  //     form.setValue('pipeline_id', data.id || '');
  //     // form.setValue('pipeline_name', data.name || '');
  //     // form.setValue('pipeline_avatar', data.avatar || '');
  //   }
  // };

  const handleLinkOrEditSubmit = (data: IConnector[] | undefined) => {
    if (data) {
      const connectors = data.map((connector) => {
        return {
          ...connector,
          auto_parse: connector.auto_parse === '0' ? '0' : '1',
          icon:
            dataSourceInfo[connector.source as keyof typeof dataSourceInfo]
              ?.icon || '',
        };
      });
      setSourceData(connectors as IDataSourceNodeProps[]);
      form.setValue('connectors', connectors || []);
      // form.setValue('pipeline_name', data.name || '');
      // form.setValue('pipeline_avatar', data.avatar || '');
    }
  };

  const parseType = useWatch({
    control: form.control,
    name: 'parse_type',
    defaultValue: knowledgeDetails.pipeline_id
      ? ParseType.Pipeline
      : ParseType.BuiltIn,
  });
  const selectedTag = useWatch({
    name: 'chunk_method',
    control: form.control,
  });

  useEffect(() => {
    if (parseType === ParseType.BuiltIn) {
      form.setValue('pipeline_id', '');
    } else {
      form.setValue('chunk_method', DocumentParserType.Naive);
    }
  }, [parseType, form]);

  const unbindFunc = (data: IDataSourceBase) => {
    if (data) {
      const connectors = sourceData?.filter((connector) => {
        return connector.id !== data.id;
      });
      setSourceData(connectors as IDataSourceNodeProps[]);
      form.setValue('connectors', connectors || []);
      // form.setValue('pipeline_name', data.name || '');
      // form.setValue('pipeline_avatar', data.avatar || '');
    }
  };
  const handleAutoParse = ({
    source_id,
    isAutoParse,
  }: {
    source_id: string;
    isAutoParse: boolean;
  }) => {
    if (source_id) {
      const connectors = sourceData?.map((connector) => {
        if (connector.id === source_id) {
          return {
            ...connector,
            auto_parse: isAutoParse ? '1' : '0',
          };
        }
        return connector;
      });
      setSourceData(connectors as IDataSourceNodeProps[]);
      form.setValue('connectors', connectors || []);
    }
  };

  return (
    <div className="pr-5 pb-5">
      <Card className="p-0 h-full flex flex-col bg-transparent shadow-none">
        <CardHeader className="p-5 border-b-0.5 border-border-button">
          <header>
            <CardTitle as="h1">{t('knowledgeDetails.configuration')}</CardTitle>

            <CardDescription>
              {t('knowledgeConfiguration.titleDescription')}
            </CardDescription>

            {/* <Button>Save as Preset</Button> */}
          </header>
        </CardHeader>

        <CardContent className="p-0 flex-1 h-0 flex divide-x-0.5">
          <DataSetContext.Provider
            value={{
              loading: datasetSettingLoading,
              knowledgeDetails: knowledgeDetails,
            }}
          >
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="flex flex-col"
              >
                <div className="flex-1 h-0 w-[768px] px-5 pt-5 overflow-y-auto scrollbar-auto">
                  <MainContainer className="text-text-secondary">
                    <div className="text-base font-medium text-text-primary">
                      {t('knowledgeConfiguration.baseInfo')}
                    </div>
                    <GeneralForm></GeneralForm>

                    <Divider />
                    <div className="text-base font-medium text-text-primary">
                      {t('knowledgeConfiguration.dataPipeline')}
                    </div>
                    <ParseTypeItem line={1} name="parse_type" />
                    {parseType === ParseType.BuiltIn && (
                      <ChunkMethodItem
                        line={1}
                        name="chunk_method"
                      ></ChunkMethodItem>
                    )}
                    {parseType === ParseType.Pipeline && (
                      <DataFlowSelect
                        isMult={false}
                        showToDataPipeline={true}
                        formFieldName="pipeline_id"
                        layout={FormLayout.Horizontal}
                      />
                    )}

                    {parseType === ParseType.BuiltIn && <ChunkMethodForm />}

                    {/* <LinkDataPipeline
                    data={pipelineData}
                    handleLinkOrEditSubmit={handleLinkOrEditSubmit}
                  /> */}
                    <Divider />
                    <LinkDataSource
                      data={sourceData}
                      handleLinkOrEditSubmit={handleLinkOrEditSubmit}
                      unbindFunc={unbindFunc}
                      handleAutoParse={handleAutoParse}
                    />
                  </MainContainer>
                </div>

                <div className="p-5 text-right items-center flex justify-end gap-3 w-[768px]">
                  <Button
                    type="reset"
                    variant="transparent"
                    onClick={() => {
                      form.reset();
                    }}
                  >
                    {t('knowledgeConfiguration.cancel')}
                  </Button>

                  <SavingButton />
                </div>
              </form>
            </Form>
          </DataSetContext.Provider>

          <div className="flex-1 p-5 overflow-auto">
            {parseType === ParseType.BuiltIn && (
              <ChunkMethodLearnMore parserId={selectedTag} />
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
