import type { Route } from './+types/route'

import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'

import { Button } from '@repo/ui/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from '@repo/ui/components/ui/card'
import { FieldSet } from '@repo/ui/components/ui/field'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@repo/ui/components/ui/form'
import { Input } from '@repo/ui/components/ui/input'
import {
  NativeSelect,
  NativeSelectOption
} from '@repo/ui/components/ui/native-select'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { HttpMethod, request as req } from '@repo/util/request'
import { useFetcher, useOutletContext } from 'react-router'
import type { Org } from '../_app.orgs.$id/data'

const formSchema = z.object({
  due_days: z
    .number({ error: 'Deve estar entre 1 e 90' })
    .min(1, { error: 'Deve ser igual 1 ou maior' })
    .max(90, { error: 'Deve ser menor ou igual a 90' }),
  payment_method: z.enum(['BANK_SLIP', 'MANUAL'], {
    error: 'Selecione uma opção'
  })
})

type Schema = z.infer<typeof formSchema>

export async function action({ params, request, context }: Route.ActionArgs) {
  const r = await req({
    url: `orgs/${params.id}/billing`,
    headers: new Headers({ 'Content-Type': 'application/json' }),
    method: HttpMethod.PUT,
    body: JSON.stringify(await request.json()),
    request,
    context
  })

  return { ok: r.ok }
}

export default function Route({}: Route.ComponentProps) {
  const fetcher = useFetcher()
  const { org } = useOutletContext() as { org: Org }
  const form = useForm<Schema>({
    resolver: zodResolver(formSchema),
    defaultValues: org?.billing
  })
  const { handleSubmit, control, formState } = form
  const onSubmit = async (data: Schema) => {
    toast.success('As condições de pagamento foram atualizadas')

    fetcher.submit(JSON.stringify(data), {
      method: 'PUT',
      encType: 'application/json'
    })
  }

  return (
    <Form {...form}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Card>
          <CardHeader>
            <CardTitle className="font-semibold text-lg">
              Condições de pagamento
            </CardTitle>
            <CardDescription>
              Estas condições serão usadas automaticamente sempre que um
              pagamento for gerado.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <FieldSet>
              <FormField
                control={control}
                name="due_days"
                render={({ field: { onChange, ...field } }) => (
                  <FormItem>
                    <FormLabel>
                      Prazo para vencimento{' '}
                      <span className="text-xs text-white/30 font-normal">
                        (em dias)
                      </span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={1}
                        max={90}
                        onChange={(e) => onChange(Number(e.target.value))}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={control}
                name="payment_method"
                render={({ field }) => (
                  <FormItem className="*:w-full">
                    <FormLabel>Forma de pagamento</FormLabel>
                    <FormControl>
                      <NativeSelect {...field}>
                        <NativeSelectOption value="">
                          Selecione
                        </NativeSelectOption>
                        <NativeSelectOption value="BANK_SLIP">
                          Boleto bancário
                        </NativeSelectOption>
                        <NativeSelectOption value="MANUAL">
                          Depósito bancário
                        </NativeSelectOption>
                        <NativeSelectOption value="PIX" disabled>
                          Pix
                        </NativeSelectOption>
                        <NativeSelectOption value="CREDIT_CARD" disabled>
                          Cartão de crédito
                        </NativeSelectOption>
                      </NativeSelect>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </FieldSet>

            <Button
              type="submit"
              className="cursor-pointer"
              disabled={formState.isSubmitting}
            >
              {formState.isSubmitting ? <Spinner /> : null}
              Atualizar condições
            </Button>
          </CardContent>
        </Card>
      </form>
    </Form>
  )
}
