'use client';

import React, { useState, useEffect } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { 
  Save, 
  Check, 
  AlertCircle, 
  Wifi, 
  WifiOff, 
  Clock, 
  RefreshCw,
  Cloud,
  CloudOff,
  Loader2
} from 'lucide-react';
import { cn } from '@/utils/cn';

interface AutoSaveIndicatorProps {
  className?: string;
  position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'inline';
  showDetails?: boolean;
  compact?: boolean;
}

export default function AutoSaveIndicator({
  className = '',
  position = 'top-right',
  showDetails = false,
  compact = false
}: AutoSaveIndicatorProps) {
  const { state } = useExam();
  const [showTooltip, setShowTooltip] = useState(false);
  const [lastSaveTime, setLastSaveTime] = useState<Date | null>(null);

  // Simulate autosave functionality
  useEffect(() => {
    if (state.autosave.saveStatus === 'saved') {
      setLastSaveTime(new Date());
    }
  }, [state.autosave.saveStatus]);

  const getStatusConfig = () => {
    const { saveStatus, isOnline, saveError, pendingChanges } = state.autosave;

    if (!isOnline) {
      return {
        icon: <WifiOff className="w-4 h-4" />,
        text: 'Offline',
        description: 'Tidak ada koneksi internet. Perubahan akan disimpan saat online kembali.',
        color: 'text-gray-500',
        bgColor: 'bg-gray-100',
        borderColor: 'border-gray-300'
      };
    }

    if (saveError) {
      return {
        icon: <AlertCircle className="w-4 h-4" />,
        text: 'Error',
        description: `Gagal menyimpan: ${saveError}`,
        color: 'text-red-600',
        bgColor: 'bg-red-50',
        borderColor: 'border-red-200'
      };
    }

    switch (saveStatus) {
      case 'saving':
        return {
          icon: <Loader2 className="w-4 h-4 animate-spin" />,
          text: 'Menyimpan...',
          description: 'Sedang menyimpan perubahan ke server.',
          color: 'text-blue-600',
          bgColor: 'bg-blue-50',
          borderColor: 'border-blue-200'
        };

      case 'saved':
        return {
          icon: <Check className="w-4 h-4" />,
          text: 'Tersimpan',
          description: 'Semua perubahan telah disimpan otomatis.',
          color: 'text-green-600',
          bgColor: 'bg-green-50',
          borderColor: 'border-green-200'
        };



      default:
        return {
          icon: <Save className="w-4 h-4" />,
          text: 'Siap',
          description: 'Sistem autosave aktif.',
          color: 'text-gray-600',
          bgColor: 'bg-gray-50',
          borderColor: 'border-gray-200'
        };
    }
  };

  const getPositionClasses = () => {
    if (position === 'inline') return '';
    
    const baseClasses = 'fixed z-50';
    switch (position) {
      case 'top-left':
        return `${baseClasses} top-4 left-4`;
      case 'top-right':
        return `${baseClasses} top-4 right-4`;
      case 'bottom-left':
        return `${baseClasses} bottom-4 left-4`;
      case 'bottom-right':
        return `${baseClasses} bottom-4 right-4`;
      default:
        return `${baseClasses} top-4 right-4`;
    }
  };

  const formatLastSaveTime = () => {
    if (!lastSaveTime) return '';
    
    const now = new Date();
    const diffMs = now.getTime() - lastSaveTime.getTime();
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);

    if (diffSeconds < 60) {
      return `${diffSeconds} detik yang lalu`;
    } else if (diffMinutes < 60) {
      return `${diffMinutes} menit yang lalu`;
    } else {
      return lastSaveTime.toLocaleTimeString('id-ID', {
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  };

  const statusConfig = getStatusConfig();
  const positionClasses = getPositionClasses();

  if (compact) {
    return (
      <div 
        className={cn(
          positionClasses,
          'flex items-center space-x-2 px-2 py-1 rounded-full border shadow-sm transition-all duration-200',
          statusConfig.bgColor,
          statusConfig.borderColor,
          className
        )}
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
      >
        <div className={statusConfig.color}>
          {statusConfig.icon}
        </div>
        
        {!state.autosave.isOnline && (
          <WifiOff className="w-3 h-3 text-gray-400" />
        )}

        {showTooltip && (
          <div className="absolute bottom-full mb-2 left-1/2 transform -translate-x-1/2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg shadow-lg whitespace-nowrap z-10">
            <div className="font-medium">{statusConfig.text}</div>
            <div className="text-gray-300">{statusConfig.description}</div>
            {lastSaveTime && (
              <div className="text-gray-400 mt-1">
                Terakhir disimpan: {formatLastSaveTime()}
              </div>
            )}
            <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900"></div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className={cn(positionClasses, className)}>
      <div 
        className={cn(
          'flex items-center space-x-3 px-4 py-3 rounded-lg border shadow-sm transition-all duration-200 min-w-[200px]',
          statusConfig.bgColor,
          statusConfig.borderColor
        )}
      >
        {/* Status Icon */}
        <div className={cn('flex-shrink-0', statusConfig.color)}>
          {statusConfig.icon}
        </div>

        {/* Status Content */}
        <div className="flex-1 min-w-0">
          <div className={cn('text-sm font-medium', statusConfig.color)}>
            {statusConfig.text}
          </div>
          
          {showDetails && (
            <div className="text-xs text-gray-600 mt-1">
              {statusConfig.description}
            </div>
          )}

          {lastSaveTime && state.autosave.saveStatus === 'saved' && (
            <div className="text-xs text-gray-500 mt-1">
              {formatLastSaveTime()}
            </div>
          )}
        </div>

        {/* Connection Status */}
        <div className="flex-shrink-0">
          {state.autosave.isOnline ? (
            <Cloud className="w-4 h-4 text-green-500" />
          ) : (
            <CloudOff className="w-4 h-4 text-gray-400" />
          )}
        </div>
      </div>

      {/* Detailed Information Panel */}
      {showDetails && (
        <div className="mt-2 p-3 bg-white rounded-lg border border-gray-200 shadow-sm">
          <div className="space-y-2 text-xs">
            <div className="flex items-center justify-between">
              <span className="text-gray-600">Status Koneksi:</span>
              <div className="flex items-center space-x-1">
                {state.autosave.isOnline ? (
                  <>
                    <Wifi className="w-3 h-3 text-green-500" />
                    <span className="text-green-600">Online</span>
                  </>
                ) : (
                  <>
                    <WifiOff className="w-3 h-3 text-red-500" />
                    <span className="text-red-600">Offline</span>
                  </>
                )}
              </div>
            </div>

            <div className="flex items-center justify-between">
              <span className="text-gray-600">Perubahan Tertunda:</span>
              <span className={state.autosave.pendingChanges ? 'text-yellow-600' : 'text-green-600'}>
                {state.autosave.pendingChanges ? 'Ya' : 'Tidak'}
              </span>
            </div>

            {state.autosave.lastSaved && (
              <div className="flex items-center justify-between">
                <span className="text-gray-600">Terakhir Disimpan:</span>
                <span className="text-gray-900">
                  {new Date(state.autosave.lastSaved).toLocaleString('id-ID')}
                </span>
              </div>
            )}

            {state.autosave.saveError && (
              <div className="pt-2 border-t border-gray-100">
                <div className="flex items-start space-x-2">
                  <AlertCircle className="w-3 h-3 text-red-500 mt-0.5 flex-shrink-0" />
                  <div>
                    <div className="text-red-600 font-medium">Error:</div>
                    <div className="text-red-600">{state.autosave.saveError}</div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Retry Button for Errors */}
          {state.autosave.saveError && (
            <div className="mt-3 pt-3 border-t border-gray-100">
              <button
                onClick={() => {
                  // This would trigger a retry of the save operation
                  // dispatch({ type: 'RETRY_SAVE' });
                }}
                className="flex items-center space-x-2 px-3 py-1.5 text-xs font-medium text-blue-600 bg-blue-50 rounded-md hover:bg-blue-100 transition-colors"
              >
                <RefreshCw className="w-3 h-3" />
                <span>Coba Lagi</span>
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}