import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { RequireAuth } from '../../../../auth'
import {
  Alert,
  Button,
  Card,
  Container,
  NumberInput,
  Select,
  Stack,
  Text,
  Textarea,
  TextInput,
  Title,
} from '@pikku/mantine/core'
import { useState, useMemo } from 'react'
import { m } from '@/i18n/messages'
import { useLocale, getLocale } from '@/i18n/config'
import { asI18n } from '@pikku/react'
import { usePikkuQuery, usePikkuMutation } from '@germantax/functions-sdk/pikku/api.gen'

function NewResolutionPage() {
  const { companyId } = Route.useParams()
  useLocale()
  const navigate = useNavigate()
  const templates = usePikkuQuery('listResolutionTemplates', undefined as never)
  const create = usePikkuMutation('createResolution', {
    onSuccess: ({ resolutionId }) => {
      navigate({
        to: '/companies/$companyId/resolutions/$resolutionId',
        params: { companyId, resolutionId },
      })
    },
  })

  const [templateKey, setTemplateKey] = useState<string | null>(null)
  const [title, setTitle] = useState('')
  const [values, setValues] = useState<Record<string, unknown>>({})

  const template = useMemo(
    () => templates.data?.find((t) => t.key === templateKey),
    [templates.data, templateKey],
  )
  const lang = getLocale()?.startsWith('de') ? 'de' : 'en'
  const labelOf = (f: { labelDe: string; labelEn: string }) => (lang === 'de' ? f.labelDe : f.labelEn)

  return (
    <Container size="md" py="xl">
      <Stack gap="xl">
        <Title order={2}>{m.app_resolutions_new()}</Title>
        <Card withBorder radius="md" p="md">
          <Stack gap="sm">
            <Select
              label={m.app_resolutions_select_template()}
              data={
                templates.data?.map((tpl) => ({ value: tpl.key, label: tpl.titleDe })) ?? []
              }
              value={templateKey}
              onChange={(v) => {
                setTemplateKey(v)
                setValues({})
                const tpl = templates.data?.find((x) => x.key === v)
                if (tpl) setTitle(tpl.titleDe)
              }}
            />
            <TextInput
              label={m.app_resolutions_resolution_title()}
              value={title}
              onChange={(e) => setTitle(e.currentTarget.value)}
            />

            {template && (
              <Stack gap="xs">
                <Text fw={600}>{m.app_resolutions_fields()}</Text>
                {template.fields.map((f) => {
                  const v = values[f.key]
                  if (f.type === 'textarea') {
                    return (
                      <Textarea
                        key={f.key}
                        label={asI18n(labelOf(f))}
                        required={f.required}
                        value={(v as string) ?? ''}
                        onChange={(e) => setValues({ ...values, [f.key]: e.currentTarget.value })}
                      />
                    )
                  }
                  if (f.type === 'number' || f.type === 'currency') {
                    return (
                      <NumberInput
                        key={f.key}
                        label={asI18n(labelOf(f))}
                        required={f.required}
                        value={typeof v === 'number' ? v : ''}
                        onChange={(val) => setValues({ ...values, [f.key]: typeof val === 'number' ? val : 0 })}
                        min={0}
                        decimalScale={f.type === 'currency' ? 2 : 0}
                      />
                    )
                  }
                  return (
                    <TextInput
                      key={f.key}
                      type={f.type === 'date' ? 'date' : 'text'}
                      label={asI18n(labelOf(f))}
                      required={f.required}
                      value={(v as string) ?? ''}
                      onChange={(e) => setValues({ ...values, [f.key]: e.currentTarget.value })}
                    />
                  )
                })}
              </Stack>
            )}

            {create.error && <Alert color="red">{asI18n(String(create.error.message))}</Alert>}

            <Button
              disabled={!templateKey || !title}
              loading={create.isPending}
              onClick={() =>
                templateKey &&
                create.mutate({
                  companyId,
                  templateKey,
                  title,
                  fieldValues: values,
                })
              }
            >
              {m.app_resolutions_create()}
            </Button>
          </Stack>
        </Card>
      </Stack>
    </Container>
  )
}

export const Route = createFileRoute('/companies/$companyId/resolutions/new')({
  component: () => <RequireAuth><NewResolutionPage /></RequireAuth>,
})
