"use client";

import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  SuggestedQuestion,
  DEFAULT_QUESTIONS,
  CONTEXTUAL_QUESTIONS,
  QuestionAnalytics,
} from "./suggested-questions-config";

interface SuggestedQuestionsProps {
  onQuestionSelect: (question: string) => void;
  context?: string;
  maxQuestions?: number;
  showCategories?: boolean;
  className?: string;
  variant?: "chips" | "list" | "grid";
  disabled?: boolean;
  animateIn?: boolean;
}

export function SuggestedQuestions({
  onQuestionSelect,
  context = "welcome",
  maxQuestions = 3,
  showCategories = false,
  className = "",
  variant = "chips",
  disabled = false,
  animateIn = true,
}: SuggestedQuestionsProps) {
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [isVisible, setIsVisible] = useState(false);

  // Animation effect
  useEffect(() => {
    if (animateIn) {
      const timer = setTimeout(() => setIsVisible(true), 100);
      return () => clearTimeout(timer);
    } else {
      setIsVisible(true);
    }
  }, [animateIn]);

  // Get suggested questions based on context
  const suggestedQuestions = useMemo(() => {
    let questions: SuggestedQuestion[] = [];

    // Try to get contextual questions first
    if (context && CONTEXTUAL_QUESTIONS[context]) {
      questions = [...CONTEXTUAL_QUESTIONS[context]];
    }

    // If no contextual questions or not enough, add from defaults
    if (questions.length < maxQuestions) {
      const remainingSlots = maxQuestions - questions.length;
      const defaultQuestions = DEFAULT_QUESTIONS.filter(
        (q) => !questions.some((cq) => cq.id === q.id)
      ).slice(0, remainingSlots);

      questions = [...questions, ...defaultQuestions];
    }

    // Sort by priority
    questions.sort((a, b) => a.priority - b.priority);

    return questions.slice(0, maxQuestions);
  }, [context, maxQuestions]);

  const handleQuestionClick = useCallback(
    (question: SuggestedQuestion) => {
      if (disabled) return;

      // Track analytics
      QuestionAnalytics.trackQuestionClick(question.id);

      // Execute callback
      onQuestionSelect(question.text);
    },
    [onQuestionSelect, disabled]
  );

  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent, question: SuggestedQuestion) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleQuestionClick(question);
      }
    },
    [handleQuestionClick]
  );

  const renderChips = () => (
    <div className={`flex flex-wrap gap-2 ${className}`}>
      {suggestedQuestions.map((question, index) => (
        <button
          key={question.id}
          onClick={() => handleQuestionClick(question)}
          onKeyDown={(e) => handleKeyDown(e, question)}
          disabled={disabled}
          className={`
            px-4 py-2 
            bg-blue-50 hover:bg-blue-100 
            text-blue-700 hover:text-blue-800
            border border-blue-200 hover:border-blue-300
            rounded-full 
            text-sm 
            font-medium
            transition-all 
            duration-200 
            focus:outline-none 
            focus:ring-2 
            focus:ring-blue-500 
            focus:ring-offset-2
            disabled:opacity-50 
            disabled:cursor-not-allowed
            transform 
            hover:scale-105 
            active:scale-95
            ${
              isVisible
                ? "animate-in slide-in-from-bottom-2 fade-in-0"
                : "opacity-0"
            }
            ${animateIn ? `[animation-delay:${index * 100}ms]` : ""}
          `}
          style={{
            animationDelay: animateIn ? `${index * 100}ms` : "0ms",
          }}
        >
          {question.text}
        </button>
      ))}
    </div>
  );

  const renderList = () => (
    <div className={`space-y-2 ${className}`}>
      {suggestedQuestions.map((question, index) => (
        <button
          key={question.id}
          onClick={() => handleQuestionClick(question)}
          onKeyDown={(e) => handleKeyDown(e, question)}
          disabled={disabled}
          className={`
            w-full 
            text-left 
            p-3 
            bg-gray-50 hover:bg-gray-100
            border border-gray-200 hover:border-gray-300
            rounded-lg 
            text-sm 
            transition-all 
            duration-200
            focus:outline-none 
            focus:ring-2 
            focus:ring-blue-500 
            focus:ring-offset-2
            disabled:opacity-50 
            disabled:cursor-not-allowed
            transform 
            hover:translate-x-1
            ${
              isVisible
                ? "animate-in slide-in-from-left-2 fade-in-0"
                : "opacity-0"
            }
          `}
          style={{
            animationDelay: animateIn ? `${index * 150}ms` : "0ms",
          }}
        >
          <div className="flex items-center space-x-2">
            <span className="text-blue-500">❓</span>
            <span className="text-gray-700">{question.text}</span>
          </div>
        </button>
      ))}
    </div>
  );

  const renderGrid = () => (
    <div className={`grid grid-cols-1 sm:grid-cols-2 gap-3 ${className}`}>
      {suggestedQuestions.map((question, index) => (
        <button
          key={question.id}
          onClick={() => handleQuestionClick(question)}
          onKeyDown={(e) => handleKeyDown(e, question)}
          disabled={disabled}
          className={`
            p-4 
            bg-white hover:bg-gray-50
            border border-gray-200 hover:border-blue-300
            rounded-xl 
            shadow-sm hover:shadow-md
            text-left 
            text-sm 
            transition-all 
            duration-200
            focus:outline-none 
            focus:ring-2 
            focus:ring-blue-500 
            focus:ring-offset-2
            disabled:opacity-50 
            disabled:cursor-not-allowed
            transform 
            hover:scale-105
            ${isVisible ? "animate-in zoom-in-95 fade-in-0" : "opacity-0"}
          `}
          style={{
            animationDelay: animateIn ? `${index * 200}ms` : "0ms",
          }}
        >
          <div className="flex items-start space-x-3">
            <span className="text-blue-500 text-lg">💡</span>
            <div>
              <div className="text-gray-800 font-medium mb-1">
                {question.text}
              </div>
              <div className="text-gray-500 text-xs">{question.category}</div>
            </div>
          </div>
        </button>
      ))}
    </div>
  );

  if (suggestedQuestions.length === 0) {
    return null;
  }

  return (
    <div className="w-full" role="region" aria-label="추천 질문">
      {showCategories && (
        <div className="mb-4">
          <h4 className="text-sm font-medium text-gray-700 mb-2">추천 질문</h4>
        </div>
      )}

      {variant === "chips" && renderChips()}
      {variant === "list" && renderList()}
      {variant === "grid" && renderGrid()}
    </div>
  );
}

// Hook for managing suggested questions state
export function useSuggestedQuestions(initialContext: string = "welcome") {
  const [context, setContext] = useState(initialContext);
  const [isVisible, setIsVisible] = useState(true);

  const updateContext = useCallback((newContext: string) => {
    setContext(newContext);
  }, []);

  const hideQuestions = useCallback(() => {
    setIsVisible(false);
  }, []);

  const showQuestions = useCallback(() => {
    setIsVisible(true);
  }, []);

  const resetQuestions = useCallback(() => {
    setContext("welcome");
    setIsVisible(true);
  }, []);

  return {
    context,
    isVisible,
    updateContext,
    hideQuestions,
    showQuestions,
    resetQuestions,
  };
}

export default SuggestedQuestions;
