import { auth } from '@/auth'
import { db } from '@/lib/db'
import { machines, groups } from '@/lib/db/schema'
import { eq, desc, or, ilike, sql } from 'drizzle-orm'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import Link from 'next/link'
import { Download, Laptop } from 'lucide-react'
import { MachineCard } from '@/components/dashboard/machine-card'
import { MachinesFilter } from '@/components/dashboard/machines-filter'

interface PageProps {
  searchParams: Promise<{ q?: string; tag?: string; group?: string }>
}

export default async function MachinesPage({ searchParams }: PageProps) {
  const session = await auth()
  const { q, tag, group } = await searchParams

  // Build query conditions
  const conditions = [eq(machines.userId, session!.user.id)]
  if (group) conditions.push(eq(machines.groupId, group))

  let machineList = await db
    .select()
    .from(machines)
    .where(conditions.length === 1 ? conditions[0] : sql`${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`)
    .orderBy(desc(machines.isOnline), desc(machines.lastSeen))

  // Text search (filter in JS — avoids complex SQL for small datasets)
  if (q) {
    const lower = q.toLowerCase()
    machineList = machineList.filter(m =>
      m.name.toLowerCase().includes(lower) ||
      (m.hostname ?? '').toLowerCase().includes(lower) ||
      (m.os ?? '').toLowerCase().includes(lower) ||
      (m.ipAddress ?? '').toLowerCase().includes(lower)
    )
  }

  // Tag filter
  if (tag) {
    machineList = machineList.filter(m => m.tags?.includes(tag))
  }

  // Collect all unique tags across machines
  const allTagsSet = new Set<string>()
  machineList.forEach(m => (m.tags ?? []).forEach(t => allTagsSet.add(t)))
  const allTags = [...allTagsSet].sort()

  const onlineCount = machineList.filter(m => m.isOnline).length

  // Fetch groups for group picker and machine card selects
  const groupList = await db.select({ id: groups.id, name: groups.name }).from(groups).orderBy(groups.name)

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold">Machines</h2>
        </div>
        <Button asChild>
          <Link href="/download">
            <Download className="mr-2 h-4 w-4" />
            Download Agent
          </Link>
        </Button>
      </div>

      <MachinesFilter
        allTags={allTags}
        groups={groupList}
        currentSearch={q ?? ''}
        currentTag={tag ?? ''}
        currentGroup={group ?? ''}
        onlineCount={onlineCount}
        totalCount={machineList.length}
      />

      {machineList.length > 0 ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {machineList.map((machine) => (
            <MachineCard key={machine.id} machine={machine} groups={groupList} />
          ))}
        </div>
      ) : (
        <Card className="border-border/50">
          <CardContent className="flex flex-col items-center justify-center py-16">
            <Laptop className="h-12 w-12 text-muted-foreground/30 mb-4" />
            <h3 className="text-lg font-semibold mb-2">
              {q || tag || group ? 'No machines match your filter' : 'No machines yet'}
            </h3>
            <p className="text-muted-foreground text-center mb-6 max-w-sm text-balance">
              {q || tag || group
                ? 'Try adjusting your search or filters.'
                : 'Download and install the RemoteLink agent on the machines you want to control remotely.'}
            </p>
            {!(q || tag || group) && (
              <Button asChild>
                <Link href="/download">
                  <Download className="mr-2 h-4 w-4" />
                  Download Agent
                </Link>
              </Button>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  )
}
