import React, { useState, useMemo } from 'react';
import { useSource, useAppState, useAction } from './sdk';
import { Badge, Metric, Glass, Icon } from './components';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { TrendingUp, DollarSign, RefreshCw, AlertCircle, CheckCircle, Clock, Package, FileText, ArrowRightLeft, Shield, Zap } from 'lucide-react';

// Mock data for when no live data is available
const MOCK_SYNC_OPERATIONS = [
  { id: 'sync-001', timestamp: '2024-01-15T10:30:00Z', type: 'Order Sync', status: 'completed', shopifyId: 'ORD-1001', qbId: 'INV-5001', amount: 1250.00, items: 3, duration: 2.3 },
  { id: 'sync-002', timestamp: '2024-01-15T11:15:00Z', type: 'Product Sync', status: 'completed', shopifyId: 'PRD-2001', qbId: 'ITEM-3001', amount: 0, items: 1, duration: 1.1 },
  { id: 'sync-003', timestamp: '2024-01-15T12:00:00Z', type: 'Order Sync', status: 'failed', shopifyId: 'ORD-1002', qbId: null, amount: 890.50, items: 2, duration: 0.5, error: 'Customer not found in QuickBooks' },
  { id: 'sync-004', timestamp: '2024-01-15T13:45:00Z', type: 'Inventory Sync', status: 'completed', shopifyId: 'INV-3001', qbId: 'ADJ-4001', amount: 0, items: 15, duration: 3.2 },
  { id: 'sync-005', timestamp: '2024-01-15T14:20:00Z', type: 'Order Sync', status: 'pending', shopifyId: 'ORD-1003', qbId: null, amount: 2100.00, items: 5, duration: 0 },
  { id: 'sync-006', timestamp: '2024-01-15T15:00:00Z', type: 'Refund Sync', status: 'completed', shopifyId: 'REF-4001', qbId: 'CR-6001', amount: -350.00, items: 1, duration: 1.8 },
  { id: 'sync-007', timestamp: '2024-01-15T15:30:00Z', type: 'Order Sync', status: 'completed', shopifyId: 'ORD-1004', qbId: 'INV-5002', amount: 675.25, items: 2, duration: 1.5 },
  { id: 'sync-008', timestamp: '2024-01-15T16:10:00Z', type: 'Product Sync', status: 'warning', shopifyId: 'PRD-2002', qbId: 'ITEM-3002', amount: 0, items: 1, duration: 4.5, error: 'Price mismatch detected' },
];

const MOCK_CHART_DATA = [
  { time: '09:00', orders: 12, products: 5, inventory: 3 },
  { time: '10:00', orders: 18, products: 8, inventory: 6 },
  { time: '11:00', orders: 25, products: 12, inventory: 9 },
  { time: '12:00', orders: 22, products: 10, inventory: 7 },
  { time: '13:00', orders: 30, products: 15, inventory: 11 },
  { time: '14:00', orders: 28, products: 14, inventory: 10 },
  { time: '15:00', orders: 35, products: 18, inventory: 14 },
  { time: '16:00', orders: 32, products: 16, inventory: 12 },
];

const STATUS_COLORS = {
  completed: '#10b981',
  failed: '#ef4444',
  pending: '#f59e0b',
  warning: '#f59e0b',
};

const COLORS = ['#8b5cf6', '#06b6d4', '#10b981', '#f59e0b', '#ef4444'];

