import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useToast } from '@/hooks/useToast';
import { useKubectl } from '@/hooks/useKubectl';
import {
  FileText,
  Search,
  Filter,
  Copy,
  Download,
  Maximize2,
  Minimize2,
  X,
  Loader2,
  RotateCw,
  Square,
  ChevronDown,
  Calendar,
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import {
  vscDarkPlus,
  oneDark,
  materialDark,
} from 'react-syntax-highlighter/dist/esm/styles/prism';
import { github } from 'react-syntax-highlighter/dist/esm/styles/hljs';

interface LogsModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  podName: string;
  containerName?: string;
  namespace: string;
  title?: string;
}

export function LogsModal({
  open,
  onOpenChange,
  podName,
  containerName,
  namespace,
  title = 'Logs do Container',
}: LogsModalProps) {
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();

  // Estados do modal
  const [logsFullscreen, setLogsFullscreen] = useState(false);
  const [podLogs, setPodLogs] = useState<string>('');
  const [loadingLogs, setLoadingLogs] = useState(false);

  // Estados de filtros
  const [logsFilter, setLogsFilter] = useState('');
  const [logsLevelFilter, setLogsLevelFilter] = useState('all');
  const [logsDateFrom, setLogsDateFrom] = useState('');
  const [logsDateTo, setLogsDateTo] = useState('');

  // Estados de controle
  const [autoRefreshLogs, setAutoRefreshLogs] = useState(true); // Habilitado por padrão
  const [refreshInterval, setRefreshInterval] = useState(3000); // 3 segundos por padrão
  const [lastLogTimestamp, setLastLogTimestamp] = useState<string>('');

  // Tema dos logs
  const [logsTheme, setLogsTheme] = useState(() => {
    return localStorage.getItem('logs-theme-preference') || 'oneDark';
  });

  // Salvar preferência do tema
  useEffect(() => {
    localStorage.setItem('logs-theme-preference', logsTheme);
  }, [logsTheme]);

  // Auto-refresh dos logs
  useEffect(() => {
    if (!autoRefreshLogs || !open || !podName || !namespace) {
      return;
    }

    const interval = setInterval(async () => {
      try {
        await loadLogs(false); // false = não mostrar loading
      } catch (err) {
        console.error('Auto-refresh error:', err);
      }
    }, refreshInterval);

    return () => clearInterval(interval);
  }, [
    autoRefreshLogs,
    open,
    podName,
    namespace,
    refreshInterval,
    lastLogTimestamp,
  ]);

  // Reset fullscreen quando fechar modal
  useEffect(() => {
    if (!open) {
      setLogsFullscreen(false);
    }
  }, [open]);

  // Carregar logs quando o modal abrir
  useEffect(() => {
    if (open && podName && namespace) {
      loadLogs(true);
    }
  }, [open, podName, namespace, containerName]);

  const loadLogs = async (showLoading = true) => {
    if (showLoading) {
      setLoadingLogs(true);
      setPodLogs('');
    }

    try {
      const containerFlag = containerName ? ` -c ${containerName}` : '';
      const sinceFlag = lastLogTimestamp
        ? ` --since-time=${lastLogTimestamp}`
        : ' --tail=300'; // Apenas 300 linhas iniciais para abertura mais rápida
      const command = `kubectl logs ${podName} -n ${namespace}${containerFlag}${sinceFlag}`;

      const result = await executeCommand(command);

      if (result.success) {
        const rawLogs = result.data || '';

        if (lastLogTimestamp) {
          // Modo tail - só append se houver logs novos reais
          if (rawLogs.trim()) {
            setPodLogs((prev) => {
              const combined = `${prev}\n${rawLogs}`;
              const lines = combined.split('\n');
              // Manter máximo de 1000 linhas para performance
              if (lines.length > 1000) {
                return lines.slice(-1000).join('\n');
              }
              return combined;
            });
          }
          // Se não há logs novos, não faz nada (não append "Nenhum log disponível")
        } else {
          // Carregamento inicial - usar fallback apenas se realmente vazio
          const logs = rawLogs || 'Nenhum log disponível';
          const lines = logs.split('\n');
          if (lines.length > 300) {
            setPodLogs(lines.slice(-300).join('\n'));
          } else {
            setPodLogs(logs);
          }
        }

        // Atualizar timestamp para próximo refresh apenas se houver logs reais
        if (rawLogs.trim()) {
          setLastLogTimestamp(new Date().toISOString());
        }
      } else {
        // Se erro contém "must be logged in" e estamos usando --since-time, tentar novamente sem ele
        if (
          result.error &&
          result.error.includes('must be logged in') &&
          lastLogTimestamp
        ) {
          console.warn(
            'Auth error com --since-time, tentando novamente sem timestamp...',
          );
          setLastLogTimestamp(''); // Reset timestamp para forçar reload completo

          try {
            const fallbackCommand = `kubectl logs ${podName} -n ${namespace}${containerFlag} --tail=300`;
            const fallbackResult = await executeCommand(fallbackCommand);

            if (fallbackResult.success) {
              const logs = fallbackResult.data || 'Nenhum log disponível';
              setPodLogs(logs);
              // Não definir novo timestamp para evitar repetir o erro
            } else {
              setPodLogs(
                `# Erro ao carregar logs\n# ${fallbackResult.error || 'Erro desconhecido'}`,
              );
            }
          } catch (fallbackErr) {
            setPodLogs(
              `# Erro ao carregar logs\n# ${fallbackErr instanceof Error ? fallbackErr.message : 'Erro inesperado'}`,
            );
          }
        } else {
          setPodLogs(
            `# Erro ao carregar logs\n# ${result.error || 'Erro desconhecido'}`,
          );
        }
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setPodLogs(`# Erro ao carregar logs\n# ${errorMsg}`);
    } finally {
      if (showLoading) {
        setLoadingLogs(false);
      }
    }
  };

  const getLogsTheme = () => {
    switch (logsTheme) {
      case 'vscDarkPlus':
        return vscDarkPlus;
      case 'github':
        return github;
      case 'oneDark':
        return oneDark;
      case 'materialDark':
        return materialDark;
      default:
        return oneDark;
    }
  };

  const getFilteredLogs = () => {
    let logs = podLogs;

    // Filtro por texto
    if (logsFilter) {
      const lines = logs.split('\n');
      const filteredLines = lines.filter((line) =>
        line.toLowerCase().includes(logsFilter.toLowerCase()),
      );
      logs = filteredLines.join('\n');
    }

    // Filtro por nível
    if (logsLevelFilter !== 'all') {
      const lines = logs.split('\n');
      const filteredLines = lines.filter((line) => {
        const upperLine = line.toUpperCase();
        return upperLine.includes(logsLevelFilter.toUpperCase());
      });
      logs = filteredLines.join('\n');
    }

    // Filtro por data
    if (logsDateFrom || logsDateTo) {
      const lines = logs.split('\n');
      const filteredLines = lines.filter((line) => {
        // Tentar extrair timestamp da linha (formato comum: ISO 8601)
        const timestampMatch = line.match(
          /\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/,
        );
        if (!timestampMatch) return true; // Se não tem timestamp, incluir

        const lineDate = new Date(timestampMatch[0]);
        const fromDate = logsDateFrom ? new Date(logsDateFrom) : null;
        const toDate = logsDateTo ? new Date(logsDateTo) : null;

        if (fromDate && lineDate < fromDate) return false;
        if (toDate && lineDate > toDate) return false;

        return true;
      });
      logs = filteredLines.join('\n');
    }

    return logs;
  };

  const handleClearLogs = () => {
    setPodLogs('');
    // Definir timestamp atual para que próximos refreshes só peguem logs novos
    setLastLogTimestamp(new Date().toISOString());
    showToast({
      title: 'Logs Limpos',
      description: 'A partir de agora só serão exibidos logs novos',
      variant: 'success',
    });
  };

  const handleDownloadLogs = () => {
    const logsToDownload = getFilteredLogs();
    const blob = new Blob([logsToDownload], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${podName}${containerName ? `-${containerName}` : ''}-logs.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    showToast({
      title: 'Download Iniciado',
      description: 'Os logs foram baixados com sucesso',
      variant: 'success',
    });
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(openState) => {
        onOpenChange(openState);
        if (!openState) {
          setLogsFullscreen(false);
          // Mantém autoRefreshLogs como true para próxima abertura
          setPodLogs('');
          setLogsFilter('');
          setLogsLevelFilter('all');
          setLogsDateFrom('');
          setLogsDateTo('');
          setLastLogTimestamp('');
        }
      }}
    >
      <DialogContent
        className={
          logsFullscreen
            ? 'max-w-none h-screen w-screen flex flex-col m-0 rounded-none [&>button]:hidden'
            : 'max-w-6xl h-[90vh] flex flex-col'
        }
      >
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <FileText className="h-5 w-5 mr-2" />
              {title}
            </div>
            {logsFullscreen && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setLogsFullscreen(false)}
                title="Sair da tela cheia"
              >
                <X className="h-4 w-4" />
              </Button>
            )}
          </DialogTitle>
          <DialogDescription>
            Pod: {podName} {containerName && `• Container: ${containerName}`} •
            Namespace: {namespace}
          </DialogDescription>
        </DialogHeader>

        {loadingLogs ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="flex items-center space-x-2">
              <Loader2 className="h-6 w-6 animate-spin" />
              <span>Carregando logs...</span>
            </div>
          </div>
        ) : (
          <div className="flex-1 flex flex-col min-h-0">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center space-x-3">
                {/* Campo de busca */}
                <div className="w-64 relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Buscar nos logs..."
                    value={logsFilter}
                    onChange={(e) => setLogsFilter(e.target.value)}
                    className="w-full pl-9 pr-9 py-2 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  {logsFilter && (
                    <button
                      onClick={() => setLogsFilter('')}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                </div>

                {/* Filtro por nível */}
                <Select
                  value={logsLevelFilter}
                  onValueChange={setLogsLevelFilter}
                >
                  <SelectTrigger className="w-[120px]">
                    <Filter className="h-4 w-4 mr-2" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Todos</SelectItem>
                    <SelectItem value="error">ERROR</SelectItem>
                    <SelectItem value="warn">WARN</SelectItem>
                    <SelectItem value="info">INFO</SelectItem>
                    <SelectItem value="debug">DEBUG</SelectItem>
                  </SelectContent>
                </Select>

                {/* Separador vertical */}
                <div className="h-6 w-px bg-gray-300" />

                {/* Split button - Tail com dropdown de tempo */}
                <div className="flex">
                  {/* Botão principal - Tail On/Off */}
                  <button
                    onClick={() => setAutoRefreshLogs(!autoRefreshLogs)}
                    className={`flex items-center space-x-1 px-3 py-1 text-sm rounded-l-md border transition-colors ${
                      autoRefreshLogs
                        ? 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100'
                        : 'bg-red-50 text-red-600 border-red-200 hover:bg-red-100'
                    }`}
                    title={autoRefreshLogs ? 'Pausar tail' : 'Iniciar tail'}
                  >
                    {autoRefreshLogs ? (
                      <Square className="h-3 w-3" />
                    ) : (
                      <RotateCw className="h-3 w-3" />
                    )}
                    <span>{autoRefreshLogs ? 'Tail On' : 'Tail Off'}</span>
                  </button>

                  {/* Dropdown de tempo */}
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <button
                        className={`px-2 py-1 text-sm rounded-r-md border-l-0 border transition-colors ${
                          autoRefreshLogs
                            ? 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100'
                            : 'bg-red-50 text-red-600 border-red-200 hover:bg-red-100'
                        }`}
                        title="Configurar intervalo de refresh"
                      >
                        <ChevronDown className="h-3 w-3" />
                      </button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuLabel>
                        Intervalo de Refresh
                      </DropdownMenuLabel>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem
                        onClick={() => setRefreshInterval(1000)}
                        className={
                          refreshInterval === 1000 ? 'bg-green-100' : ''
                        }
                      >
                        1 segundo
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setRefreshInterval(3000)}
                        className={
                          refreshInterval === 3000 ? 'bg-green-100' : ''
                        }
                      >
                        3 segundos (padrão)
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setRefreshInterval(5000)}
                        className={
                          refreshInterval === 5000 ? 'bg-green-100' : ''
                        }
                      >
                        5 segundos
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setRefreshInterval(10000)}
                        className={
                          refreshInterval === 10000 ? 'bg-green-100' : ''
                        }
                      >
                        10 segundos
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </div>

              <div className="flex items-center space-x-2">
                <Select value={logsTheme} onValueChange={setLogsTheme}>
                  <SelectTrigger className="w-[140px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="vscDarkPlus">VS Code Dark</SelectItem>
                    <SelectItem value="github">GitHub Light</SelectItem>
                    <SelectItem value="oneDark">One Dark</SelectItem>
                    <SelectItem value="materialDark">Material Dark</SelectItem>
                  </SelectContent>
                </Select>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const logsToShare = getFilteredLogs();
                    navigator.clipboard.writeText(logsToShare);
                    showToast({
                      title: 'Logs Copiados',
                      description:
                        logsFilter ||
                        logsLevelFilter !== 'all' ||
                        logsDateFrom ||
                        logsDateTo
                          ? 'Logs filtrados copiados para a área de transferência'
                          : 'Logs copiados para a área de transferência',
                      variant: 'success',
                    });
                  }}
                >
                  <Copy className="h-4 w-4 mr-2" />
                  Copiar Logs
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleClearLogs}
                  disabled={loadingLogs}
                >
                  Limpar
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleDownloadLogs}
                  disabled={!podLogs || podLogs.startsWith('# Erro')}
                >
                  <Download className="h-4 w-4 mr-2" />
                  Download
                </Button>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setLogsFullscreen(!logsFullscreen)}
                  title={
                    logsFullscreen
                      ? 'Sair da tela cheia'
                      : 'Abrir em tela cheia'
                  }
                >
                  {logsFullscreen ? (
                    <Minimize2 className="h-4 w-4" />
                  ) : (
                    <Maximize2 className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>

            <div className="flex-1 rounded-lg border overflow-hidden min-h-0">
              <SyntaxHighlighter
                language="log"
                style={getLogsTheme()}
                showLineNumbers
                wrapLines
                customStyle={{
                  margin: 0,
                  padding: '16px',
                  fontSize: '14px',
                  height: '100%',
                  maxHeight: '100%',
                  overflow: 'auto',
                  borderRadius: '8px',
                  color: logsTheme === 'github' ? '#6B7280' : '#9CA3AF',
                  borderRight:
                    logsTheme === 'github'
                      ? '1px solid #E5E7EB'
                      : '1px solid #374151',
                }}
              >
                {getFilteredLogs() || '# Nenhum log disponível'}
              </SyntaxHighlighter>
            </div>

            {/* Informações na parte inferior */}
            <div className="flex items-center justify-between pt-3 border-t">
              {/* Contador de linhas - esquerda */}
              <span className="text-sm text-muted-foreground">
                {
                  getFilteredLogs()
                    .split('\n')
                    .filter((line) => line.trim()).length
                }{' '}
                linhas
                {(logsFilter ||
                  logsLevelFilter !== 'all' ||
                  logsDateFrom ||
                  logsDateTo) && (
                  <span className="text-blue-600">
                    {' '}
                    (filtradas de {podLogs.split('\n').length})
                  </span>
                )}
              </span>

              {/* Filtros de período - direita */}
              <div className="flex items-center space-x-3">
                <div className="flex items-center space-x-2">
                  <Calendar className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm text-muted-foreground">
                    Período:
                  </span>
                </div>
                <div className="flex items-center space-x-2">
                  <input
                    type="datetime-local"
                    value={logsDateFrom}
                    onChange={(e) => setLogsDateFrom(e.target.value)}
                    className="text-sm border rounded-md px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="De"
                  />
                  <span className="text-muted-foreground">até</span>
                  <input
                    type="datetime-local"
                    value={logsDateTo}
                    onChange={(e) => setLogsDateTo(e.target.value)}
                    className="text-sm border rounded-md px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Até"
                  />
                  {(logsDateFrom || logsDateTo) && (
                    <button
                      onClick={() => {
                        setLogsDateFrom('');
                        setLogsDateTo('');
                      }}
                      className="text-muted-foreground hover:text-foreground"
                      title="Limpar filtro de data"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
