import { auth } from '@/auth'
import { db } from '@/lib/db'
import { machines } from '@/lib/db/schema'
import { eq, desc } from 'drizzle-orm'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import Link from 'next/link'
import { Download, Laptop, Link2 } from 'lucide-react'
import { formatDistanceToNow } from 'date-fns'
import { MachineActions } from '@/components/dashboard/machine-actions'

export default async function MachinesPage() {
  const session = await auth()
  const machineList = await db
    .select()
    .from(machines)
    .where(eq(machines.userId, session!.user.id))
    .orderBy(desc(machines.isOnline), desc(machines.lastSeen))

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

  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>
          <p className="text-muted-foreground">
            {machineList.length} machine{machineList.length !== 1 ? 's' : ''} registered, {onlineCount} online
          </p>
        </div>
        <Button asChild>
          <Link href="/download">
            <Download className="mr-2 h-4 w-4" />
            Download Agent
          </Link>
        </Button>
      </div>

      {machineList.length > 0 ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {machineList.map((machine) => (
            <Card key={machine.id} className="border-border/50">
              <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
                <div className="flex items-center gap-3">
                  <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${machine.isOnline ? 'bg-green-500/10 text-green-500' : 'bg-muted text-muted-foreground'}`}>
                    <Laptop className="h-5 w-5" />
                  </div>
                  <div>
                    <CardTitle className="text-base">{machine.name}</CardTitle>
                    <CardDescription className="text-xs">{machine.hostname || 'Unknown host'}</CardDescription>
                  </div>
                </div>
                <MachineActions machine={machine} />
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Status</span>
                  <span className={`flex items-center gap-1.5 ${machine.isOnline ? 'text-green-500' : 'text-muted-foreground'}`}>
                    <span className={`h-2 w-2 rounded-full ${machine.isOnline ? 'bg-green-500' : 'bg-muted-foreground/30'}`} />
                    {machine.isOnline ? 'Online' : 'Offline'}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">OS</span>
                  <span>{machine.os || 'Unknown'} {machine.osVersion || ''}</span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Last seen</span>
                  <span>
                    {machine.lastSeen
                      ? formatDistanceToNow(new Date(machine.lastSeen), { addSuffix: true })
                      : 'Never'}
                  </span>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Agent</span>
                  <span className="font-mono text-xs">{machine.agentVersion || 'N/A'}</span>
                </div>
                <div className="pt-2">
                  <Button className="w-full" size="sm" disabled={!machine.isOnline} asChild={machine.isOnline}>
                    {machine.isOnline ? (
                      <Link href={`/viewer/${machine.id}`}>
                        <Link2 className="mr-2 h-4 w-4" />
                        Connect
                      </Link>
                    ) : (
                      <>
                        <Link2 className="mr-2 h-4 w-4" />
                        Connect
                      </>
                    )}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </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">No machines yet</h3>
            <p className="text-muted-foreground text-center mb-6 max-w-sm text-balance">
              Download and install the RemoteLink agent on the machines you want to control remotely.
            </p>
            <Button asChild>
              <Link href="/download">
                <Download className="mr-2 h-4 w-4" />
                Download Agent
              </Link>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
