import React from "react";
import { Card, CardContent, CardHeader } from "./card";
import { Button } from "./button";
import type { HistoryPanelProps, HistoryEntry } from "../../types/ai";
import { cn } from "../../lib/utils";

/**
 * 히스토리 패널 컴포넌트
 * 우측에서 슬라이드 인하는 방식으로 작동
 */
const HistoryPanel: React.FC<HistoryPanelProps> = ({
  isOpen,
  onClose,
  history,
  onReapply,
  onClear,
}) => {
  // 키보드 접근성: Escape 키로 패널 닫기
  React.useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape" && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleKeyDown);
      // 포커스 트랩을 위해 패널에 포커스 설정
      const panel = document.getElementById("history-panel");
      if (panel) {
        panel.focus();
      }
    }

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, onClose]);

  // 시간 포맷팅 함수
  const formatTime = (date: Date): string => {
    return new Intl.DateTimeFormat("ko-KR", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    }).format(date);
  };

  // 날짜 포맷팅 함수
  const formatDate = (date: Date): string => {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === today.toDateString()) {
      return "오늘";
    } else if (date.toDateString() === yesterday.toDateString()) {
      return "어제";
    } else {
      return new Intl.DateTimeFormat("ko-KR", {
        month: "short",
        day: "numeric",
      }).format(date);
    }
  };

  // 상태별 아이콘 및 색상
  const getStatusIcon = (status: HistoryEntry["status"]) => {
    switch (status) {
      case "success":
        return <span className="text-green-500">✅</span>;
      case "error":
        return <span className="text-red-500">❌</span>;
      case "pending":
        return <span className="text-yellow-500 animate-pulse">⏳</span>;
      default:
        return <span className="text-gray-400">❓</span>;
    }
  };

  // 액션 요약 생성
  const getActionSummary = (actions: HistoryEntry["actions"]): string => {
    if (actions.length === 0) return "액션 없음";

    const actionTypes = actions.map((action) => {
      switch (action.type) {
        case "formula":
          return "수식";
        case "style":
          return "스타일";
        case "chart":
          return "차트";
        default:
          return "기타";
      }
    });

    return `${actionTypes.join(", ")} (${actions.length}개)`;
  };

  return (
    <>
      {/* 백드롭 오버레이 */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-60 z-40 transition-opacity duration-300"
          onClick={onClose}
          aria-hidden="true"
        />
      )}

      {/* 히스토리 패널 */}
      <div
        id="history-panel"
        className={cn(
          "bg-white shadow-2xl z-50",
          "transform transition-transform duration-300 ease-in-out",
          "flex flex-col border-l border-gray-200",
          isOpen ? "translate-x-0" : "translate-x-full",
        )}
        style={{
          position: "fixed",
          top: 65,
          right: 0,
          height: "100vh",
          width: "384px", // w-96 = 384px
          backgroundColor: "#ffffff",
          zIndex: 50,
        }}
        role="dialog"
        aria-modal="true"
        aria-labelledby="history-panel-title"
        aria-describedby="history-panel-description"
        tabIndex={-1}
      >
        {/* 헤더 */}
        <div className="flex-shrink-0 border-b border-gray-200 p-4">
          <div className="flex items-center justify-between">
            <div>
              <h2
                id="history-panel-title"
                className="text-lg font-semibold text-gray-900"
              >
                📝 작업 히스토리
              </h2>
              <p
                id="history-panel-description"
                className="text-sm text-gray-500 mt-1"
              >
                AI 프롬프트 실행 기록 ({history.length}개)
              </p>
            </div>

            {/* 닫기 버튼 */}
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              aria-label="히스토리 패널 닫기"
              className="text-gray-400 hover:text-gray-600"
            >
              ✕
            </Button>
          </div>

          {/* 전체 삭제 버튼 */}
          {history.length > 0 && onClear && (
            <div className="mt-3">
              <Button
                variant="outline"
                size="sm"
                onClick={onClear}
                className="w-full text-red-600 border-red-200 hover:bg-red-50"
                aria-label="모든 히스토리 삭제"
              >
                🗑️ 전체 삭제
              </Button>
            </div>
          )}
        </div>

        {/* 히스토리 목록 */}
        <div className="flex-1 overflow-y-auto">
          {history.length === 0 ? (
            // 빈 상태
            <div className="flex flex-col items-center justify-center h-full text-gray-500">
              <div className="text-4xl mb-4">📋</div>
              <p className="text-center px-4">
                아직 실행된 AI 프롬프트가 없습니다.
                <br />
                <span className="text-sm text-gray-400">
                  프롬프트를 입력하고 실행해보세요!
                </span>
              </p>
            </div>
          ) : (
            // 히스토리 항목들
            <div className="p-4 space-y-3">
              {history.map((entry, index) => (
                <Card
                  key={entry.id}
                  className={cn(
                    "transition-all duration-200 hover:shadow-md",
                    entry.status === "error" && "border-red-200 bg-red-50",
                    entry.status === "success" &&
                      "border-green-200 bg-green-50",
                    entry.status === "pending" &&
                      "border-yellow-200 bg-yellow-50",
                  )}
                >
                  <CardHeader className="pb-2">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-2">
                        {getStatusIcon(entry.status)}
                        <div className="text-xs text-gray-500">
                          {formatDate(entry.timestamp)}{" "}
                          {formatTime(entry.timestamp)}
                        </div>
                      </div>
                      <div className="text-xs text-gray-400">
                        #{history.length - index}
                      </div>
                    </div>
                  </CardHeader>

                  <CardContent className="pt-0">
                    {/* 프롬프트 */}
                    <div className="mb-3">
                      <p className="text-sm font-medium text-gray-900 mb-1">
                        프롬프트:
                      </p>
                      <p className="text-sm text-gray-700 bg-gray-100 rounded-md p-2 break-words">
                        {entry.prompt}
                      </p>
                    </div>

                    {/* 범위 및 시트 정보 */}
                    <div className="mb-3 text-xs text-gray-600">
                      <span className="font-medium">범위:</span> {entry.range} |
                      <span className="font-medium ml-1">시트:</span>{" "}
                      {entry.sheetName}
                    </div>

                    {/* 액션 요약 */}
                    <div className="mb-3">
                      <p className="text-xs text-gray-600">
                        <span className="font-medium">실행된 액션:</span>{" "}
                        {getActionSummary(entry.actions)}
                      </p>
                    </div>

                    {/* 에러 메시지 */}
                    {entry.status === "error" && entry.error && (
                      <div className="mb-3 p-2 bg-red-100 border border-red-200 rounded-md">
                        <p className="text-xs text-red-700">
                          <span className="font-medium">오류:</span>{" "}
                          {entry.error}
                        </p>
                      </div>
                    )}

                    {/* 재적용 버튼 */}
                    {entry.status === "success" && onReapply && (
                      <div className="mt-3">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => onReapply(entry)}
                          className="w-full text-blue-600 border-blue-200 hover:bg-blue-50"
                          aria-label={`프롬프트 재적용: ${entry.prompt.slice(0, 20)}...`}
                        >
                          🔄 다시 적용
                        </Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default HistoryPanel;
