'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { Clock, AlertTriangle, Zap } from 'lucide-react';
import { cn } from '@/utils/cn';

interface EnhancedTimerProps {
  className?: string;
  showCircularProgress?: boolean;
  enableAlerts?: boolean;
  enableVibration?: boolean;
  autoSubmitEnabled?: boolean;
}

export default function EnhancedTimer({ 
  className = '',
  showCircularProgress = true,
  enableAlerts = true,
  enableVibration = true,
  autoSubmitEnabled = true
}: EnhancedTimerProps) {
  const { state, formattedTimeRemaining, submitExam } = useExam();
  const [hasWarningShown, setHasWarningShown] = useState(false);
  const [hasCriticalShown, setHasCriticalShown] = useState(false);
  const [hasVibrated, setHasVibrated] = useState(false);

  // Calculate timer states
  const timeRemaining = state.timeRemaining;
  const totalTime = state.examData ? state.examData.duration * 60 : 0;
  const progressPercentage = totalTime > 0 ? ((totalTime - timeRemaining) / totalTime) * 100 : 0;
  
  const isWarning = timeRemaining <= 300 && timeRemaining > 60; // 5 minutes
  const isCritical = timeRemaining <= 60; // 1 minute
  const isExpired = timeRemaining <= 0;

  // Auto-submit when time expires
  useEffect(() => {
    if (isExpired && autoSubmitEnabled && !state.isSubmitted) {
      submitExam();
    }
  }, [isExpired, autoSubmitEnabled, state.isSubmitted, submitExam]);

  // Warning alerts
  useEffect(() => {
    if (!enableAlerts) return;

    if (isWarning && !hasWarningShown && !state.isSubmitted) {
      setHasWarningShown(true);
      // You could add toast notification here
      console.log('Warning: 5 minutes remaining!');
    }

    if (isCritical && !hasCriticalShown && !state.isSubmitted) {
      setHasCriticalShown(true);
      // You could add toast notification here
      console.log('Critical: 1 minute remaining!');
    }
  }, [isWarning, isCritical, hasWarningShown, hasCriticalShown, enableAlerts, state.isSubmitted]);

  // Vibration feedback
  useEffect(() => {
    if (!enableVibration || hasVibrated || state.isSubmitted) return;

    if (isCritical && 'vibrate' in navigator) {
      navigator.vibrate([200, 100, 200, 100, 200]);
      setHasVibrated(true);
    }
  }, [isCritical, enableVibration, hasVibrated, state.isSubmitted]);

  // Reset warning states when timer resets
  useEffect(() => {
    if (timeRemaining > 300) {
      setHasWarningShown(false);
      setHasCriticalShown(false);
      setHasVibrated(false);
    }
  }, [timeRemaining]);

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

  const getTimerColor = () => {
    if (isCritical) return 'text-red-600';
    if (isWarning) return 'text-orange-600';
    return 'text-gray-700';
  };

  const getBackgroundColor = () => {
    if (isCritical) return 'bg-red-50 border-red-200';
    if (isWarning) return 'bg-orange-50 border-orange-200';
    return 'bg-white border-gray-200';
  };

  return (
    <div className={cn(
      'flex items-center space-x-3 px-4 py-3 rounded-lg border transition-all duration-300',
      getBackgroundColor(),
      className
    )}>
      {/* Timer Icon with Status */}
      <div className="relative">
        {isCritical ? (
          <AlertTriangle className={cn('w-6 h-6', getTimerColor())} />
        ) : isWarning ? (
          <Zap className={cn('w-6 h-6', getTimerColor())} />
        ) : (
          <Clock className={cn('w-6 h-6', getTimerColor())} />
        )}
        
        {/* Pulsing animation for critical state */}
        {isCritical && (
          <div className="absolute inset-0 w-6 h-6 bg-red-400 rounded-full animate-ping opacity-20" />
        )}
      </div>

      {/* Circular Progress (Optional) */}
      {showCircularProgress && (
        <div className="relative w-12 h-12">
          <svg className="w-12 h-12 transform -rotate-90" viewBox="0 0 36 36">
            {/* Background circle */}
            <path
              className="text-gray-200"
              stroke="currentColor"
              strokeWidth="3"
              fill="none"
              d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
            />
            {/* Progress circle */}
            <path
              className={cn(
                'transition-all duration-300',
                isCritical ? 'text-red-500' : isWarning ? 'text-orange-500' : 'text-blue-500'
              )}
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              fill="none"
              strokeDasharray={`${progressPercentage}, 100`}
              d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
            />
          </svg>
          
          {/* Time text in center */}
          <div className="absolute inset-0 flex items-center justify-center">
            <span className={cn('text-xs font-bold', getTimerColor())}>
              {Math.ceil(timeRemaining / 60)}m
            </span>
          </div>
        </div>
      )}

      {/* Time Display */}
      <div className="flex flex-col">
        <div className={cn('text-lg font-mono font-bold', getTimerColor())}>
          {formattedTimeRemaining}
        </div>
        
        {/* Status Text */}
        <div className="text-xs text-gray-500">
          {isCritical ? (
            <span className="text-red-600 font-medium animate-pulse">
              Waktu hampir habis!
            </span>
          ) : isWarning ? (
            <span className="text-orange-600 font-medium">
              Perhatikan waktu
            </span>
          ) : (
            'Sisa waktu'
          )}
        </div>
      </div>

      {/* Auto-submit indicator */}
      {autoSubmitEnabled && (
        <div className="text-xs text-gray-400 ml-auto">
          <div className="flex items-center space-x-1">
            <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
            <span>Auto-submit</span>
          </div>
        </div>
      )}
    </div>
  );
}