import { Controller, useFormContext } from 'react-hook-form'
import { Checkbox, Box, Text, Group } from '@pikku/mantine/core'
import type { DB } from '@heygermany/sdk'
import { ApplicationCandidateData, ApplicationCandidateLicense, CandidateDocumentTypes } from '@heygermany/sdk'
import { FileUpload } from '../../ui/FileUpload'
import { useUploadCandidateFiles } from '@/hooks/useUploadCandidateFiles'
import { useEffect } from 'react'
import { CandidateSection } from './CandidateSection'
import { useI18n } from '@/context/i18n-provider'
import { asI18n } from '@pikku/react'

export const License: React.FunctionComponent<{ candidate: ApplicationCandidateData }> = ({ candidate }) => {
  const t = useI18n()
  const { control, trigger, formState: { errors }, watch, setValue } = useFormContext<ApplicationCandidateLicense>()

  const licenseProvided = watch('licenseProvided')

  const { uploadFiles, deleteFile } = useUploadCandidateFiles(candidate.candidateId, CandidateDocumentTypes.LICENSE, trigger)

  const validateLicenses = (files: any[]): boolean | string => {
    if (!files || files.length === 0) {
      return t('jobs.license.validation.required')
    }

    if (files.length > 5) {
      return t('jobs.license.validation.maxfiles')
    }

    return true
  }

  useEffect(() => {
    if (licenseProvided === null) {
      setValue('licenseProvided', true)
    }
  }, [licenseProvided])

  useEffect(() => {
    if (licenseProvided === false) {
      trigger()
    }
  }, [licenseProvided])

  return (
    <CandidateSection
      title={t('jobs.license.title')}
      example={t('jobs.license.example')}
      description={t('jobs.license.description')}
    >
      <Box>
        <Controller
          name="licenseProvided"
          control={control}
          render={({ field }) => (
            <Group gap="xs" mb="lg">
              <Checkbox
                id="license-not-provided"
                checked={field.value === false}
                onChange={(e) => field.onChange(!e.currentTarget.checked)}
              />
              <Text size="sm" style={{ cursor: 'pointer' }} component="label" htmlFor="license-not-provided">
                {t('jobs.license.nolicense')}
              </Text>
            </Group>
          )}
        />

        {licenseProvided && (
          <Controller
            name="licenses"
            control={control}
            rules={{
              validate: () => validateLicenses(candidate.licenses)
            }}
            render={() => (
              <FileUpload
                files={candidate.licenses.map((file: DB.CandidateDocument) => ({ id: file.documentId, fileName: file.fileName }))}
                uploadFiles={uploadFiles}
                deleteFile={deleteFile}
              />
            )}
          />
        )}

        {errors.licenses && (
          <Text size="sm" c="error" mt="xs">
            {asI18n(errors.licenses?.message ?? '')}
          </Text>
        )}
      </Box>
    </CandidateSection>
  )
}
