import React from 'react';
import styled from 'styled-components';
import { ContentWidth, Surface, IconFile } from '../ui';
import { DragAndDrop, Button, Select, MenuItem, TextInput, Loading } from '@nemo-ui/core'
import { useUnit } from 'effector-react';
import { $error, $pending, $projects, generateFx, ProjectsGate, retryClicked } from './generate-model';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { generateUtilsReadFileAsText } from './generate-utils-read-file-as-text';
import { PageResult } from '../page-result';

const Wrapper = styled(ContentWidth)`
    margin: 0 auto;
`;
const Inner = styled(Surface)`
    width: 100%;
    box-shadow: 0px 1px 9px rgba(0, 0, 0, 0.09);
    border-radius: 8px;
    padding: 20px 30px 36px;
    display: flex;
    flex-direction: column;
`;
const Title = styled.div`
    font-style: normal;
    font-weight: 700;
    font-size: 32px;
    line-height: 40px;
    margin-bottom: 32px;
`;
const Hr = styled.div`
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    margin-bottom: 32px;

    p {
        font-weight: 400;
        font-size: 12px;
        line-height: 22px;
        color: #616A73;
    }
    .line {
        height: 1px;
        width: auto;
        background-color: #D9D9D9;
        flex-grow: 1;
        margin-top: 2px;
    }
`;
const Form = styled.div`
    display: grid;
    gap: 16px;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2,auto);
    gap: 16px;
    width: 100%;
    margin-bottom: 32px;

    .cols2 {
        grid-column: 1 / span 2;
        grid-row: 1;
    }


    & > * {
        width: 100%;
        min-height: 0;
        overflow: hidden;
    }
    .nemo-ui_select-selectedItem {
        display: block;
        & > * {
            overflow: hidden;
        }
            .nemo-ui_menuItem {
                display: block;
                overflow: hidden;
                text-overflow: ellipsis;
            }
    }
`;
const LoadingTooltip = styled.h1`
  margin: 0 auto;
  display: block;
  text-align: center;
`;
const getExtension = (str: string): string => {
  return str.slice(str.indexOf('.') + 1)
}
const MAX_FILE_SIZE = 99999999999999;
const schema = Yup.object({
  project: Yup.object({
    title: Yup.string().required(),
    source_id: Yup.string().required(),
    comment: Yup.string().required().nullable().optional(),
  }).required("Обязательно").nullable(),
  pageName: Yup.string().min(1).required(),
  linkAdditionalPage: Yup.string().min(1).required(),
  documentType: Yup.object({
    id: Yup.string().required(),
    title: Yup.string().required(),
  }).required("Обязательно").nullable(),
  files: Yup.mixed()
    .test({
      message: 'Please provide a supported file type',
      test: (file, context) => {
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        if (typeof file === 'object' && file !== null && 'name' in file && typeof file.name === 'string') {
          const isValid = ['txt'].includes(file.name.length > 0 ? getExtension(file.name) : '');
          if (!isValid) context.createError();
          return isValid;
        }
        context.createError();
        return false;

      }
    })
    .test({
      message: `File too big, can't exceed ${String(MAX_FILE_SIZE)}`,
      test: (file) => {
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        if (typeof file === 'object' && file !== null &&  'size' in file && typeof file.size === 'number') {
          const isValid = file.size < MAX_FILE_SIZE;
          return isValid;
        }
        return false;
      }
    })
    .required('Required')
    .nullable()
});

const documentTypeOptions = [
  {
    id: 'Спецификация Backend',
    title: 'Спецификация Backend'
  },
  {
    id: 'Спецификация межсистемного / внутрисистемного взаимодействия',
    title: 'Спецификация межсистемного / внутрисистемного взаимодействия'
  },
];

type Schema = Yup.InferType<typeof schema>;

