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

import { useToggle } from 'ahooks'
import {
  CalendarIcon,
  SearchIcon,
  CopyIcon,
  CopyPlusIcon,
  Trash2Icon,
  PlusIcon
} from 'lucide-react'
import { Link } from 'react-router'
import { Controller, useFieldArray, useForm } from 'react-hook-form'
import { Fragment, useState } from 'react'
import { format } from 'date-fns'
import { ptBR } from 'react-day-picker/locale'

import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from '@repo/ui/components/ui/breadcrumb'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText
} from '@repo/ui/components/ui/input-group'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from '@repo/ui/components/ui/card'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { Input } from '@repo/ui/components/ui/input'
import { Button } from '@repo/ui/components/ui/button'
import { Separator } from '@repo/ui/components/ui/separator'
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from '@repo/ui/components/ui/popover'
import { Label } from '@repo/ui/components/ui/label'
import { Calendar } from '@repo/ui/components/ui/calendar'
import { data } from 'react-router'

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Adicionar matrícula' }]
}

export default function Route({}: Route.ComponentProps) {
  const form = useForm({ defaultValues: { enrollments: [{}] } })
  const { formState, control, handleSubmit, getValues } = form
  const { fields, insert, remove, append } = useFieldArray({
    control,
    name: 'enrollments'
  })

  const onSubmit = async (data) => {
    console.log(data)
  }

  const duplicateRow = (index: number, times: number = 1) => {
    const values = getValues(`enrollments.${index}`)
    Array.from({ length: times }, (_, i) => {
      insert(index + 1 + i, values)
    })
  }

  return (
    <div className="space-y-2.5">
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink asChild>
              <Link to="../enrollments">Matrículas</Link>
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>Adicionar matrícula</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      <form
        onSubmit={handleSubmit(onSubmit)}
        className="lg:max-w-4xl mx-auto space-y-2.5"
      >
        <Card>
          <CardHeader>
            <CardTitle className="text-2xl">Adicionar matrícula</CardTitle>
            <CardDescription>
              Siga os passos abaixo para adicionar uma nova matrícula
            </CardDescription>
          </CardHeader>

          <CardContent className="space-y-4">
            <div className="grid lg:grid-cols-[repeat(3,1fr)_auto] w-full gap-1.5">
              {/* Header */}
              <>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Colaborador
                </div>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Curso
                </div>
                <div className="max-lg:hidden text-foreground font-medium text-sm">
                  Matriculado em
                </div>
                <div></div>
              </>

              {/* Rows */}
              <>
                {fields.map((field, index) => (
                  <Fragment key={field.id}>
                    {index >= 1 && <div className="h-2.5 lg:hidden"></div>}

                    <InputGroup>
                      <InputGroupInput placeholder="Search..." />
                      <InputGroupAddon>
                        <SearchIcon />
                      </InputGroupAddon>
                    </InputGroup>

                    <InputGroup>
                      <InputGroupInput placeholder="Search..." />
                      <InputGroupAddon>
                        <SearchIcon />
                      </InputGroupAddon>
                    </InputGroup>

                    <Controller
                      control={control}
                      name={`enrollments.${index}.scheduled_for`}
                      render={({ field: { value, onChange } }) => (
                        <ScheduledForInput value={value} onChange={onChange} />
                      )}
                    />

                    {/* Action */}
                    <div className="flex gap-1.5">
                      <Button
                        tabIndex={-1}
                        variant="outline"
                        className="cursor-pointer"
                        onClick={() => duplicateRow(index)}
                        title="Duplicar linha"
                      >
                        <CopyIcon />
                      </Button>

                      <DuplicateRowMultipleTimes
                        index={index}
                        duplicateRow={duplicateRow}
                      />

                      <Button
                        tabIndex={-1}
                        variant="destructive"
                        className="cursor-pointer"
                        disabled={fields.length == 1}
                        onClick={() => remove(index)}
                      >
                        <Trash2Icon />
                      </Button>
                    </div>
                  </Fragment>
                ))}
              </>
            </div>

            <Button
              type="button"
              onClick={() => append({})}
              className="cursor-pointer"
              variant="outline"
              size="sm"
            >
              <PlusIcon /> Adicionar
            </Button>

            <Separator />

            <Button
              type="submit"
              className="cursor-pointer"
              disabled={formState.isSubmitting}
            >
              {formState.isSubmitting && <Spinner />}
              Continuar
            </Button>
          </CardContent>
        </Card>
      </form>
    </div>
  )
}

function ScheduledForInput({ value, onChange }) {
  const today = new Date()
  const [open, { toggle, set }] = useToggle()
  const [selected, setDate] = useState<Date | undefined>(value)
  const displayValue = !selected
    ? 'Imediatamente'
    : format(selected, 'dd/MM/yyyy')

  return (
    <Popover open={open} onOpenChange={toggle}>
      <PopoverTrigger asChild>
        <InputGroup>
          <InputGroupInput readOnly value={displayValue} />
          <InputGroupAddon>
            <CalendarIcon />
          </InputGroupAddon>
        </InputGroup>
      </PopoverTrigger>
      <PopoverContent className="w-full p-0" align="start">
        <Calendar
          mode="single"
          selected={selected}
          onSelect={(date: Date) => {
            setDate(date)
            onChange?.(date)
            set(false)
          }}
          disabled={{ before: today }}
          startMonth={new Date(today.getFullYear(), 0)}
          endMonth={new Date(today.getFullYear() + 3, 11)}
          captionLayout="dropdown"
          locale={ptBR}
        />
      </PopoverContent>
    </Popover>
  )
}

function DuplicateRowMultipleTimes({
  index,
  duplicateRow
}: {
  index: number
  duplicateRow: (index: number, times: number) => void
}) {
  const [open, { toggle, set }] = useToggle()

  return (
    <Popover open={open} onOpenChange={toggle}>
      <PopoverTrigger asChild>
        <Button
          tabIndex={-1}
          variant="outline"
          className="cursor-pointer"
          title="Duplicar várias vezes"
        >
          <CopyPlusIcon />
        </Button>
      </PopoverTrigger>

      <PopoverContent align="end" className="w-80">
        <form
          onSubmit={(e) => {
            e.stopPropagation()
            e.preventDefault()
            const formData = new FormData(e.currentTarget)
            const times = parseInt(formData.get('quantity') as string)
            duplicateRow(index, times)
            set(false)
          }}
        >
          <div className="space-y-2.5">
            <h4 className="leading-none font-medium">Duplicar várias vezes</h4>
            <p className="text-muted-foreground text-sm">
              Duplique o curso desta linha na quantidade desejada para agilizar
              o preenchimento.
            </p>

            <div className="grid gap-2">
              <div className="grid grid-cols-3 items-center gap-4">
                <Label htmlFor="quantity">Quantidade</Label>
                <Input
                  id="quantity"
                  name="quantity"
                  type="number"
                  defaultValue="2"
                  min="2"
                  max="100"
                  className="col-span-2 "
                />
              </div>
            </div>

            <div className="flex justify-end">
              <Button type="submit">Duplicar</Button>
            </div>
          </div>
        </form>
      </PopoverContent>
    </Popover>
  )
}
