import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { accountMutations, accountKeys } from '@/api/accounts'
import { memberMutations } from '@/api/members'
import { AccountForm } from '@/components/accounts/account-form'
import { toast } from 'sonner'

export const Route = createFileRoute('/_authenticated/accounts/new')({
  component: NewAccountPage,
})

function NewAccountPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: async (data: Record<string, unknown>) => {
      // Extract member fields
      const memberFirstName = data.memberFirstName as string | undefined
      const memberLastName = data.memberLastName as string | undefined
      const memberEmail = data.memberEmail as string | undefined
      const memberPhone = data.memberPhone as string | undefined
      const memberDateOfBirth = data.memberDateOfBirth as string | undefined
      const memberIsMinor = data.memberIsMinor as boolean | undefined

      // Create account (without member fields)
      const memberKeys = new Set(['memberFirstName', 'memberLastName', 'memberEmail', 'memberPhone', 'memberDateOfBirth', 'memberIsMinor'])
      const accountData: Record<string, unknown> = Object.fromEntries(Object.entries(data).filter(([k]) => !memberKeys.has(k)))

      // Auto-generate account name from member if not provided
      if (!accountData.name && memberFirstName && memberLastName) {
        accountData.name = `${memberFirstName} ${memberLastName} - Account`
      }

      const account = await accountMutations.create(accountData)

      // Create first member if name provided
      if (memberFirstName && memberLastName) {
        await memberMutations.create(account.id, {
          firstName: memberFirstName,
          lastName: memberLastName,
          email: memberEmail || undefined,
          phone: memberPhone || undefined,
          dateOfBirth: memberDateOfBirth || undefined,
          isMinor: memberIsMinor,
        })
      }

      return account
    },
    onSuccess: (account) => {
      queryClient.invalidateQueries({ queryKey: accountKeys.lists() })
      toast.success('Account created')
      navigate({ to: '/accounts/$accountId', params: { accountId: account.id } })
    },
    onError: (err) => {
      toast.error(err.message)
    },
  })

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">New Account</h1>
      <AccountForm onSubmit={mutation.mutate} loading={mutation.isPending} includeFirstMember />
    </div>
  )
}