export const GenerateView: React.FC = () => {
  const [
    projects,
    projectsPending,
    projectsError,
    projectsOnRetry,
  ] = useUnit([
    $projects,
    $pending,
    $error,
    retryClicked
  ]);




  const formik = useFormik<Schema>({
    initialValues: {
      project: null,
      pageName: '',
      linkAdditionalPage: '',
      documentType: null,
      files: null,
    },
    validationSchema: schema,
    onSubmit: async (values, helpers) => {
      if (!values.project?.source_id) return; // todo
      if (!values.documentType?.id) return; // todo
      if (!values.files) return; // todo

      const readedFile = await generateUtilsReadFileAsText(values.files as File);
      if (typeof readedFile !== 'string') return; //todo
      const result = await generateFx({
        attached_link: values.linkAdditionalPage,
        document_type: values.documentType.id,
        jira_text: readedFile,
        page_name: values.pageName,
        project: values.project.source_id,
      });
      // await sendLoginFromFx({
      //   username: values.username,
      //   password: values.password,
      // });
    }
  });

  console.log('>>>', formik.values.files)
  return (
    <>
      {JSON.stringify(formik.values)}
      <ProjectsGate />
      {
        projectsPending ? <LoadingTooltip>Загрузка...</LoadingTooltip> :
          <Wrapper>
            <Inner>
              <Title>ИИ генератор документации «Сократ»</Title>
              <Hr>
                <p>Параметры запроса</p>
                <div
                  className="line"
                ></div>
              </Hr>
              <Form>
                <div
                  className="cols2"
                >

                  <Select
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    label="Проект"
                    outLabel={true}
                    size="large"
                    inputProps={{
                      ...formik.getFieldProps("project"),
                    }}
                    error={formik.touched.project && formik.errors.project}
                    value={formik.values.project || '123'}
                  >
                    {
                      projects.map((project, idx) => {
                        return (
                          <MenuItem
                            value={project}
                            key={project.source_id}
                          >
                            {project.title}
                          </MenuItem>
                        )
                      })
                    }
                  </Select>
                  {formik.touched.project && formik.errors.project && (
                    <p
                      className="error-text"
                    >
                      {formik.errors.project}
                    </p>
                  )}
                </div>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={10}
                  label="Бизнес требования"
                  onChange={() => { }}
                  outLabel={true}
                  size="large"
                  icon={<IconFile />}
                >
                  <MenuItem
                    value={10}
                  >Загрузка из файла</MenuItem>
                  <MenuItem
                    value={20}
                  >Twenty</MenuItem>
                  <MenuItem
                    value={30}
                  >Thirty</MenuItem>
                </Select>
                <div>
                  <TextInput
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    value={' '}
                    label="Название страницы"
                    onChange={() => { }}
                    outLabel={true}
                    size="large"
                    style={{ width: '100%' }}
                    inputProps={{
                      ...formik.getFieldProps("pageName"),
                    }}
                    error={formik.touched.pageName && formik.errors.pageName}
                  />
                  {formik.touched.pageName && formik.errors.pageName && (
                    <p
                      className="error-text"
                    >
                      {formik.errors.pageName}
                    </p>
                  )}
                </div>
                <div>

                  <Select
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    label="Тип документа"
                    outLabel={true}
                    size="large"
                    inputProps={{
                      ...formik.getFieldProps("documentType"),

                    }}
                    error={formik.touched.documentType && formik.errors.documentType}
                    value={formik.values.documentType || '123'}
                  >
                    {
                      documentTypeOptions.map((documentType) => {
                        return (
                          <MenuItem
                            value={documentType}
                            key={documentType.id}
                          >
                            {documentType.title}
                          </MenuItem>
                        )
                      })
                    }
                  </Select>
                  {formik.touched.documentType && formik.errors.documentType && (
                    <p
                      className="error-text"
                    >
                      {formik.errors.documentType}
                    </p>
                  )}
                </div>
                <div>
                  <TextInput
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    value={' '}
                    label="Ссылка на доп страницу"
                    onChange={() => { }}
                    outLabel={true}
                    size="large"
                    style={{ width: '100%' }}
                    inputProps={{
                      ...formik.getFieldProps("linkAdditionalPage"),
                    }}
                    error={formik.touched.linkAdditionalPage && formik.errors.linkAdditionalPage}
                  />
                  {formik.touched.linkAdditionalPage && formik.errors.linkAdditionalPage && (
                    <p
                      className="error-text"
                    >
                      {formik.errors.linkAdditionalPage}
                    </p>
                  )}
                </div>
              </Form>
              <Hr>
                <p>Загрузка бизнес требований</p>
                <div
                  className="line"
                ></div>
              </Hr>
              <DragAndDrop
                style={{
                  width: '100%',
                }}
                text={
                  <div
                    style={{ textAlign: 'center' }}
                  >
                    Перенесите файлы для загрузки <br /> Файл TXT — до 200 МБ
                  </div>
                }
                onChange={(e: unknown) => {
                  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                  //@ts-ignore
                  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
                  void formik.setFieldValue("files", e.target?.files?.[0] || null);
                }}
              />
              {formik.touched.files && formik.errors.files && (
                <p
                  className="error-text"
                >
                  {formik.errors.files}
                </p>
              )}
              <Button
                style={{ marginTop: 32 }}
                onClick={() => {
                  void formik.submitForm();
                }}
              >
                Сгенерировать документацию
              </Button>
            </Inner>
          </Wrapper>
      }
    </>
  )
}