import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { RequireAuth } from '../../auth'
import {
  Alert,
  Badge,
  Box,
  Button,
  Card,
  Container,
  Group,
  Modal,
  NumberInput,
  Select,
  SimpleGrid,
  Skeleton,
  Stack,
  Text,
  TextInput,
  ThemeIcon,
  Title,
} from '@pikku/mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { useEffect, useState } from 'react'
import { m, mKey } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { asI18n } from '@pikku/react'
import { Building2, Plus, AlertCircle, CheckCircle2 } from 'lucide-react'
import { usePikkuQuery, usePikkuMutation } from '@germantax/functions-sdk/pikku/api.gen'

const MONTHS = [
  '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
] as const

function daysInMonth(month: string): number {
  const m = Number(month)
  if (!m) return 31
  if ([4, 6, 9, 11].includes(m)) return 30
  if (m === 2) return 29
  return 31
}

type FormState = {
  name: string
  registryNo: string
  addressLine1: string
  addressLine2: string
  postcode: string
  town: string
  country: string
  totalShares: number | ''
  fiscalMonth: string
  fiscalDay: string
}

const EMPTY_FORM: FormState = {
  name: '',
  registryNo: '',
  addressLine1: '',
  addressLine2: '',
  postcode: '',
  town: '',
  country: '',
  totalShares: '',
  fiscalMonth: '',
  fiscalDay: '',
}

type FormErrorKey = keyof FormState | 'fiscalYearEnd'

function CompanyCard({
  company,
  onOpen,
}: {
  company: {
    companyId: string
    name: string
    registryNo?: string | null
    town?: string | null
    country?: string | null
    totalShares: number
    assignedShares: number
    fiscalYearEnd?: string | null
    role: string
  }
  onOpen: (id: string) => void
}) {
  useLocale()
  const location = [company.town, company.country].filter(Boolean).join(', ')
  return (
    <Card
      withBorder
      radius="md"
      p="md"
      role="button"
      tabIndex={0}
      onClick={() => onOpen(company.companyId)}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault()
          onOpen(company.companyId)
        }
      }}
      style={{
        cursor: 'pointer',
        transition: 'transform 150ms ease, box-shadow 150ms ease',
        height: '100%',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.transform = 'translateY(-2px)'
        e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = 'translateY(0)'
        e.currentTarget.style.boxShadow = ''
      }}
      aria-label={`${company.name} — ${mKey(`app.companies.rolesEnum.${company.role}` as any) /* TODO i18n typed dynamic key */}`}
    >
      <Stack gap="xs" h="100%" justify="space-between">
        <Stack gap={6}>
          <Group justify="space-between" wrap="nowrap" align="flex-start">
            <Title order={5} style={{ wordBreak: 'break-word' }}>
              {asI18n(company.name)}
            </Title>
            <Badge variant="light" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
              {mKey(`app.companies.rolesEnum.${company.role}` as any) /* TODO i18n typed dynamic key */}
            </Badge>
          </Group>
          {company.registryNo && (
            <Text size="sm" c="dimmed">
              {asI18n(company.registryNo)}
            </Text>
          )}
          {location && (
            <Text size="sm" c="dimmed" lineClamp={1}>
              {asI18n(location)}
            </Text>
          )}
        </Stack>
        <Group gap="xs" mt="xs" wrap="wrap">
          {company.totalShares > 0 && (
            <Badge variant="default" size="sm" radius="sm">
              {m.app_companies_shares_assigned({
                assigned: company.assignedShares,
                total: company.totalShares,
              })}
            </Badge>
          )}
          {company.fiscalYearEnd && (
            <Badge variant="default" size="sm" radius="sm">
              {asI18n(`${m.app_companies_fiscal_year_end_short()}: ${company.fiscalYearEnd}`)}
            </Badge>
          )}
        </Group>
      </Stack>
    </Card>
  )
}

