import { useState } from 'react'
import {
  Button,
  Text,
  Drawer,
  Stack,
} from '@pikku/mantine/core'
import {
  IconInfoCircle,
  IconBriefcase,
  IconFile,
  IconCircleCheck,
  IconLanguage,
  IconExternalLink,
} from '@tabler/icons-react'
import GetHelp from './GetHelp'
import ConnectWithEmployers from './ConnectWithEmployers'
import CompareOptionsRecognition from './CompareOptionsRecognition'
import { useI18n } from '@/context/i18n-provider'
import { asI18n } from '@pikku/react'
import DocumentsChecklist from './DocumentsChecklist'
import HowToApply from './HowToApply'
import GermanLanguageTips from './GermanLanguageTips'
import ApplicantProfile from './ApplicantProfile'
import { ExpandableSteps, type ExpandableStep } from '@/components/common/ExpandableSteps'
import { useMantineTheme } from '@pikku/mantine/core'
import { NextSteps as NextStepsType } from '@heygermany/sdk'

interface NextStepsProps {
  joinTalentPool: boolean
  nextSteps: NextStepsType | null
  isHelper?: boolean
}

interface NextStepContentProps {
  subtitle?: string
  costs?: string
  textButton?: string
  onButtonClick?: () => void
}

function NextStepContent({ subtitle, costs, textButton, onButtonClick }: NextStepContentProps) {
  const theme = useMantineTheme()

  return (
    <Stack justify='center' align='center' ta='start'>
      {subtitle && (
        <Text
          c="dimmed"
          fz="lg"
          mt="md"
        >
          {asI18n(subtitle)}
        </Text>
      )}
      {costs && (
        <Text
          c={`${theme.colors.gray[8]}`}
          fw={400}
          fz="md"
          mt="md"
          mb="lg"
        >
          {asI18n(costs)}
        </Text>
      )}
      {textButton && onButtonClick && (
        <Button
          leftSection={<IconExternalLink size={24} />}
          size="md"
          onClick={(e) => {
            e.stopPropagation()
            onButtonClick()
          }}
        >
          {asI18n(textButton)}
        </Button>
      )}
    </Stack>
  )
}

export default function NextSteps({ joinTalentPool, nextSteps, isHelper = false }: NextStepsProps) {
  const t = useI18n()
  const [drawerOpened, setDrawerOpened] = useState(false)
  const [drawerTitle, setDrawerTitle] = useState('')
  const [drawerContent, setDrawerContent] = useState<
    'getHelp' | 'connect' | 'documents' | 'apply' | 'compensatory' | 'language'
  >('getHelp')

  // Handle missing next steps data
  if (!nextSteps) {
    console.error('[NextSteps] No next steps data provided from backend')
    return null
  }

  const openDrawer = (contentType: 'getHelp' | 'connect' | 'documents' | 'apply' | 'compensatory' | 'language', title: string) => {
    setDrawerTitle(title)
    setDrawerContent(contentType)
    setDrawerOpened(true)
  }

  // For helpers, only show: gethelp, connect, and conditionally german
  // For others, show all available steps
  const allSteps: ExpandableStep[] = [
    {
      title: nextSteps.gethelp.title,
      icon: <IconInfoCircle size={38} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.gethelp.subtitle}
          costs={nextSteps.gethelp.costs}
          textButton={nextSteps.gethelp.button}
          onButtonClick={() => openDrawer('getHelp', nextSteps.gethelp.title)}
        />
      ),
    },
    {
      title: nextSteps.connect.title,
      icon: <IconBriefcase size={38} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.connect.subtitle}
          costs={nextSteps.connect.costs}
          textButton={joinTalentPool
            ? nextSteps.connect.buttonimprove
            : nextSteps.connect.buttonjoin}
          onButtonClick={() => openDrawer('connect', nextSteps.connect.title)}
        />
      ),
    },
    ...(!isHelper && nextSteps.documents ? [{
      title: nextSteps.documents.title,
      icon: <IconFile size={38} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.documents?.subtitle}
          costs={nextSteps.documents?.costs}
          textButton={nextSteps.documents?.button}
          onButtonClick={() => openDrawer('documents', nextSteps.documents!.title)}
        />
      ),
    }] : []),
    ...(!isHelper && nextSteps.submit ? [{
      title: nextSteps.submit.title,
      icon: <IconFile size={38} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.submit?.subtitle}
          costs={nextSteps.submit?.costs}
          textButton={nextSteps.submit?.button}
          onButtonClick={() => openDrawer('apply', nextSteps.submit!.title)}
        />
      ),
    }] : []),
    ...(!isHelper && nextSteps.compensatory ? [{
      title: nextSteps.compensatory.title,
      icon: <IconCircleCheck size={38} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.compensatory?.subtitle}
          costs={nextSteps.compensatory?.costs}
          textButton={nextSteps.compensatory?.button}
          onButtonClick={() => openDrawer('compensatory', nextSteps.compensatory!.title)}
        />
      ),
    }] : []),
    ...(nextSteps.german ? [{
      title: nextSteps.german.title,
      icon: <IconLanguage size={36} />,
      content: () => (
        <NextStepContent
          subtitle={nextSteps.german?.subtitle}
          costs={nextSteps.german?.costs}
          textButton={nextSteps.german?.button}
          onButtonClick={() => openDrawer('language', nextSteps.german!.title)}
        />
      ),
    }] : []),
  ]

  const renderDrawerContent = () => {
    switch (drawerContent) {
      case 'getHelp':
        return <GetHelp />
      case 'connect':
        return joinTalentPool ? <ApplicantProfile /> : <ConnectWithEmployers />
      case 'documents':
        return (
          <DocumentsChecklist
            openGetHelpDrawer={() => openDrawer('getHelp', nextSteps.gethelp.title)}
          />
        )
      case 'apply':
        return <HowToApply />
      case 'compensatory':
        return <CompareOptionsRecognition />
      case 'language':
        return <GermanLanguageTips />
      default:
        console.error(`[NextSteps] Unknown drawer content type: ${drawerContent}`)
        return (
          <Text c="dimmed" p="md">
            {asI18n('Content not available')}
          </Text>
        )
    }
  }

  return (
    <>
      <ExpandableSteps
        steps={allSteps}
        defaultExpanded={[0]}
        singleExpand={true}
        showTitle={true}
        title={t('jobs.nextsteps.title')}
      />

      <Drawer
        opened={drawerOpened}
        onClose={() => setDrawerOpened(false)}
        title={asI18n(drawerTitle)}
        size="lg"
        position="right"
      >
        {renderDrawerContent()}
      </Drawer>
    </>
  )
}
