'use client';

import React, { useState } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { 
  Search, 
  Filter, 
  Grid3X3, 
  List, 
  Flag, 
  Bookmark, 
  CheckCircle, 
  Circle,
  Eye,
  ChevronLeft,
  ChevronRight
} from 'lucide-react';
import { cn } from '@/utils/cn';

interface EnhancedQuestionNavigatorProps {
  className?: string;
  showSearch?: boolean;
  showFilters?: boolean;
  showViewToggle?: boolean;
  compact?: boolean;
}

export default function EnhancedQuestionNavigator({
  className = '',
  showSearch = true,
  showFilters = true,
  showViewToggle = true,
  compact = false
}: EnhancedQuestionNavigatorProps) {
  const { 
    state, 
    goToQuestion, 
    toggleBookmark,
    setSearchQuery,
    setFilterMode,
    setViewMode,
    filteredQuestions,
    answeredCount,
    flaggedCount,
    bookmarkedCount
  } = useExam();

  const [localSearch, setLocalSearch] = useState(state.navigation.searchQuery);

  if (!state.examData) {
    return null;
  }

  const totalQuestions = state.examData.questions.length;
  const currentQuestion = state.currentQuestion;

  const getQuestionStatus = (questionIndex: number) => {
    if (questionIndex === currentQuestion) return 'current';
    if (questionIndex in state.answers) {
      if (state.flaggedQuestions.has(questionIndex)) return 'answered-flagged';
      return 'answered';
    }
    if (state.flaggedQuestions.has(questionIndex)) return 'flagged';
    return 'unanswered';
  };

  const getQuestionButtonClass = (questionIndex: number, status: string) => {
    const baseClass = compact 
      ? 'w-8 h-8 text-xs' 
      : 'w-10 h-10 text-sm';
    
    const commonClass = `${baseClass} rounded-lg border-2 flex items-center justify-center font-medium cursor-pointer transition-all duration-200 hover:scale-105 relative`;
    
    switch (status) {
      case 'current':
        return cn(commonClass, 'bg-blue-500 border-blue-500 text-white shadow-lg ring-2 ring-blue-200');
      case 'answered':
        return cn(commonClass, 'bg-green-500 border-green-500 text-white');
      case 'answered-flagged':
        return cn(commonClass, 'bg-orange-500 border-orange-500 text-white');
      case 'flagged':
        return cn(commonClass, 'bg-yellow-400 border-yellow-400 text-gray-800');
      case 'unanswered':
      default:
        return cn(commonClass, 'bg-gray-100 border-gray-300 text-gray-600 hover:bg-gray-200');
    }
  };

  const handleSearchChange = (value: string) => {
    setLocalSearch(value);
    setSearchQuery(value);
  };

  const handleQuestionClick = (questionIndex: number) => {
    goToQuestion(questionIndex);
  };

  const handleBookmarkToggle = (questionIndex: number, e: React.MouseEvent) => {
    e.stopPropagation();
    toggleBookmark(questionIndex);
  };

  const getFilteredQuestionIndices = () => {
    let indices = Array.from({ length: totalQuestions }, (_, i) => i);
    
    // Apply search filter
    if (localSearch) {
      const searchNum = parseInt(localSearch);
      if (!isNaN(searchNum)) {
        indices = indices.filter(i => (i + 1).toString().includes(localSearch));
      }
    }
    
    // Apply status filter
    return indices.filter(index => {
      const isAnswered = index in state.answers;
      const isFlagged = state.flaggedQuestions.has(index);
      const isBookmarked = state.bookmarkedQuestions.has(index);
      
      switch (state.navigation.filterMode) {
        case 'answered':
          return isAnswered;
        case 'unanswered':
          return !isAnswered;
        case 'flagged':
          return isFlagged;
        case 'bookmarked':
          return isBookmarked;
        default:
          return true;
      }
    });
  };

  const displayQuestions = getFilteredQuestionIndices();

  return (
    <div className={cn('bg-white rounded-lg shadow-sm border', className)}>
      {/* Header */}
      <div className="p-4 border-b border-gray-100">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold text-gray-800">
            Navigasi Soal
          </h3>
          
          {showViewToggle && (
            <div className="flex items-center space-x-1 bg-gray-100 rounded-lg p-1">
              <button
                onClick={() => setViewMode('grid')}
                className={cn(
                  'p-1.5 rounded transition-colors',
                  state.navigation.questionViewMode === 'grid'
                    ? 'bg-white text-blue-600 shadow-sm'
                    : 'text-gray-500 hover:text-gray-700'
                )}
              >
                <Grid3X3 className="w-4 h-4" />
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={cn(
                  'p-1.5 rounded transition-colors',
                  state.navigation.questionViewMode === 'list'
                    ? 'bg-white text-blue-600 shadow-sm'
                    : 'text-gray-500 hover:text-gray-700'
                )}
              >
                <List className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>

        {/* Search */}
        {showSearch && (
          <div className="relative mb-3">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Cari nomor soal..."
              value={localSearch}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        )}

        {/* Filters */}
        {showFilters && (
          <div className="flex items-center space-x-2">
            <Filter className="w-4 h-4 text-gray-500" />
            <select
              value={state.navigation.filterMode}
              onChange={(e) => setFilterMode(e.target.value as any)}
              className="text-sm border border-gray-200 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">Semua ({totalQuestions})</option>
              <option value="answered">Terjawab ({answeredCount})</option>
              <option value="unanswered">Belum Dijawab ({totalQuestions - answeredCount})</option>
              <option value="flagged">Ditandai ({flaggedCount})</option>
              <option value="bookmarked">Bookmark ({bookmarkedCount})</option>
            </select>
          </div>
        )}
      </div>

      {/* Question Display */}
      <div className="p-4">
        {state.navigation.questionViewMode === 'grid' ? (
          /* Grid View */
          <div className={cn(
            'grid gap-3 mb-6',
            compact ? 'grid-cols-8' : 'grid-cols-5'
          )}>
            {displayQuestions.map((questionIndex) => {
              const status = getQuestionStatus(questionIndex);
              const isBookmarked = state.bookmarkedQuestions.has(questionIndex);
              
              return (
                <div key={questionIndex} className="relative">
                  <button
                    onClick={() => handleQuestionClick(questionIndex)}
                    className={getQuestionButtonClass(questionIndex, status)}
                    title={`Soal ${questionIndex + 1} - ${status}`}
                  >
                    {questionIndex + 1}
                    
                    {/* Bookmark indicator */}
                    {isBookmarked && (
                      <Bookmark 
                        className="absolute -top-1 -right-1 w-3 h-3 text-purple-500 fill-current" 
                      />
                    )}
                  </button>
                  
                  {/* Bookmark toggle button */}
                  <button
                    onClick={(e) => handleBookmarkToggle(questionIndex, e)}
                    className="absolute -bottom-1 -right-1 w-4 h-4 bg-white border border-gray-200 rounded-full flex items-center justify-center hover:bg-purple-50 transition-colors"
                    title={isBookmarked ? 'Hapus bookmark' : 'Tambah bookmark'}
                  >
                    <Bookmark 
                      className={cn(
                        'w-2.5 h-2.5',
                        isBookmarked ? 'text-purple-500 fill-current' : 'text-gray-400'
                      )} 
                    />
                  </button>
                </div>
              );
            })}
          </div>
        ) : (
          /* List View */
          <div className="space-y-2 mb-6">
            {displayQuestions.map((questionIndex) => {
              const status = getQuestionStatus(questionIndex);
              const isBookmarked = state.bookmarkedQuestions.has(questionIndex);
              
              return (
                <div
                  key={questionIndex}
                  onClick={() => handleQuestionClick(questionIndex)}
                  className={cn(
                    'flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-all duration-200 hover:shadow-sm',
                    questionIndex === currentQuestion 
                      ? 'bg-blue-50 border-blue-200' 
                      : 'bg-gray-50 border-gray-200 hover:bg-gray-100'
                  )}
                >
                  <div className="flex items-center space-x-3">
                    <div className={cn(
                      'w-8 h-8 rounded-lg flex items-center justify-center text-sm font-medium',
                      getQuestionButtonClass(questionIndex, status).split(' ').slice(-6).join(' ')
                    )}>
                      {questionIndex + 1}
                    </div>
                    
                    <div>
                      <div className="text-sm font-medium text-gray-900">
                        Soal {questionIndex + 1}
                      </div>
                      <div className="text-xs text-gray-500 capitalize">
                        {status.replace('-', ' & ')}
                      </div>
                    </div>
                  </div>
                  
                  <div className="flex items-center space-x-2">
                    {questionIndex in state.answers && (
                      <CheckCircle className="w-4 h-4 text-green-500" />
                    )}
                    {state.flaggedQuestions.has(questionIndex) && (
                      <Flag className="w-4 h-4 text-orange-500" />
                    )}
                    <button
                      onClick={(e) => handleBookmarkToggle(questionIndex, e)}
                      className="p-1 hover:bg-purple-50 rounded transition-colors"
                    >
                      <Bookmark 
                        className={cn(
                          'w-4 h-4',
                          isBookmarked ? 'text-purple-500 fill-current' : 'text-gray-400'
                        )} 
                      />
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* Navigation Controls */}
        <div className="flex items-center justify-between pt-4 border-t border-gray-100">
          <button
            onClick={() => goToQuestion(Math.max(0, currentQuestion - 1))}
            disabled={currentQuestion === 0}
            className="flex items-center space-x-2 px-3 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronLeft className="w-4 h-4" />
            <span>Sebelumnya</span>
          </button>
          
          <div className="text-sm text-gray-500">
            {currentQuestion + 1} dari {totalQuestions}
          </div>
          
          <button
            onClick={() => goToQuestion(Math.min(totalQuestions - 1, currentQuestion + 1))}
            disabled={currentQuestion === totalQuestions - 1}
            className="flex items-center space-x-2 px-3 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <span>Selanjutnya</span>
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Legend */}
      <div className="p-4 bg-gray-50 rounded-b-lg">
        <h4 className="text-sm font-medium text-gray-700 mb-2">Keterangan:</h4>
        <div className="grid grid-cols-2 gap-2 text-xs">
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded bg-blue-500"></div>
            <span className="text-gray-600">Soal Aktif</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded bg-green-500"></div>
            <span className="text-gray-600">Terjawab</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded bg-yellow-400"></div>
            <span className="text-gray-600">Ditandai</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded bg-orange-500"></div>
            <span className="text-gray-600">Terjawab & Ditandai</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 rounded bg-gray-100 border border-gray-300"></div>
            <span className="text-gray-600">Belum Dijawab</span>
          </div>
          <div className="flex items-center gap-2">
            <Bookmark className="w-4 h-4 text-purple-500 fill-current" />
            <span className="text-gray-600">Bookmark</span>
          </div>
        </div>
      </div>
    </div>
  );
}