function CompanyFormFields({
  form,
  setForm,
  errors,
  idPrefix,
}: {
  form: FormState
  setForm: (next: FormState) => void
  errors: Partial<Record<FormErrorKey, string>>
  idPrefix: string
}) {
  useLocale()
  const monthOptions = MONTHS.map((m) => ({
    value: m,
    label: mKey(`app.companies.months.${m}`),
  }))
  const dayOptions = Array.from({ length: daysInMonth(form.fiscalMonth) }, (_, i) => {
    const v = String(i + 1).padStart(2, '0')
    return { value: v, label: v }
  })

  return (
    <Stack gap="sm">
      <TextInput
        id={`${idPrefix}-name`}
        label={m.app_companies_name()}
        value={form.name}
        onChange={(e) => setForm({ ...form, name: e.currentTarget.value })}
        error={errors.name}
        required
        autoFocus
      />
      <TextInput
        id={`${idPrefix}-registryNo`}
        label={m.app_companies_registry_no()}
        value={form.registryNo}
        onChange={(e) => setForm({ ...form, registryNo: e.currentTarget.value })}
      />
      <TextInput
        id={`${idPrefix}-addressLine1`}
        label={m.app_companies_address_line1()}
        value={form.addressLine1}
        onChange={(e) => setForm({ ...form, addressLine1: e.currentTarget.value })}
      />
      <TextInput
        id={`${idPrefix}-addressLine2`}
        label={m.app_companies_address_line2_optional()}
        value={form.addressLine2}
        onChange={(e) => setForm({ ...form, addressLine2: e.currentTarget.value })}
      />
      <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
        <TextInput
          id={`${idPrefix}-postcode`}
          label={m.app_companies_postcode()}
          value={form.postcode}
          onChange={(e) => setForm({ ...form, postcode: e.currentTarget.value })}
        />
        <TextInput
          id={`${idPrefix}-town`}
          label={m.app_companies_town()}
          value={form.town}
          onChange={(e) => setForm({ ...form, town: e.currentTarget.value })}
        />
      </SimpleGrid>
      <TextInput
        id={`${idPrefix}-country`}
        label={m.app_companies_country()}
        value={form.country}
        onChange={(e) => setForm({ ...form, country: e.currentTarget.value })}
      />
      <NumberInput
        id={`${idPrefix}-totalShares`}
        label={m.app_companies_total_shares()}
        description={m.app_companies_total_shares_hint()}
        value={form.totalShares}
        onChange={(v) =>
          setForm({ ...form, totalShares: typeof v === 'number' ? v : '' })
        }
        min={0}
        step={1}
        allowDecimal={false}
        error={errors.totalShares}
        required
      />
      <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
        <Select
          id={`${idPrefix}-fiscalMonth`}
          label={m.app_companies_fiscal_month()}
          placeholder={m.app_companies_fiscal_month_placeholder()}
          data={monthOptions}
          value={form.fiscalMonth || null}
          onChange={(v) => {
            const month = v ?? ''
            const max = daysInMonth(month)
            const day = form.fiscalDay && Number(form.fiscalDay) > max ? '' : form.fiscalDay
            setForm({ ...form, fiscalMonth: month, fiscalDay: day })
          }}
          error={errors.fiscalYearEnd}
          clearable
        />
        <Select
          id={`${idPrefix}-fiscalDay`}
          label={m.app_companies_fiscal_day()}
          placeholder={m.app_companies_fiscal_day_placeholder()}
          data={dayOptions}
          value={form.fiscalDay || null}
          onChange={(v) => setForm({ ...form, fiscalDay: v ?? '' })}
          disabled={!form.fiscalMonth}
          clearable
        />
      </SimpleGrid>
    </Stack>
  )
}

const FISCAL_RE = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/

