'use client';

import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Search, RefreshCw, Filter, Download } from 'lucide-react';
import { api } from '@/lib/api';
import { formatTime } from '@/lib/utils';

interface LogEntry {
  timestamp: string;
  service: string;
  host: string;
  level: string;
  message: string;
  trace_id?: string;
  span_id?: string;
  source?: string;
  container_id?: string;
}

const LOG_LEVELS = ['', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'];

export default function LogsPage() {
  const [service, setService] = useState('');
  const [level, setLevel] = useState('');
  const [query, setQuery] = useState('');
  const [traceId, setTraceId] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(false);

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['logs', service, level, query, traceId],
    queryFn: () => api.get('/api/v1/logs', {
      service,
      level,
      q: query,
      trace_id: traceId,
      from: new Date(Date.now() - 3600000).toISOString(),
      limit: '200',
    }),
    refetchInterval: autoRefresh ? 5000 : false,
  });

  const logs: LogEntry[] = data?.logs ?? [];

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-white">Logs</h1>
        <div className="flex items-center gap-2">
          <label className="flex items-center gap-2 text-sm text-gray-400">
            <input
              type="checkbox"
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
              className="rounded border-gray-600 bg-gray-800 text-indigo-500"
            />
            Auto-refresh
          </label>
          <button
            onClick={() => refetch()}
            className="p-2 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-colors"
          >
            <RefreshCw className={`h-5 w-5 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-4 p-4 bg-gray-900/50 rounded-lg border border-gray-800">
        <div className="flex-1 min-w-[200px]">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search logs..."
              className="w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-indigo-500"
            />
          </div>
        </div>
        <div className="w-40">
          <select
            value={service}
            onChange={(e) => setService(e.target.value)}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-indigo-500"
          >
            <option value="">All services</option>
            {/* Services would be populated dynamically */}
          </select>
        </div>
        <div className="w-32">
          <select
            value={level}
            onChange={(e) => setLevel(e.target.value)}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-indigo-500"
          >
            {LOG_LEVELS.map((l) => (
              <option key={l} value={l}>
                {l || 'All levels'}
              </option>
            ))}
          </select>
        </div>
        <div className="w-64">
          <input
            type="text"
            value={traceId}
            onChange={(e) => setTraceId(e.target.value)}
            placeholder="Trace ID"
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-indigo-500"
          />
        </div>
      </div>

      {/* Log Table */}
      <div className="bg-gray-900/50 rounded-lg border border-gray-800 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-800">
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Time</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Level</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Service</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Message</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-800">
              {logs.map((log, i) => (
                <LogRow key={i} log={log} />
              ))}
              {!isLoading && logs.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-4 py-8 text-center text-gray-500">
                    No logs found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between text-sm text-gray-500">
        <span>Showing {logs.length} logs</span>
        {data?.count && data.count > logs.length && (
          <span>Limited to 200 results</span>
        )}
      </div>
    </div>
  );
}

function LogRow({ log }: { log: LogEntry }) {
  const [expanded, setExpanded] = useState(false);

  const levelColors: Record<string, string> = {
    ERROR: 'text-red-400 bg-red-400/10',
    WARN: 'text-yellow-400 bg-yellow-400/10',
    INFO: 'text-blue-400 bg-blue-400/10',
    DEBUG: 'text-gray-400 bg-gray-400/10',
    TRACE: 'text-gray-500 bg-gray-500/10',
    FATAL: 'text-red-500 bg-red-500/20',
  };

  return (
    <>
      <tr
        onClick={() => setExpanded(!expanded)}
        className="hover:bg-gray-800/50 cursor-pointer"
      >
        <td className="px-4 py-2 text-sm text-gray-400 whitespace-nowrap font-mono">
          {formatTime(log.timestamp)}
        </td>
        <td className="px-4 py-2">
          <span className={`px-2 py-0.5 text-xs font-medium rounded ${levelColors[log.level] || ''}`}>
            {log.level}
          </span>
        </td>
        <td className="px-4 py-2 text-sm text-gray-300 whitespace-nowrap">
          {log.service}
        </td>
        <td className="px-4 py-2 text-sm text-gray-200 max-w-xl truncate font-mono">
          {log.message}
        </td>
      </tr>
      {expanded && (
        <tr className="bg-gray-800/30">
          <td colSpan={4} className="px-4 py-3">
            <pre className="text-sm text-gray-300 whitespace-pre-wrap font-mono">
              {log.message}
            </pre>
            <div className="mt-2 flex flex-wrap gap-4 text-xs text-gray-500">
              <span>Host: {log.host}</span>
              <span>Source: {log.source}</span>
              {log.container_id && <span>Container: {log.container_id}</span>}
              {log.trace_id && (
                <a
                  href={`/traces?id=${log.trace_id}`}
                  className="text-indigo-400 hover:text-indigo-300"
                >
                  Trace: {log.trace_id.slice(0, 16)}...
                </a>
              )}
            </div>
          </td>
        </tr>
      )}
    </>
  );
}
