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

export const Route = createFileRoute('/_authenticated/accounts/$accountId/')({
  component: AccountOverviewPage,
})

function AccountOverviewPage() {
  const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/' })
  const queryClient = useQueryClient()
  const { data: account } = useQuery(accountDetailOptions(accountId))

  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => accountMutations.update(accountId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: accountKeys.detail(accountId) })
      toast.success('Account updated')
    },
    onError: (err) => {
      toast.error(err.message)
    },
  })

  if (!account) return null

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold">Edit Account</h2>
      <AccountForm
        defaultValues={account}
        onSubmit={mutation.mutate}
        loading={mutation.isPending}
      />
    </div>
  )
}
