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

import { useToggle } from 'ahooks'

import {
  Card,
  CardContent,
  CardHeader,
  CardDescription,
  CardTitle
} from '@repo/ui/components/ui/card'
import { Switch } from '@repo/ui/components/ui/switch'
import { createSearch } from '@repo/util/meili'
import { cloudflareContext } from '@repo/auth/context'
import { Label } from '@repo/ui/components/ui/label'

import { Assigned } from './assigned'
import { Bulk } from './bulk'
import type { Course } from '../_.$orgid.enrollments.add/data'

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

export async function loader({ params, context, request }: Route.LoaderArgs) {
  const cloudflare = context.get(cloudflareContext)
  const courses = createSearch<Course>({
    index: 'saladeaula_courses',
    sort: ['created_at:desc'],
    filter: 'unlisted NOT EXISTS',
    hitsPerPage: 100,
    env: cloudflare.env
  })

  return { courses }
}

export default function Route({
  loaderData: { courses }
}: Route.ComponentProps) {
  const [state, { toggle }] = useToggle('bulk', 'assigned')

  return (
    <div className="lg:max-w-4xl mx-auto space-y-2.5">
      <Card>
        <CardHeader>
          <CardTitle className="text-2xl">Comprar matrículas</CardTitle>
          <CardDescription>
            Siga os passos abaixo para comprar novas matrículas.
          </CardDescription>
        </CardHeader>

        <CardContent className="space-y-4">
          <Label
            className="flex flex-row items-center justify-between
                       bg-accent/50 rounded-lg border p-4 cursor-pointer
                       dark:has-aria-checked:border-blue-900
                       dark:has-aria-checked:bg-blue-950"
          >
            <div className="grid gap-1.5 font-normal">
              <p className="text-sm leading-none font-medium">
                Adicionar colaboradores
              </p>
              <p className="text-muted-foreground text-sm">
                Você pode adicionar agora os colaboradores que irão fazer o
                curso ou deixar para fazer isso depois.
              </p>
            </div>
            <Switch
              checked={state === 'assigned'}
              onCheckedChange={toggle}
              className="cursor-pointer"
            />
          </Label>

          {state == 'assigned' ? (
            <Assigned courses={courses} />
          ) : (
            <Bulk courses={courses} />
          )}
        </CardContent>
      </Card>
    </div>
  )
}
