'use client';
import { useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';
import { type DeploymentEvent } from '@/src/types/deployment';
import { TerminalSkeleton } from '@/components/skeletons/TerminalSkeleton';
import { TerminalProps } from '@/types/common';

export function Terminal({
  logs = [],
  isActive = true,
  maxHeight = '300px',
  className,
  loading = false,
}: TerminalProps) {
  const terminalRef = useRef<HTMLDivElement>(null);

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

  const getLogStyle = (type: DeploymentEvent['type']) => {
    switch (type) {
      case 'stderr':
        return 'text-red-400';
      case 'stdout':
        return 'text-neutral-900';
      default:
        return 'text-neutral-900';
    }
  };

  return (
    <div className={cn('flex flex-col rounded-md overflow-hidden', className)}>
      <div
        ref={terminalRef}
        className={cn(
          'bg-neutral-200 p-4 font-mono text-sm overflow-y-auto',
          'transition-opacity duration-150',
          isActive ? 'opacity-100' : 'opacity-70'
        )}
        style={{ maxHeight }}
      >
        {loading ? (
          <TerminalSkeleton />
        ) : (
          logs.map((log) => (
            <div key={crypto.randomUUID()} className='leading-5 mb-1'>
              <span className='text-neutral-700'>{new Date(log.date).toLocaleTimeString()} → </span>
              <span className={getLogStyle(log.type)}>{log.text.replace(/\x1b\[[0-9;]*m/g, '')}</span>
            </div>
          ))
        )}
        {isActive && (
          <div className='animate-pulse'>
            <span className='text-neutral-800'>$ </span>
            <span className='inline-block w-2 h-4 bg-neutral-700 ml-1' />
          </div>
        )}
      </div>
    </div>
  );
}