export default function App() {
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedSync, setSelectedSync] = useState<any | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  
  const { data, loading, error, refetch } = useSource('/api/framework/connections/app/shopify-quickbooks-sync/data', 30000);
  const dispatch = useAction();

  // Use live data if available, otherwise use mock data
  const syncOperations = useMemo(() => {
    const liveData = data?.providers?.shopify?.data || data?.providers?.quickbooks?.data;
    if (liveData && Array.isArray(liveData) && liveData.length > 0) {
      return liveData;
    }
    return MOCK_SYNC_OPERATIONS;
  }, [data]);

  const filteredOperations = useMemo(() => {
    if (filterStatus === 'all') return syncOperations;
    return syncOperations.filter((op: any) => op.status === filterStatus);
  }, [syncOperations, filterStatus]);

  // Calculate KPIs
  const kpis = useMemo(() => {
    const total = syncOperations.length;
    const completed = syncOperations.filter((op: any) => op.status === 'completed').length;
    const failed = syncOperations.filter((op: any) => op.status === 'failed').length;
    const pending = syncOperations.filter((op: any) => op.status === 'pending').length;
    const successRate = total > 0 ? Math.round((completed / total) * 100) : 0;
    const totalValue = syncOperations.reduce((sum: number, op: any) => sum + Math.abs(op.amount || 0), 0);
    const avgDuration = syncOperations.filter((op: any) => op.duration > 0).reduce((sum: number, op: any) => sum + op.duration, 0) / Math.max(1, syncOperations.filter((op: any) => op.duration > 0).length);
    
    return { total, completed, failed, pending, successRate, totalValue, avgDuration: avgDuration.toFixed(1) };
  }, [syncOperations]);

  const statusDistribution = useMemo(() => {
    return [
      { name: 'Completed', value: kpis.completed, color: STATUS_COLORS.completed },
      { name: 'Failed', value: kpis.failed, color: STATUS_COLORS.failed },
      { name: 'Pending', value: kpis.pending, color: STATUS_COLORS.pending },
      { name: 'Warning', value: syncOperations.filter((op: any) => op.status === 'warning').length, color: STATUS_COLORS.warning },
    ].filter(s => s.value > 0);
  }, [kpis, syncOperations]);

  const getStatusBadge = (status: string) => {
    const variants: Record<string, any> = {
      completed: { variant: 'positive' as const, icon: 'check' },
      failed: { variant: 'negative' as const, icon: 'alert' },
      pending: { variant: 'neutral' as const, icon: 'clock' },
      warning: { variant: 'neutral' as const, icon: 'alert' },
    };
    const config = variants[status] || variants.pending;
    return <Badge label={status.charAt(0).toUpperCase() + status.slice(1)} variant={config.variant} icon={config.icon as any} />;
  };

  const handleConnectProvider = (provider: string) => {
    dispatch('oauth', { service: provider });
  };

  // Loading state
  if (loading && !syncOperations.length) {
    return (
      <div className="min-h-screen bg-[#0a0e1a] flex items-center justify-center">
        <div className="text-violet-400 animate-spin text-3xl">
          <RefreshCw size={32} />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#0a0e1a] text-white">
      {/* Header */}
      <header className="border-b border-white/[0.08] px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-violet-500/20 rounded-lg">
              <ArrowRightLeft size={24} className="text-violet-400" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-white">Shopify-QuickBooks Sync Dashboard</h1>
              <p className="text-sm text-slate-400">Real-time synchronization monitoring</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button 
              onClick={() => refetch()}
              className="flex items-center gap-2 px-4 py-2 bg-violet-500/20 text-violet-400 rounded-lg text-sm hover:bg-violet-500/30 transition-colors"
            >
              <RefreshCw size={16} />
              Refresh
            </button>
            <Badge label="Live" variant="positive" icon="radio" />
          </div>
        </div>
        
        {/* Tabs */}
        <div className="flex gap-2 mt-4">
          {['overview', 'operations', 'analytics', 'settings'].map(tab => (
            <button 
              key={tab} 
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                activeTab === tab 
                  ? 'bg-violet-500/20 text-violet-400 border border-violet-500/30' 
                  : 'text-slate-400 hover:text-white hover:bg-white/[0.05]'
              }`}
            >
              {tab.charAt(0).toUpperCase() + tab.slice(1)}
            </button>
          ))}
        </div>
      </header>

      <div className="p-6 space-y-6">
        {/* Connection Status Banner */}
        {error && (
          <Glass className="p-4 border border-amber-500/30 bg-amber-500/10">
            <div className="flex items-center gap-3">
              <AlertCircle size={20} className="text-amber-400" />
              <div>
                <p className="text-sm text-amber-200">Live data unavailable. Showing demo data.</p>
                <p className="text-xs text-amber-400/80 mt-1">Connect Shopify and QuickBooks to see real sync operations.</p>
              </div>
              <div className="ml-auto flex gap-2">
                <button onClick={() => handleConnectProvider('shopify')} className="px-3 py-1.5 bg-violet-500/20 text-violet-400 rounded text-xs hover:bg-violet-500/30">
                  Connect Shopify
                </button>
                <button onClick={() => handleConnectProvider('quickbooks')} className="px-3 py-1.5 bg-emerald-500/20 text-emerald-400 rounded text-xs hover:bg-emerald-500/30">
                  Connect QuickBooks
                </button>
              </div>
            </div>
          </Glass>
        )}

        {/* KPI Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Glass className="p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm text-slate-400">Total Syncs</span>
              <Package size={20} className="text-violet-400" />
            </div>
            <div className="text-3xl font-bold text-white">{kpis.total}</div>
            <div className="text-xs text-slate-500 mt-1">Last 24 hours</div>
          </Glass>
          
          <Glass className="p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm text-slate-400">Success Rate</span>
              <CheckCircle size={20} className="text-emerald-400" />
            </div>
            <div className="text-3xl font-bold text-white">{kpis.successRate}%</div>
            <div className="text-xs text-emerald-400 mt-1 flex items-center gap-1">
              <TrendingUp size={12} />
              {kpis.completed} completed
            </div>
          </Glass>
          
          <Glass className="p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm text-slate-400">Total Value</span>
              <DollarSign size={20} className="text-cyan-400" />
            </div>
            <div className="text-3xl font-bold text-white">${kpis.totalValue.toLocaleString()}</div>
            <div className="text-xs text-slate-500 mt-1">Synced transactions</div>
          </Glass>
          
          <Glass className="p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm text-slate-400">Avg Duration</span>
              <Clock size={20} className="text-amber-400" />
            </div>
            <div className="text-3xl font-bold text-white">{kpis.avgDuration}s</div>
            <div className="text-xs text-slate-500 mt-1">Per sync operation</div>
          </Glass>
        </div>

        {/* Overview Tab */}
        {activeTab === 'overview' && (
          <>
            {/* Charts Row */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              <Glass className="p-5">
                <div className="flex items-center gap-2 mb-4">
                  <Zap size={18} className="text-violet-400" />
                  <h2 className="text-lg font-semibold text-white">Sync Activity Over Time</h2>
                </div>
                <ResponsiveContainer width="100%" height={280}>
                  <LineChart data={MOCK_CHART_DATA}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                    <XAxis dataKey="time" stroke="#64748b" fontSize={12} />
                    <YAxis stroke="#64748b" fontSize={12} />
                    <Tooltip 
                      contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                      labelStyle={{ color: '#fff' }}
                    />
                    <Legend />
                    <Line type="monotone" dataKey="orders" stroke="#8b5cf6" strokeWidth={2} dot={{ fill: '#8b5cf6' }} name="Orders" />
                    <Line type="monotone" dataKey="products" stroke="#06b6d4" strokeWidth={2} dot={{ fill: '#06b6d4' }} name="Products" />
                    <Line type="monotone" dataKey="inventory" stroke="#10b981" strokeWidth={2} dot={{ fill: '#10b981' }} name="Inventory" />
                  </LineChart>
                </ResponsiveContainer>
              </Glass>
              
              <Glass className="p-5">
                <div className="flex items-center gap-2 mb-4">
                  <Shield size={18} className="text-cyan-400" />
                  <h2 className="text-lg font-semibold text-white">Status Distribution</h2>
                </div>
                <ResponsiveContainer width="100%" height={280}>
                  <PieChart>
                    <Pie
                      data={statusDistribution}
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={100}
                      paddingAngle={5}
                      dataKey="value"
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                      labelLine={false}
                    >
                      {statusDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip 
                      contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </Glass>
            </div>

            {/* Recent Operations Table */}
            <Glass className="p-5">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <FileText size={18} className="text-violet-400" />
                  <h2 className="text-lg font-semibold text-white">Recent Sync Operations</h2>
                </div>
                <div className="flex gap-2">
                  {['all', 'completed', 'failed', 'pending'].map(status => (
                    <button
                      key={status}
                      onClick={() => setFilterStatus(status)}
                      className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${
                        filterStatus === status
                          ? 'bg-violet-500/20 text-violet-400'
                          : 'text-slate-400 hover:text-white hover:bg-white/[0.05]'
                      }`}
                    >
                      {status.charAt(0).toUpperCase() + status.slice(1)}
                    </button>
                  ))}
                </div>
              </div>
              
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-white/[0.08] text-slate-400 text-xs">
                      <th className="text-left py-3 px-4">Type</th>
                      <th className="text-left py-3 px-4">Status</th>
                      <th className="text-left py-3 px-4">Shopify ID</th>
                      <th className="text-left py-3 px-4">QB ID</th>
                      <th className="text-right py-3 px-4">Amount</th>
                      <th className="text-right py-3 px-4">Duration</th>
                      <th className="text-left py-3 px-4">Time</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredOperations.slice(0, 10).map((op: any) => (
                      <tr 
                        key={op.id} 
                        className="border-b border-white/[0.04] hover:bg-white/[0.02] cursor-pointer transition-colors"
                        onClick={() => setSelectedSync(op)}
                      >
                        <td className="py-3 px-4">
                          <div className="flex items-center gap-2">
                            <Icon name={op.type.includes('Order') ? 'package' : op.type.includes('Product') ? 'tag' : 'layers'} size={16} className="text-slate-400" />
                            <span className="text-white">{op.type}</span>
                          </div>
                        </td>
                        <td className="py-3 px-4">{getStatusBadge(op.status)}</td>
                        <td className="py-3 px-4 text-slate-300 font-mono text-xs">{op.shopifyId}</td>
                        <td className="py-3 px-4 text-slate-300 font-mono text-xs">{op.qbId || '-'}</td>
                        <td className="py-3 px-4 text-right">
                          <span className={op.amount >= 0 ? 'text-emerald-400' : 'text-red-400'}>
                            {op.amount >= 0 ? '+' : ''}${Math.abs(op.amount).toFixed(2)}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-right text-slate-400">{op.duration > 0 ? `${op.duration}s` : '-'}</td>
                        <td className="py-3 px-4 text-slate-400 text-xs">
                          {new Date(op.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Glass>
          </>
        )}

        {/* Operations Tab */}
        {activeTab === 'operations' && (
          <Glass className="p-5">
            <div className="flex items-center gap-2 mb-4">
              <RefreshCw size={18} className="text-violet-400" />
              <h2 className="text-lg font-semibold text-white">All Sync Operations</h2>
            </div>
            <div className="space-y-3">
              {filteredOperations.map((op: any) => (
                <div 
                  key={op.id}
                  className="p-4 bg-white/[0.03] rounded-lg border border-white/[0.06] hover:bg-white/[0.05] cursor-pointer transition-colors"
                  onClick={() => setSelectedSync(op)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`w-2 h-2 rounded-full ${STATUS_COLORS[op.status as keyof typeof STATUS_COLORS] || '#64748b'}`} />
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-white">{op.type}</span>
                          {getStatusBadge(op.status)}
                        </div>
                        <div className="text-xs text-slate-400 mt-1">
                          {op.shopifyId} → {op.qbId || 'Pending'}
                        </div>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-emerald-400 font-medium">
                        {op.amount >= 0 ? '+' : ''}${Math.abs(op.amount).toFixed(2)}
                      </div>
                      <div className="text-xs text-slate-500">
                        {new Date(op.timestamp).toLocaleString()}
                      </div>
                    </div>
                  </div>
                  {op.error && (
                    <div className="mt-3 p-2 bg-red-500/10 border border-red-500/20 rounded text-xs text-red-400">
                      <AlertCircle size={12} className="inline mr-1" />
                      {op.error}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </Glass>
        )}

        {/* Analytics Tab */}
        {activeTab === 'analytics' && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <Glass className="p-5">
              <div className="flex items-center gap-2 mb-4">
                <BarChart3 size={18} className="text-cyan-400" />
                <h2 className="text-lg font-semibold text-white">Sync Volume by Type</h2>
              </div>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={[
                  { name: 'Orders', count: syncOperations.filter((o: any) => o.type.includes('Order')).length },
                  { name: 'Products', count: syncOperations.filter((o: any) => o.type.includes('Product')).length },
                  { name: 'Inventory', count: syncOperations.filter((o: any) => o.type.includes('Inventory')).length },
                  { name: 'Refunds', count: syncOperations.filter((o: any) => o.type.includes('Refund')).length },
                ]}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                  <XAxis dataKey="name" stroke="#64748b" fontSize={12} />
                  <YAxis stroke="#64748b" fontSize={12} />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                  />
                  <Bar dataKey="count" fill="#06b6d4" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </Glass>
            
            <Glass className="p-5">
              <div className="flex items-center gap-2 mb-4">
                <Activity size={18} className="text-emerald-400" />
                <h2 className="text-lg font-semibold text-white">Performance Metrics</h2>
              </div>
              <div className="space-y-4">
                <div>
                  <div className="flex justify-between text-sm mb-2">
                    <span className="text-slate-400">Average Sync Duration</span>
                    <span className="text-white font-medium">{kpis.avgDuration}s</span>
                  </div>
                  <div className="h-2 bg-white/[0.05] rounded-full overflow-hidden">
                    <div className="h-full bg-violet-500 rounded-full" style={{ width: `${Math.min(100, (parseFloat(kpis.avgDuration) / 5) * 100)}%` }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-2">
                    <span className="text-slate-400">Success Rate</span>
                    <span className="text-white font-medium">{kpis.successRate}%</span>
                  </div>
                  <div className="h-2 bg-white/[0.05] rounded-full overflow-hidden">
                    <div className="h-full bg-emerald-500 rounded-full" style={{ width: `${kpis.successRate}%` }} />
                  </div>
                </div>
                <div>
                  <div className="flex justify-between text-sm mb-2">
                    <span className="text-slate-400">Failed Syncs</span>
                    <span className="text-white font-medium">{kpis.failed}</span>
                  </div>
                  <div className="h-2 bg-white/[0.05] rounded-full overflow-hidden">
                    <div className="h-full bg-red-500 rounded-full" style={{ width: `${(kpis.failed / Math.max(1, kpis.total)) * 100}%` }} />
                  </div>
                </div>
              </div>
            </Glass>
          </div>
        )}

        {/* Settings Tab */}
        {activeTab === 'settings' && (
          <Glass className="p-5">
            <div className="flex items-center gap-2 mb-4">
              <Settings size={18} className="text-violet-400" />
              <h2 className="text-lg font-semibold text-white">Integration Settings</h2>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-white/[0.03] rounded-lg border border-white/[0.06]">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-[#95bf47]/20 rounded-lg">
                      <Icon name="shopping-bag" size={20} className="text-[#95bf47]" />
                    </div>
                    <div>
                      <div className="font-medium text-white">Shopify</div>
                      <div className="text-xs text-slate-400">E-commerce platform</div>
                    </div>
                  </div>
                  <button onClick={() => handleConnectProvider('shopify')} className="px-4 py-2 bg-[#95bf47]/20 text-[#95bf47] rounded-lg text-sm hover:bg-[#95bf47]/30">
                    {data?.providers?.shopify?.connected ? 'Connected' : 'Connect'}
                  </button>
                </div>
              </div>
              
              <div className="p-4 bg-white/[0.03] rounded-lg border border-white/[0.06]">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-[#2ca01c]/20 rounded-lg">
                      <Icon name="file-text" size={20} className="text-[#2ca01c]" />
                    </div>
                    <div>
                      <div className="font-medium text-white">QuickBooks</div>
                      <div className="text-xs text-slate-400">Accounting software</div>
                    </div>
                  </div>
                  <button onClick={() => handleConnectProvider('quickbooks')} className="px-4 py-2 bg-[#2ca01c]/20 text-[#2ca01c] rounded-lg text-sm hover:bg-[#2ca01c]/30">
                    {data?.providers?.quickbooks?.connected ? 'Connected' : 'Connect'}
                  </button>
                </div>
              </div>
            </div>
          </Glass>
        )}
      </div>

      {/* Detail Modal */}
      {selectedSync && (
        <div 
          className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
          onClick={() => setSelectedSync(null)}
        >
          <Glass 
            className="p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto"
            onClick={e => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold text-white">Sync Operation Details</h2>
              <button onClick={() => setSelectedSync(null)} className="text-slate-400 hover:text-white">
                <Icon name="x" size={20} />
              </button>
            </div>
            
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Type</div>
                  <div className="text-white font-medium">{selectedSync.type}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Status</div>
                  <div>{getStatusBadge(selectedSync.status)}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Shopify ID</div>
                  <div className="text-white font-mono text-sm">{selectedSync.shopifyId}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">QuickBooks ID</div>
                  <div className="text-white font-mono text-sm">{selectedSync.qbId || 'Pending'}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Amount</div>
                  <div className={`font-medium ${selectedSync.amount >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                    {selectedSync.amount >= 0 ? '+' : ''}${Math.abs(selectedSync.amount).toFixed(2)}
                  </div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Duration</div>
                  <div className="text-white">{selectedSync.duration > 0 ? `${selectedSync.duration}s` : 'Pending'}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Items Synced</div>
                  <div className="text-white">{selectedSync.items}</div>
                </div>
                <div className="p-3 bg-white/[0.03] rounded-lg">
                  <div className="text-xs text-slate-400 mb-1">Timestamp</div>
                  <div className="text-white text-sm">{new Date(selectedSync.timestamp).toLocaleString()}</div>
                </div>
              </div>
              
              {selectedSync.error && (
                <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
                  <div className="flex items-center gap-2 text-red-400 mb-2">
                    <AlertCircle size={16} />
                    <span className="font-medium">Error Details</span>
                  </div>
                  <div className="text-sm text-red-300">{selectedSync.error}</div>
                </div>
              )}
              
              <div className="p-4 bg-white/[0.03] rounded-lg">
                <div className="text-xs text-slate-400 mb-2">Raw Data</div>
                <pre className="text-xs text-slate-300 whitespace-pre-wrap overflow-auto max-h-40">
                  {JSON.stringify(selectedSync, null, 2)}
                </pre>
              </div>
            </div>
            
            <div className="flex gap-3 mt-6">
              <button 
                onClick={() => setSelectedSync(null)}
                className="flex-1 px-4 py-2 bg-violet-500/20 text-violet-400 rounded-lg text-sm hover:bg-violet-500/30 transition-colors"
              >
                Close
              </button>
              <button 
                onClick={() => {
                  dispatch('toast', { message: 'Retry initiated', type: 'info' });
                  refetch();
                }}
                className="flex-1 px-4 py-2 bg-emerald-500/20 text-emerald-400 rounded-lg text-sm hover:bg-emerald-500/30 transition-colors"
              >
                Retry Sync
              </button>
            </div>
          </Glass>
        </div>
      )}
    </div>
  );
}

// Missing icon imports
import { Settings, Activity, BarChart3 } from 'lucide-react';
