'use client'

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

export const ProfessionalExperience: React.FunctionComponent<{ candidate: ApplicationCandidateData }> = ({ candidate }) => {
  const t = useI18n()
  const { control, trigger, formState: { errors } } = useFormContext<ApplicationCandidateWorkExperience>()
  const { uploadFiles, deleteFile } = useUploadCandidateFiles(candidate.candidateId, CandidateDocumentTypes.WORK_EXPERIENCE, trigger)

  const validateWorkExperience = (files: any[]): boolean | string => {
    if (files && files.length > 5) {
      return t('jobs.professionalexperience.validation.maxfiles')
    }
    return true
  }

  return (
    <CandidateSection
      title={t('jobs.professionalexperience.title')}
      example={t('jobs.professionalexperience.example')}
      description={t('jobs.professionalexperience.description')}
    >
      <Box>
        <Controller
          name="workExperience"
          control={control}
          rules={{
            validate: () => validateWorkExperience(candidate.workExperience)
          }}
          render={() => (
            <Box mt="xs">
              <FileUpload
                files={candidate.workExperience.map((file: DB.CandidateDocument) => ({ id: file.documentId, fileName: file.fileName }))}
                uploadFiles={uploadFiles}
                deleteFile={deleteFile}
              />
            </Box>
          )}
        />

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