/**
 * ChatHeader Component
 * Header for chat conversations with title, actions, and status
 */

import React, { useState } from 'react';
import {
  MoreVertical,
  Edit2,
  Trash2,
  Download,
  Share2,
  Pin,
  PinOff,
  Copy,
  Settings,
  Wifi,
  WifiOff,
  Check,
  X,
  ChevronLeft,
  Sparkles,
} from 'lucide-react';

interface ChatSession {
  id: string;
  title: string;
  isPinned?: boolean;
  createdAt: string;
  messageCount: number;
}

interface ChatHeaderProps {
  session: ChatSession | null;
  isConnected?: boolean;
  isStreaming?: boolean;
  onTitleChange?: (newTitle: string) => void;
  onDelete?: () => void;
  onExport?: () => void;
  onShare?: () => void;
  onPin?: () => void;
  onCopy?: () => void;
  onSettings?: () => void;
  onBack?: () => void;
  showBackButton?: boolean;
  compact?: boolean;
}

const ChatHeader: React.FC<ChatHeaderProps> = ({
  session,
  isConnected = true,
  isStreaming = false,
  onTitleChange,
  onDelete,
  onExport,
  onShare,
  onPin,
  onCopy,
  onSettings,
  onBack,
  showBackButton = false,
  compact = false,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedTitle, setEditedTitle] = useState(session?.title || '');
  const [showMenu, setShowMenu] = useState(false);

  const handleStartEdit = () => {
    if (!onTitleChange) return;
    setEditedTitle(session?.title || '');
    setIsEditing(true);
    setShowMenu(false);
  };

  const handleSaveTitle = () => {
    if (editedTitle.trim() && editedTitle !== session?.title) {
      onTitleChange?.(editedTitle.trim());
    }
    setIsEditing(false);
  };

  const handleCancelEdit = () => {
    setEditedTitle(session?.title || '');
    setIsEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSaveTitle();
    } else if (e.key === 'Escape') {
      handleCancelEdit();
    }
  };

  const menuItems = [
    onTitleChange && { icon: Edit2, label: 'Rename', action: handleStartEdit },
    onPin && {
      icon: session?.isPinned ? PinOff : Pin,
      label: session?.isPinned ? 'Unpin' : 'Pin',
      action: onPin,
    },
    onCopy && { icon: Copy, label: 'Copy link', action: onCopy },
    onExport && { icon: Download, label: 'Export', action: onExport },
    onShare && { icon: Share2, label: 'Share', action: onShare },
    onDelete && {
      icon: Trash2,
      label: 'Delete',
      action: onDelete,
      danger: true,
    },
  ].filter(Boolean);

  return (
    <div
      className={`flex items-center justify-between border-b border-gray-700 bg-gray-800/50 ${
        compact ? 'px-3 py-2' : 'px-4 py-3'
      }`}
    >
      {/* Left Section */}
      <div className="flex items-center gap-3 flex-1 min-w-0">
        {showBackButton && onBack && (
          <button
            onClick={onBack}
            className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
        )}

        {/* AI Assistant Icon */}
        <div className="relative flex-shrink-0">
          <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          {/* Connection Status Dot */}
          <div
            className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-gray-800 ${
              isConnected ? 'bg-green-400' : 'bg-red-400'
            }`}
          />
        </div>

        {/* Title & Status */}
        <div className="flex-1 min-w-0">
          {isEditing ? (
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={editedTitle}
                onChange={(e) => setEditedTitle(e.target.value)}
                onKeyDown={handleKeyDown}
                autoFocus
                className="flex-1 px-2 py-1 bg-gray-900 border border-gray-600 rounded text-white text-sm focus:outline-none focus:border-blue-500"
                placeholder="Conversation title..."
              />
              <button
                onClick={handleSaveTitle}
                className="p-1 text-green-400 hover:bg-gray-700 rounded"
              >
                <Check className="w-4 h-4" />
              </button>
              <button
                onClick={handleCancelEdit}
                className="p-1 text-gray-400 hover:bg-gray-700 rounded"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          ) : (
            <>
              <div className="flex items-center gap-2">
                <h2 className="font-medium text-white truncate">
                  {session?.title || 'New Conversation'}
                </h2>
                {session?.isPinned && (
                  <Pin className="w-3 h-3 text-blue-400 flex-shrink-0" />
                )}
              </div>
              <div className="flex items-center gap-2 text-xs text-gray-500">
                {isStreaming ? (
                  <span className="flex items-center gap-1 text-blue-400">
                    <span className="w-1.5 h-1.5 bg-blue-400 rounded-full animate-pulse" />
                    Generating...
                  </span>
                ) : (
                  <>
                    {isConnected ? (
                      <span className="flex items-center gap-1">
                        <Wifi className="w-3 h-3 text-green-400" />
                        Connected
                      </span>
                    ) : (
                      <span className="flex items-center gap-1 text-red-400">
                        <WifiOff className="w-3 h-3" />
                        Disconnected
                      </span>
                    )}
                    {session && (
                      <>
                        <span>•</span>
                        <span>{session.messageCount} messages</span>
                      </>
                    )}
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Right Section - Actions */}
      <div className="flex items-center gap-1">
        {/* Settings Button */}
        {onSettings && (
          <button
            onClick={onSettings}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            title="Settings"
          >
            <Settings className="w-4 h-4" />
          </button>
        )}

        {/* More Menu */}
        {menuItems.length > 0 && (
          <div className="relative">
            <button
              onClick={() => setShowMenu(!showMenu)}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            >
              <MoreVertical className="w-4 h-4" />
            </button>

            {showMenu && (
              <>
                {/* Backdrop */}
                <div
                  className="fixed inset-0 z-10"
                  onClick={() => setShowMenu(false)}
                />
                {/* Menu */}
                <div className="absolute right-0 top-full mt-1 w-48 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20 py-1">
                  {menuItems.map((item, index) => {
                    if (!item) return null;
                    const Icon = item.icon;
                    return (
                      <button
                        key={index}
                        onClick={() => {
                          item.action();
                          setShowMenu(false);
                        }}
                        className={`w-full flex items-center gap-3 px-3 py-2 text-sm transition-colors ${
                          item.danger
                            ? 'text-red-400 hover:bg-red-500/10'
                            : 'text-gray-300 hover:bg-gray-700'
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                        {item.label}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default ChatHeader;
