import React, { useState } from 'react';
import { RefreshCw, CheckCircle, AlertCircle, Clock, TrendingUp, Loader2 } from 'lucide-react';
import { Card } from '../../ui';
import { showToast } from '../../../utils/toast';
import { posService } from '../../../api/services/pos';

interface POSSyncStatusProps {
  tenantId: string;
  onSyncComplete?: () => void;
}

interface SyncStatus {
  total_completed_transactions: number;
  synced_to_sales: number;
  pending_sync: number;
  sync_rate: number;
}

export const POSSyncStatus: React.FC<POSSyncStatusProps> = ({ tenantId, onSyncComplete }) => {
  const [status, setStatus] = useState<SyncStatus | null>(null);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);

  const fetchSyncStatus = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `/api/v1/pos/tenants/${tenantId}/pos/transactions/sync-status`,
        {
          headers: {
            'Content-Type': 'application/json',
            // Add auth headers as needed
          },
        }
      );

      if (!response.ok) {
        throw new Error('Failed to fetch sync status');
      }

      const data = await response.json();
      setStatus(data);
      setLastUpdated(new Date());
    } catch (error: any) {
      console.error('Error fetching sync status:', error);
      showToast.error('Error al obtener estado de sincronización');
    } finally {
      setLoading(false);
    }
  };

  const triggerSync = async () => {
    setSyncing(true);
    try {
      const response = await fetch(
        `/api/v1/pos/tenants/${tenantId}/pos/transactions/sync-all-to-sales`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // Add auth headers as needed
          },
        }
      );

      if (!response.ok) {
        throw new Error('Sync failed');
      }

      const result = await response.json();

      showToast.success(
        `Sincronización completada: ${result.synced} de ${result.total_transactions} transacciones`
      );

      // Refresh status after sync
      await fetchSyncStatus();

      if (onSyncComplete) {
        onSyncComplete();
      }
    } catch (error: any) {
      console.error('Error during sync:', error);
      showToast.error('Error al sincronizar transacciones');
    } finally {
      setSyncing(false);
    }
  };

  React.useEffect(() => {
    if (tenantId) {
      fetchSyncStatus();

      // Auto-refresh every 30 seconds
      const interval = setInterval(fetchSyncStatus, 30000);
      return () => clearInterval(interval);
    }
  }, [tenantId]);

  if (loading && !status) {
    return (
      <Card className="p-6">
        <div className="flex items-center justify-center">
          <Loader2 className="w-6 h-6 animate-spin text-[var(--color-primary)]" />
          <span className="ml-3 text-[var(--text-secondary)]">Cargando estado...</span>
        </div>
      </Card>
    );
  }

  if (!status) {
    return null;
  }

  const hasPendingSync = status.pending_sync > 0;

  return (
    <Card className="p-6">
      <div className="space-y-4">
        {/* Header */}
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] flex items-center">
            <RefreshCw className="w-5 h-5 mr-2 text-blue-500" />
            Estado de Sincronización POS → Ventas
          </h3>
          <button
            onClick={fetchSyncStatus}
            disabled={loading}
            className="p-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors disabled:opacity-50"
            title="Actualizar estado"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Total Transactions */}
          <div className="p-4 bg-[var(--bg-secondary)] rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm text-[var(--text-secondary)]">Total Transacciones</span>
              <Clock className="w-4 h-4 text-gray-400" />
            </div>
            <div className="text-2xl font-bold text-[var(--text-primary)]">
              {status.total_completed_transactions}
            </div>
          </div>

          {/* Synced */}
          <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm text-green-700 dark:text-green-400">Sincronizadas</span>
              <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400" />
            </div>
            <div className="text-2xl font-bold text-green-800 dark:text-green-300">
              {status.synced_to_sales}
            </div>
          </div>

          {/* Pending */}
          <div
            className={`p-4 rounded-lg ${
              hasPendingSync
                ? 'bg-orange-50 dark:bg-orange-900/20'
                : 'bg-gray-50 dark:bg-gray-800'
            }`}
          >
            <div className="flex items-center justify-between mb-2">
              <span
                className={`text-sm ${
                  hasPendingSync
                    ? 'text-orange-700 dark:text-orange-400'
                    : 'text-gray-500 dark:text-gray-400'
                }`}
              >
                Pendientes
              </span>
              <AlertCircle
                className={`w-4 h-4 ${
                  hasPendingSync
                    ? 'text-orange-600 dark:text-orange-400'
                    : 'text-gray-400'
                }`}
              />
            </div>
            <div
              className={`text-2xl font-bold ${
                hasPendingSync
                  ? 'text-orange-800 dark:text-orange-300'
                  : 'text-gray-600 dark:text-gray-300'
              }`}
            >
              {status.pending_sync}
            </div>
          </div>
        </div>

        {/* Sync Rate */}
        <div className="p-4 bg-[var(--bg-secondary)] rounded-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-[var(--text-secondary)]">Tasa de Sincronización</span>
            <TrendingUp className="w-4 h-4 text-blue-500" />
          </div>
          <div className="flex items-center">
            <div className="flex-1">
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div
                  className="bg-green-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${status.sync_rate}%` }}
                />
              </div>
            </div>
            <span className="ml-3 text-lg font-semibold text-[var(--text-primary)]">
              {status.sync_rate.toFixed(1)}%
            </span>
          </div>
        </div>

        {/* Actions */}
        {hasPendingSync && (
          <div className="flex items-center justify-between pt-4 border-t border-[var(--border-primary)]">
            <div className="text-sm text-[var(--text-secondary)]">
              {status.pending_sync} transacción{status.pending_sync !== 1 ? 'es' : ''} esperando
              sincronización
            </div>
            <button
              onClick={triggerSync}
              disabled={syncing}
              className="px-4 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors inline-flex items-center gap-2"
            >
              {syncing ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Sincronizando...
                </>
              ) : (
                <>
                  <RefreshCw className="w-4 h-4" />
                  Sincronizar Ahora
                </>
              )}
            </button>
          </div>
        )}

        {/* Last Updated */}
        {lastUpdated && (
          <div className="text-xs text-[var(--text-tertiary)] text-center">
            Última actualización: {lastUpdated.toLocaleTimeString('es-ES')}
          </div>
        )}
      </div>
    </Card>
  );
};
