import { Button, Card, Collapse, Divider, Grid, Group, HoverCard, Input, Stack, Typography } from '@tidbcloud/uikit'
import { FormNumberInput, FormSwitch, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconAtom02, IconChevronRight, IconInfoCircle } from '@tidbcloud/uikit/icons'
import { useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'

import { CSVImage } from 'dbaas/screens/DataImportV2/CSVConfiguration'
import { V1beta2CSVFormat } from 'dbaas/services/dataflow/interface'

export const LearnHowMappingWorks = () => {
  const [showLearnMore, setShowLearnMore] = useState(false)

  return (
    <Card>
      <Card.Section>
        <Group
          px={16}
          py={12}
          bg="carbon.2"
          justify="space-between"
          sx={{ cursor: 'pointer' }}
          onClick={() => setShowLearnMore(!showLearnMore)}
        >
          <Group gap={8}>
            <IconAtom02 />
            <Typography variant="label-md">Learn how source-target mapping works</Typography>
          </Group>

          <IconChevronRight
            sx={{
              transform: showLearnMore ? 'rotate(90deg)' : 'rotate(0deg)',
              transition: 'transform 0.3s ease-in-out'
            }}
          />
        </Group>
      </Card.Section>
      <Card.Section>
        <Collapse in={showLearnMore}>
          <Stack px={16} py={12}>
            <Typography>
              When your files follow the{' '}
              <a href="https://docs.pingcap.com/tidb/stable/dumpling-overview/" target="_blank" rel="noreferrer">
                TiDB Dumpling naming convention
              </a>
              , TiDB Cloud can automatically map them to the correct database and table in the next step.
            </Typography>

            <Typography>
              Data files such as <b>mydb.customers.000000000.sql</b> (or .csv) map to the table <b>mydb.customer</b>.
            </Typography>

            <Typography>
              If schema (DDL) files like <b>mydb-schema-create.sql</b> and <b>mydb.customers-schema.sql</b> are present,
              TiDB Cloud can also automatically create the database and tables. Without schema files, the target tables
              must already exist and be empty.
            </Typography>

            <Typography>
              When your files don't follow Dumpling naming conventions, you must uncheck that option and manually map
              source files to target tables.
            </Typography>
          </Stack>
        </Collapse>
      </Card.Section>
    </Card>
  )
}

const DEFAULT_CSV_FORMAT: V1beta2CSVFormat = {
  separator: ',',
  delimiter: '"',
  lineTerminator: '\\r\\n',
  escapeChar: '\\',
  skipRows: 0,
  nullValue: '\\N',
  splitFile: false
}

export function CSVConfigurationForPremiumImport({
  defaultValues = DEFAULT_CSV_FORMAT,
  onCancel,
  onApply
}: {
  defaultValues?: V1beta2CSVFormat
  onCancel?: () => void
  onApply?: (data: V1beta2CSVFormat) => void
}) {
  const methods = useForm<V1beta2CSVFormat>({ defaultValues })
  const splitFile = methods.watch('splitFile')

  const onReset = () => {
    methods.reset(defaultValues)
  }

  const onSubmit = (data: V1beta2CSVFormat) => {
    onApply?.(data)
  }

  return (
    <FormProvider {...methods}>
      <Stack>
        <Grid>
          <Grid.Col span={3}>
            <FormTextInput name="lineTerminator" label="Line Terminator" size="sm" />
          </Grid.Col>

          <Grid.Col span={3}>
            <FormTextInput name="delimiter" label="Delimiter" size="sm" />
          </Grid.Col>

          <Grid.Col span={3}>
            <FormTextInput name="escapeChar" label="Escape Character" size="sm" />
          </Grid.Col>

          <Grid.Col span={3}>
            <FormTextInput
              name="separator"
              label={
                <Input.Label mb={0}>
                  <Group gap={8}>
                    <span>Separator</span>
                    <HoverCard position="top">
                      <HoverCard.Target>
                        <IconInfoCircle cursor="pointer" size={14} color="carbon.8" />
                      </HoverCard.Target>
                      <HoverCard.Dropdown maw={480}>
                        <Typography variant="body-lg">
                          To use tab as separator (TSV format), enter \t in the separator field.
                        </Typography>
                      </HoverCard.Dropdown>
                    </HoverCard>
                  </Group>
                </Input.Label>
              }
              size="sm"
            />
          </Grid.Col>

          <Grid.Col span={4}>
            <FormNumberInput
              name="skipRows"
              min={0}
              max={splitFile ? 1 : Infinity}
              label={
                <Input.Label mb={0}>
                  <Group gap={8}>
                    <span>Skip first</span>
                    <HoverCard position="top">
                      <HoverCard.Target>
                        <IconInfoCircle cursor="pointer" size={14} color="carbon.8" />
                      </HoverCard.Target>
                      <HoverCard.Dropdown maw={480}>
                        <Typography variant="body-lg">
                          Skip the first n rows of the file, use 0 for CSV files without a header, 1 to skip a
                          single-line header, or any higher number to bypass that many initial rows. When Auto split
                          file is enabled, Skip first can only be 0 or 1.
                        </Typography>
                      </HoverCard.Dropdown>
                    </HoverCard>
                  </Group>
                </Input.Label>
              }
              suffix=" row(s)"
              size="sm"
            />
          </Grid.Col>

          <Grid.Col span={4}>
            <FormTextInput name="nullValue" label="NULL value" size="sm" />
          </Grid.Col>

          <Grid.Col span={4}>
            <Stack gap={6}>
              <Input.Label mb={0}>Auto split file</Input.Label>
              <FormSwitch name="splitFile" size="md" />
            </Stack>
          </Grid.Col>
        </Grid>

        <CSVImage />

        <Divider mx={-24} />

        <Group justify="flex-end">
          <Button type="button" variant="default" onClick={onCancel}>
            Cancel
          </Button>

          <Button type="button" variant="default" onClick={onReset}>
            Reset
          </Button>

          <Button type="button" onClick={methods.handleSubmit(onSubmit)}>
            Apply
          </Button>
        </Group>
      </Stack>
    </FormProvider>
  )
}
