import React from 'react';
import { HStack, Text, Spinner, Icon, Tooltip } from '@chakra-ui/react';
import { FiCheck, FiAlertCircle, FiClock } from 'react-icons/fi';
import type { SaveStatus } from '../../hooks/useAutoSave';

interface SaveStatusIndicatorProps {
  status: SaveStatus;
  lastSaved: Date | null;
  compact?: boolean;
}

const SaveStatusIndicator: React.FC<SaveStatusIndicatorProps> = ({
  status,
  lastSaved,
  compact = false,
}) => {
  const getStatusDisplay = () => {
    switch (status) {
      case 'saving':
        return {
          icon: <Spinner size="xs" color="blue.500" />,
          text: 'Ukládání...',
          color: 'blue.500',
        };
      case 'saved':
        return {
          icon: <Icon as={FiCheck} color="green.500" />,
          text: 'Uloženo',
          color: 'green.500',
        };
      case 'error':
        return {
          icon: <Icon as={FiAlertCircle} color="orange.500" />,
          text: 'Uloženo lokálně',
          color: 'orange.500',
        };
      default:
        return {
          icon: <Icon as={FiClock} color="gray.400" />,
          text: 'Čeká se na změny...',
          color: 'gray.400',
        };
    }
  };

  const { icon, text, color } = getStatusDisplay();

  const getLastSavedText = () => {
    if (!lastSaved) return null;
    
    const now = new Date();
    const diff = Math.floor((now.getTime() - lastSaved.getTime()) / 1000); // seconds
    
    if (diff < 60) return 'před chvílí';
    if (diff < 3600) return `před ${Math.floor(diff / 60)} min`;
    if (diff < 86400) return `před ${Math.floor(diff / 3600)} h`;
    return lastSaved.toLocaleString('cs-CZ', { 
      day: 'numeric', 
      month: 'short', 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  const lastSavedText = getLastSavedText();

  if (compact) {
    return (
      <Tooltip 
        label={lastSavedText ? `${text} ${lastSavedText}` : text}
        hasArrow
      >
        <HStack spacing={1}>
          {icon}
        </HStack>
      </Tooltip>
    );
  }

  return (
    <HStack spacing={2} fontSize="sm">
      {icon}
      <Text color={color} fontWeight="medium">
        {text}
      </Text>
      {lastSavedText && status === 'saved' && (
        <Text color="gray.500" fontSize="xs">
          {lastSavedText}
        </Text>
      )}
    </HStack>
  );
};

export default SaveStatusIndicator;
