import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@core/components/ui/card'
import { Badge } from '@core/components/ui/badge'
import { Skeleton } from '@core/components/ui/skeleton'
import { Terminal, CheckCircle } from 'lucide-react'
import { apiFetch } from '@core/lib/api'

interface CliInstance {
  id: string
  serial: string
  app_slug: string
  version: string
  first_seen_at: string
  last_signal_at: string
  claimed_at?: string
  claimed_by_person_id?: string
}

interface CliInstancesCardProps {
  accountId?: string
  personId?: string
  title?: string
}

export function CliInstancesCard({ 
  accountId, 
  personId,
  title = "CLI Installations" 
}: CliInstancesCardProps) {
  const [instances, setInstances] = useState<CliInstance[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function loadInstances() {
      if (!accountId && !personId) return

      try {
        setLoading(true)
        const endpoint = accountId 
          ? `/custom_api/account-cli-instances?account_id=${accountId}`
          : `/custom_api/person-cli-instances?person_id=${personId}`
        
        const { data } = await apiFetch(endpoint)
        setInstances(data || [])
      } catch (e) {
        console.error('Failed to load CLI instances:', e)
      } finally {
        setLoading(false)
      }
    }

    loadInstances()
  }, [accountId, personId])

  // Truncate serial for display
  const truncateSerial = (serial: string) => {
    if (!serial || serial.length < 20) return serial
    return `${serial.slice(0, 8)}***${serial.slice(-6)}`
  }

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Terminal className="w-4 h-4" />
            {title}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Skeleton className="h-12" />
        </CardContent>
      </Card>
    )
  }

  if (instances.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Terminal className="w-4 h-4" />
            {title}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            No CLI installations claimed yet
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Terminal className="w-4 h-4" />
            {title}
          </CardTitle>
          <Badge variant="secondary" className="text-xs">
            {instances.length}
          </Badge>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-2">
          {instances.map((instance) => (
            <div 
              key={instance.id}
              className="flex items-center justify-between p-2 rounded-md border hover:bg-muted/50 transition-colors"
            >
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <code className="text-xs font-mono bg-muted px-1.5 py-0.5 rounded">
                    {truncateSerial(instance.serial)}
                  </code>
                  <Badge variant="outline" className="text-[10px] px-1 py-0">
                    {instance.app_slug}
                  </Badge>
                  <span className="text-xs text-muted-foreground">
                    v{instance.version}
                  </span>
                </div>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span>First seen {new Date(instance.first_seen_at).toLocaleDateString()}</span>
                  {instance.last_signal_at && (
                    <>
                      <span>•</span>
                      <span>Active {new Date(instance.last_signal_at).toLocaleDateString()}</span>
                    </>
                  )}
                </div>
              </div>
              <CheckCircle className="w-4 h-4 text-green-500" />
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