function CompaniesPage() {
  useLocale()
  const navigate = useNavigate()
  const list = usePikkuQuery('listMyCompanies', undefined as never)
  const [modalOpened, { open: openModal, close: closeModal }] = useDisclosure(false)
  const [form, setForm] = useState<FormState>(EMPTY_FORM)
  const [errors, setErrors] = useState<Partial<Record<FormErrorKey, string>>>({})
  const [successName, setSuccessName] = useState<string | null>(null)
  const [submitError, setSubmitError] = useState<string | null>(null)

  const create = usePikkuMutation('createCompany', {
    onSuccess: (_data, vars) => {
      setForm(EMPTY_FORM)
      setErrors({})
      setSubmitError(null)
      setSuccessName(vars?.name ?? null)
      closeModal()
      list.refetch()
    },
    onError: (err: unknown) => {
      const msg = err instanceof Error ? err.message : String(err)
      setSubmitError(msg)
    },
  })

  useEffect(() => {
    if (!successName) return
    const t = setTimeout(() => setSuccessName(null), 5000)
    return () => clearTimeout(t)
  }, [successName])

  const validate = (f: FormState) => {
    const next: Partial<Record<FormErrorKey, string>> = {}
    if (!f.name.trim()) next.name = m.app_companies_errors_name_required()
    if (typeof f.totalShares !== 'number' || f.totalShares < 0 || !Number.isInteger(f.totalShares)) {
      next.totalShares = m.app_companies_errors_total_shares_invalid()
    }
    const fy = f.fiscalMonth && f.fiscalDay ? `${f.fiscalMonth}-${f.fiscalDay}` : ''
    if (f.fiscalMonth && !f.fiscalDay) {
      next.fiscalYearEnd = m.app_companies_errors_fiscal_day_required()
    } else if (!f.fiscalMonth && f.fiscalDay) {
      next.fiscalYearEnd = m.app_companies_errors_fiscal_month_required()
    } else if (fy && !FISCAL_RE.test(fy)) {
      next.fiscalYearEnd = m.app_companies_errors_fiscal_invalid()
    }
    return next
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const v = validate(form)
    setErrors(v)
    if (Object.keys(v).length > 0) return
    setSubmitError(null)
    const fiscalYearEnd =
      form.fiscalMonth && form.fiscalDay ? `${form.fiscalMonth}-${form.fiscalDay}` : undefined
    create.mutate({
      name: form.name.trim(),
      registryNo: form.registryNo.trim() || undefined,
      addressLine1: form.addressLine1.trim() || undefined,
      addressLine2: form.addressLine2.trim() || undefined,
      postcode: form.postcode.trim() || undefined,
      town: form.town.trim() || undefined,
      country: form.country.trim() || undefined,
      totalShares: typeof form.totalShares === 'number' ? form.totalShares : 0,
      fiscalYearEnd,
    })
  }

  const handleOpenCompany = (id: string) => {
    navigate({ to: '/companies/$companyId', params: { companyId: id } as never })
  }

  const handleOpenModal = () => {
    setErrors({})
    setSubmitError(null)
    openModal()
  }

  const isLoading = list.isLoading
  const companies = list.data ?? []
  const isEmpty = !isLoading && !list.error && companies.length === 0

  return (
    <Container size="lg" py="xl">
      <Stack gap="lg">
        <Group justify="space-between" align="flex-end" wrap="wrap">
          <Stack gap={4}>
            <Title order={2}>{m.app_companies_list_title()}</Title>
            {!isLoading && !list.error && companies.length > 0 && (
              <Text c="dimmed" size="sm">
                {m.app_companies_count_subtitle({ count: companies.length })}
              </Text>
            )}
          </Stack>
          {companies.length > 0 && (
            <Button
              leftSection={<Plus size={16} aria-hidden="true" />}
              onClick={handleOpenModal}
            >
              {m.app_companies_new_company()}
            </Button>
          )}
        </Group>

        {successName && (
          <Alert
            role="status"
            color="green"
            variant="light"
            icon={<CheckCircle2 size={18} aria-hidden="true" />}
            withCloseButton
            onClose={() => setSuccessName(null)}
            title={m.app_companies_success_title()}
          >
            {m.app_companies_success_message({ name: successName })}
          </Alert>
        )}

        {list.error && (
          <Alert
            role="alert"
            color="red"
            variant="light"
            icon={<AlertCircle size={18} aria-hidden="true" />}
            title={m.app_companies_errors_load_title()}
          >
            {asI18n(String(list.error.message))}
          </Alert>
        )}

        {isLoading && (
          <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="md">
            {Array.from({ length: 6 }).map((_, i) => (
              <Card key={i} withBorder radius="md" p="md">
                <Stack gap="xs">
                  <Group justify="space-between" wrap="nowrap">
                    <Skeleton height={20} width="60%" />
                    <Skeleton height={20} width={80} radius="xl" />
                  </Group>
                  <Skeleton height={12} width="40%" mt="xs" />
                  <Skeleton height={12} width="80%" />
                  <Skeleton height={20} width={110} radius="sm" mt="md" />
                </Stack>
              </Card>
            ))}
          </SimpleGrid>
        )}

        {isEmpty && (
          <Card withBorder radius="md" p="xl">
            <Stack align="center" gap="md" py="lg">
              <ThemeIcon size={64} radius="xl" variant="light" color="blue">
                <Building2 size={32} aria-hidden="true" />
              </ThemeIcon>
              <Stack gap={4} align="center">
                <Title order={3} ta="center">
                  {m.app_companies_empty_state_title()}
                </Title>
                <Text c="dimmed" ta="center" maw={420}>
                  {m.app_companies_empty_state_description()}
                </Text>
              </Stack>
              <Button
                size="md"
                leftSection={<Plus size={16} aria-hidden="true" />}
                onClick={handleOpenModal}
              >
                {m.app_companies_empty_state_cta()}
              </Button>
            </Stack>
          </Card>
        )}

        {!isLoading && companies.length > 0 && (
          <SimpleGrid cols={{ base: 1, sm: 2, md: 3 }} spacing="md">
            {companies.map((c) => (
              <CompanyCard
                key={c.companyId}
                company={c as any}
                onOpen={handleOpenCompany}
              />
            ))}
          </SimpleGrid>
        )}
      </Stack>

      <Modal
        opened={modalOpened}
        onClose={closeModal}
        title={m.app_companies_create()}
        size="md"
        centered
        overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
      >
        <Box component="form" onSubmit={handleSubmit} noValidate>
          <Stack gap="md">
            {submitError && (
              <Alert
                role="alert"
                color="red"
                variant="light"
                icon={<AlertCircle size={18} aria-hidden="true" />}
                title={m.app_companies_errors_create_title()}
              >
                {asI18n(submitError)}
              </Alert>
            )}
            <CompanyFormFields
              form={form}
              setForm={setForm}
              errors={errors}
              idPrefix="modal"
            />
            <Group justify="flex-end" gap="sm">
              <Button variant="subtle" onClick={closeModal} type="button">
                {m.app_companies_cancel()}
              </Button>
              <Button type="submit" loading={create.isPending}>
                {m.app_companies_create()}
              </Button>
            </Group>
          </Stack>
        </Box>
      </Modal>
    </Container>
  )
}

function CompaniesPageWrapper() {
  return (
    <RequireAuth>
      <CompaniesPage />
    </RequireAuth>
  )
}

export const Route = createFileRoute('/companies/')({
  component: CompaniesPageWrapper,
})
