import { useToggle } from 'ahooks'
import { PencilIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import valid from 'card-validator'

import { Currency } from '@repo/ui/components/currency'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow
} from '@repo/ui/components/ui/table'
import {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemGroup,
  ItemTitle
} from '@repo/ui/components/ui/item'
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@repo/ui/components/ui/dialog'

import { useWizard } from '@/components/wizard'
import { type WizardState } from './route'
import { applyDiscount } from './discount'
import { paymentMethods } from '@repo/ui/routes/orders/data'

type ReviewProps = {
  state: WizardState
  onSubmit: (value: WizardState) => void | Promise<void>
}

export function Review({ state, onSubmit }: ReviewProps) {
  const wizard = useWizard()
  const [loading, { set }] = useToggle()
  const { coupon, items } = state || { items: [], coupon: {} }
  const subtotal =
    items?.reduce(
      (acc, { course, quantity }) =>
        acc +
        (course?.unit_price || 0) *
          (Number.isFinite(quantity) && quantity > 0 ? quantity : 1),
      0
    ) || 0
  const discount = coupon
    ? applyDiscount(subtotal, coupon.amount, coupon.type) * -1
    : 0
  const total = subtotal > 0 ? subtotal + discount : 0

  return (
    <>
      <Address {...state} />

      <form
        onSubmit={async (e) => {
          e.preventDefault()
          set(true)
          await onSubmit(state)
        }}
        className="space-y-4"
      >
        <Table className="pointer-events-none">
          <TableHeader>
            <TableRow>
              <TableHead>Curso</TableHead>
              <TableHead>Quantidade</TableHead>
              <TableHead>Valor unit.</TableHead>
              <TableHead>Total</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items?.map(({ course, quantity }, index) => {
              return (
                <TableRow key={index}>
                  <TableCell>{course.name}</TableCell>
                  <TableCell>{quantity}</TableCell>
                  <TableCell>
                    <Currency>{course.unit_price}</Currency>
                  </TableCell>
                  <TableCell>
                    <Currency>{course.unit_price * quantity}</Currency>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
          <TableFooter>
            <TableRow>
              <TableCell className="text-right" colSpan={3}>
                Subtotal
              </TableCell>
              <TableCell>
                <Currency>{subtotal}</Currency>
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell className="text-right" colSpan={3}>
                Descontos
              </TableCell>
              <TableCell>
                <Currency>{discount}</Currency>
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell className="text-right" colSpan={3}>
                Total
              </TableCell>
              <TableCell>
                <Currency>{total}</Currency>
              </TableCell>
            </TableRow>
          </TableFooter>
        </Table>

        <Separator />

        <div className="flex justify-between gap-4 *:cursor-pointer">
          <Button
            type="button"
            variant="link"
            className="text-black dark:text-white"
            onClick={() => wizard('payment')}
            tabIndex={-1}
          >
            Voltar
          </Button>

          <Button type="submit" disabled={loading}>
            {loading && <Spinner />}
            Pagar <Currency>{total}</Currency>
          </Button>
        </div>
      </form>
    </>
  )
}

export function Address({ payment_method, credit_card }: WizardState) {
  const numberValidation = valid.number(credit_card?.number)
  // console.log(numberValidation)

  return (
    <ItemGroup className="grid lg:grid-cols-2 gap-4">
      <Item variant="outline" className="items-start">
        <ItemContent>
          <ItemTitle>Endereço de cobrança</ItemTitle>
          <ul className="text-muted-foreground text-sm leading-normal font-normal text-balance">
            Rua Monsenhor Ivo Zanlorenzi, nº 5190, ap 1802
            <br />
            Cidade Industrial
            <br />
            Curitiba, Paraná
            <br />
            81280-350
          </ul>
        </ItemContent>
        <ItemActions>
          <DialogDemo />
        </ItemActions>
      </Item>

      <Item variant="outline" className="items-start">
        <ItemContent>
          <ItemTitle>Forma de pagamento</ItemTitle>
          <ItemDescription>
            {payment_method ? paymentMethods[payment_method] : payment_method}
            {credit_card ? (
              <>
                <br />
                {numberValidation.card?.niceType} ****{' '}
                {credit_card.number.slice(-4)}
              </>
            ) : null}
          </ItemDescription>
        </ItemContent>
      </Item>
    </ItemGroup>
  )
}

export function DialogDemo() {
  const form = useForm()
  const { handleSubmit } = form

  const onSubmit = async () => {}

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Dialog>
        <DialogTrigger asChild>
          <Button
            variant="ghost"
            type="button"
            className="text-muted-foreground cursor-pointer"
            size="icon-sm"
          >
            <PencilIcon />
            <span className="sr-only">Editar endereço</span>
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>Editar endereço</DialogTitle>
            <DialogDescription>
              Este endereço será utilizado para a emissão da NFS-e.
            </DialogDescription>
          </DialogHeader>

          <DialogFooter className="*:cursor-pointer">
            <DialogClose asChild>
              <Button
                variant="link"
                type="button"
                className="text-black dark:text-white"
              >
                Cancel
              </Button>
            </DialogClose>

            <Button type="submit">Atualizar endereço</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </form>
  )
}
