import { createFileRoute, Link } from '@tanstack/react-router'
import { RequireAuth } from '../auth'
import { Container, Stack, Title, Text, Card, Group, Badge, Button } from '@pikku/mantine/core'
import { m, mKey } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { asI18n } from '@pikku/react'
import { usePikkuQuery } from '@germantax/functions-sdk/pikku/api.gen'

function PortfolioPage() {
  useLocale()
  const list = usePikkuQuery('listMyCompanies', undefined as never)
  return (
    <Container size="lg" py="xl">
      <Stack gap="md">
        <Title order={2}>{m.app_nav_portfolio()}</Title>
        {list.data && list.data.length === 0 && <Text c="dimmed">{m.app_companies_empty()}</Text>}
        <Stack gap="sm">
          {list.data?.map((c) => (
            <Card key={c.companyId} withBorder radius="md" p="md">
              <Group justify="space-between">
                <Stack gap={2}>
                  <Title order={5}>{asI18n(c.name)}</Title>
                  {c.registryNo && <Text size="xs" c="dimmed">{asI18n(c.registryNo)}</Text>}
                </Stack>
                <Group>
                  <Badge>{mKey(`app.companies.rolesEnum.${c.role}`)}</Badge>
                  <Button component={Link} to="/companies/$companyId" params={{ companyId: c.companyId } as any} size="xs" variant="light">
                    {m.app_companies_open()}
                  </Button>
                </Group>
              </Group>
            </Card>
          ))}
        </Stack>
      </Stack>
    </Container>
  )
}

function PortfolioPageWrapper() {
  return (
    <RequireAuth>
      <PortfolioPage />
    </RequireAuth>
  )
}

export const Route = createFileRoute('/portfolio')({
  component: PortfolioPageWrapper,
})
