'use client'

import { useState, useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card'
import { Button } from '../ui/Button'
import { Input } from '../ui/Input'
import { RefreshCw, Search, Download } from 'lucide-react'
import axios from 'axios'

interface LogEntry {
  stream: Record<string, string>
  values: Array<[string, string]>
}

interface LokiQueryResponse {
  status: string
  data: {
    resultType: string
    result: LogEntry[]
  }
}

interface LokiLogViewerProps {
  query?: string
  limit?: number
  since?: string
}

export default function LokiLogViewer({
  query = '{job="default"}',
  limit = 100,
  since = '1h',
}: LokiLogViewerProps) {
  const [searchQuery, setSearchQuery] = useState(query)
  const [logLines, setLogLines] = useState<Array<{ timestamp: string; message: string; labels: Record<string, string> }>>([])
  const lokiURL = process.env.NEXT_PUBLIC_LOKI_URL || 'http://localhost:3100'

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['loki-logs', searchQuery, limit, since],
    queryFn: async () => {
      const end = Math.floor(Date.now() / 1000)
      const start = end - (since === '1h' ? 3600 : since === '6h' ? 21600 : 86400)

      const response = await axios.get<LokiQueryResponse>(`${lokiURL}/loki/api/v1/query_range`, {
        params: {
          query: searchQuery,
          start,
          end,
          limit,
        },
      })

      const logs: Array<{ timestamp: string; message: string; labels: Record<string, string> }> = []
      
      response.data.data.result.forEach((entry: LogEntry) => {
        entry.values.forEach(([timestamp, message]) => {
          logs.push({
            timestamp: new Date(parseInt(timestamp) / 1000000).toISOString(),
            message,
            labels: entry.stream,
          })
        })
      })

      return logs.sort((a, b) => b.timestamp.localeCompare(a.timestamp))
    },
    refetchInterval: 10000, // Refresh every 10 seconds
  })

  useEffect(() => {
    if (data) {
      setLogLines(data)
    }
  }, [data])

  const handleExport = () => {
    const logText = logLines
      .map((log) => `[${log.timestamp}] ${JSON.stringify(log.labels)} ${log.message}`)
      .join('\n')
    
    const blob = new Blob([logText], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `logs-${Date.now()}.txt`
    a.click()
    URL.revokeObjectURL(url)
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle>Log Viewer (Loki)</CardTitle>
          <div className="flex gap-2">
            <Button onClick={handleExport} variant="outline" size="sm">
              <Download className="h-4 w-4 mr-2" />
              Export
            </Button>
            <Button onClick={() => refetch()} variant="outline" size="sm">
              <RefreshCw className="h-4 w-4 mr-2" />
              Refresh
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="flex gap-2">
            <Input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="LogQL query (e.g., {job='default'})"
              className="flex-1"
            />
            <Button onClick={() => refetch()}>
              <Search className="h-4 w-4 mr-2" />
              Search
            </Button>
          </div>

          {isLoading ? (
            <div className="flex items-center justify-center p-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
          ) : logLines.length === 0 ? (
            <div className="text-center text-gray-400 p-8">No logs found</div>
          ) : (
            <div className="bg-gray-900 rounded-lg p-4 font-mono text-sm overflow-auto max-h-96">
              {logLines.map((log, index) => (
                <div key={index} className="mb-2 border-b border-gray-800 pb-2 last:border-0">
                  <div className="flex items-start gap-2">
                    <span className="text-gray-500 text-xs whitespace-nowrap">
                      {new Date(log.timestamp).toLocaleTimeString()}
                    </span>
                    <span className="text-blue-400 text-xs">
                      {Object.entries(log.labels)
                        .map(([k, v]) => `${k}=${v}`)
                        .join(' ')}
                    </span>
                  </div>
                  <div className="text-gray-300 mt-1 break-words">{log.message}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}

