'use client';

import { useEffect, useState, useRef } from 'react';
import { api } from '@/lib/api';
import { X, Maximize2, Minimize2 } from 'lucide-react';

interface LogViewerProps {
  deploymentId: string;
  onClose: () => void;
}

export function LogViewer({ deploymentId, onClose }: LogViewerProps) {
  const [logs, setLogs] = useState<string[]>([]);
  const [isExpanded, setIsExpanded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const logContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let cancelled = false;
    let intervalId: ReturnType<typeof setInterval> | null = null;

    const stopPolling = () => {
      if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
      }
      setIsRefreshing(false);
    };

    const loadLogs = async () => {
      try {
        const deployment = await api.getDeploymentLogs(deploymentId);

        if (cancelled) {
          return;
        }

        setError(null);
        setLogs(deployment.logs ? deployment.logs.split('\n') : []);
        if (deployment.status === 'running') {
          setIsRefreshing(true);
        } else {
          stopPolling();
        }
      } catch (err) {
        if (cancelled) {
          return;
        }
        console.error('Failed to load initial logs:', err);
        setError(err instanceof Error ? err.message : 'Failed to load logs');
        setIsRefreshing(true);
      }
    };

    setError(null);
    setLogs([]);
    setIsRefreshing(true);
    intervalId = setInterval(() => {
      void loadLogs();
    }, 2000);
    void loadLogs();

    return () => {
      cancelled = true;
      stopPolling();
    };
  }, [deploymentId]);

  useEffect(() => {
    if (logContainerRef.current) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
    }
  }, [logs]);

  return (
    <div className={`fixed bg-gray-900 text-gray-100 font-mono text-sm shadow-xl transition-all duration-300 ${
      isExpanded ? 'inset-4 z-50' : 'bottom-0 left-0 right-0 h-64 z-40'
    }`} role="region" aria-label="Deployment logs" aria-live="polite">
      <div className="flex items-center justify-between px-4 py-2 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center gap-3">
          <span className="font-medium">Deployment Logs</span>
          <span className={`flex items-center gap-1 text-xs ${
            isRefreshing ? 'text-green-400' : 'text-gray-500'
          }`} aria-live="polite">
            <span className={`w-2 h-2 rounded-full ${isRefreshing ? 'bg-green-400' : 'bg-gray-500'}`} aria-hidden="true" />
            {isRefreshing ? 'Updating' : 'Stopped'}
          </span>
          {error && <span className="text-xs text-red-400" role="alert">{error}</span>}
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="p-1 text-gray-400 hover:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 rounded"
            title={isExpanded ? 'Minimize' : 'Expand'}
            aria-label={isExpanded ? 'Minimize log viewer' : 'Expand log viewer'}
          >
            {isExpanded ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
          </button>
          <button
            onClick={onClose}
            className="p-1 text-gray-400 hover:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 rounded"
            title="Close"
            aria-label="Close log viewer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div
        ref={logContainerRef}
        className="p-4 overflow-y-auto"
        style={{ height: isExpanded ? 'calc(100% - 40px)' : 'calc(100% - 40px)' }}
      >
        {logs.length === 0 ? (
          <div className="text-gray-500">Waiting for logs...</div>
        ) : (
          logs.map((log, index) => (
            <div key={index} className="py-0.5">
              {log}
            </div>
          ))
        )}
      </div>
    </div>
  );
}
