import React, { useState } from 'react';
import { Calendar, Activity, Filter, Download, Eye, BarChart3 } from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';

const EventsPage: React.FC = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('week');
  const [selectedCategory, setSelectedCategory] = useState('all');

  const events = [
    {
      id: '1',
      timestamp: '2024-01-26 10:30:00',
      category: 'sales',
      type: 'order_completed',
      title: 'Pedido Completado',
      description: 'Pedido #ORD-456 completado por €127.50',
      metadata: {
        orderId: 'ORD-456',
        amount: 127.50,
        customer: 'María González',
        items: 8
      },
      severity: 'info'
    },
    {
      id: '2',
      timestamp: '2024-01-26 09:15:00',
      category: 'production',
      type: 'batch_started',
      title: 'Lote Iniciado',
      description: 'Iniciado lote de croissants CR-024',
      metadata: {
        batchId: 'CR-024',
        product: 'Croissants',
        quantity: 48,
        expectedDuration: '2.5h'
      },
      severity: 'info'
    },
    {
      id: '3',
      timestamp: '2024-01-26 08:45:00',
      category: 'inventory',
      type: 'stock_updated',
      title: 'Stock Actualizado',
      description: 'Repuesto stock de harina - Nivel: 50kg',
      metadata: {
        item: 'Harina de Trigo',
        previousLevel: '5kg',
        newLevel: '50kg',
        supplier: 'Molinos del Sur'
      },
      severity: 'success'
    },
    {
      id: '4',
      timestamp: '2024-01-26 07:30:00',
      category: 'system',
      type: 'user_login',
      title: 'Inicio de Sesión',
      description: 'Usuario admin ha iniciado sesión',
      metadata: {
        userId: 'admin',
        ipAddress: '192.168.1.100',
        userAgent: 'Chrome/120.0',
        location: 'Madrid, ES'
      },
      severity: 'info'
    },
    {
      id: '5',
      timestamp: '2024-01-25 19:20:00',
      category: 'sales',
      type: 'payment_processed',
      title: 'Pago Procesado',
      description: 'Pago de €45.80 procesado exitosamente',
      metadata: {
        amount: 45.80,
        method: 'Tarjeta',
        reference: 'PAY-789',
        customer: 'Juan Pérez'
      },
      severity: 'success'
    }
  ];

  const eventStats = {
    total: events.length,
    today: events.filter(e => 
      new Date(e.timestamp).toDateString() === new Date().toDateString()
    ).length,
    sales: events.filter(e => e.category === 'sales').length,
    production: events.filter(e => e.category === 'production').length,
    system: events.filter(e => e.category === 'system').length
  };

  const categories = [
    { value: 'all', label: 'Todos', count: events.length },
    { value: 'sales', label: 'Ventas', count: eventStats.sales },
    { value: 'production', label: 'Producción', count: eventStats.production },
    { value: 'inventory', label: 'Inventario', count: events.filter(e => e.category === 'inventory').length },
    { value: 'system', label: 'Sistema', count: eventStats.system }
  ];

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'success': return 'green';
      case 'warning': return 'yellow';
      case 'error': return 'red';
      default: return 'blue';
    }
  };

  const getCategoryIcon = (category: string) => {
    const iconProps = { className: "w-4 h-4" };
    switch (category) {
      case 'sales': return <BarChart3 {...iconProps} />;
      case 'production': return <Activity {...iconProps} />;
      case 'inventory': return <Calendar {...iconProps} />;
      default: return <Activity {...iconProps} />;
    }
  };

  const filteredEvents = selectedCategory === 'all' 
    ? events 
    : events.filter(event => event.category === selectedCategory);

  const formatTimeAgo = (timestamp: string) => {
    const now = new Date();
    const eventTime = new Date(timestamp);
    const diffInMs = now.getTime() - eventTime.getTime();
    const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60));
    const diffInDays = Math.floor(diffInHours / 24);
    
    if (diffInDays > 0) {
      return `hace ${diffInDays}d`;
    } else if (diffInHours > 0) {
      return `hace ${diffInHours}h`;
    } else {
      return `hace ${Math.floor(diffInMs / (1000 * 60))}m`;
    }
  };

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Registro de Eventos"
        description="Seguimiento de todas las actividades y eventos del sistema"
        action={
          <div className="flex space-x-2">
            <Button variant="outline">
              <Filter className="w-4 h-4 mr-2" />
              Filtros Avanzados
            </Button>
            <Button variant="outline">
              <Download className="w-4 h-4 mr-2" />
              Exportar
            </Button>
          </div>
        }
      />

      {/* Event Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Total Eventos</p>
              <p className="text-3xl font-bold text-[var(--text-primary)]">{eventStats.total}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-info)]/10 rounded-full flex items-center justify-center">
              <Activity className="h-6 w-6 text-[var(--color-info)]" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Hoy</p>
              <p className="text-3xl font-bold text-[var(--color-success)]">{eventStats.today}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-success)]/10 rounded-full flex items-center justify-center">
              <Calendar className="h-6 w-6 text-[var(--color-success)]" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Ventas</p>
              <p className="text-3xl font-bold text-purple-600">{eventStats.sales}</p>
            </div>
            <div className="h-12 w-12 bg-purple-100 rounded-full flex items-center justify-center">
              <BarChart3 className="h-6 w-6 text-purple-600" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Producción</p>
              <p className="text-3xl font-bold text-[var(--color-primary)]">{eventStats.production}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-primary)]/10 rounded-full flex items-center justify-center">
              <Activity className="h-6 w-6 text-[var(--color-primary)]" />
            </div>
          </div>
        </Card>
      </div>

      {/* Filters */}
      <Card className="p-6">
        <div className="flex flex-col sm:flex-row gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Período</label>
            <select
              value={selectedPeriod}
              onChange={(e) => setSelectedPeriod(e.target.value)}
              className="px-3 py-2 border border-[var(--border-secondary)] rounded-md"
            >
              <option value="day">Hoy</option>
              <option value="week">Esta Semana</option>
              <option value="month">Este Mes</option>
              <option value="all">Todos</option>
            </select>
          </div>
          
          <div className="flex gap-2 flex-wrap">
            {categories.map((category) => (
              <button
                key={category.value}
                onClick={() => setSelectedCategory(category.value)}
                className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                  selectedCategory === category.value
                    ? 'bg-blue-600 text-white'
                    : 'bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:bg-[var(--bg-quaternary)]'
                }`}
              >
                {category.label} ({category.count})
              </button>
            ))}
          </div>
        </div>
      </Card>

      {/* Events List */}
      <div className="space-y-4">
        {filteredEvents.map((event) => (
          <Card key={event.id} className="p-6">
            <div className="flex items-start justify-between">
              <div className="flex items-start space-x-4 flex-1">
                <div className={`p-2 rounded-lg bg-${getSeverityColor(event.severity)}-100`}>
                  {getCategoryIcon(event.category)}
                </div>
                
                <div className="flex-1">
                  <div className="flex items-center space-x-3 mb-2">
                    <h3 className="text-lg font-semibold text-[var(--text-primary)]">{event.title}</h3>
                    <Badge variant={getSeverityColor(event.severity)}>
                      {event.category}
                    </Badge>
                  </div>
                  
                  <p className="text-[var(--text-secondary)] mb-3">{event.description}</p>
                  
                  {/* Event Metadata */}
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                    {Object.entries(event.metadata).map(([key, value]) => (
                      <div key={key} className="bg-[var(--bg-secondary)] p-3 rounded-lg">
                        <p className="text-xs text-[var(--text-tertiary)] uppercase tracking-wider mb-1">
                          {key.replace(/([A-Z])/g, ' $1').replace(/^./, (str: string) => str.toUpperCase())}
                        </p>
                        <p className="text-sm font-medium text-[var(--text-primary)]">{value}</p>
                      </div>
                    ))}
                  </div>
                  
                  <div className="flex items-center text-sm text-[var(--text-tertiary)]">
                    <span>{formatTimeAgo(event.timestamp)}</span>
                    <span className="mx-2">•</span>
                    <span>{new Date(event.timestamp).toLocaleString('es-ES')}</span>
                  </div>
                </div>
              </div>
              
              <Button size="sm" variant="outline">
                <Eye className="w-4 h-4 mr-2" />
                Ver Detalles
              </Button>
            </div>
          </Card>
        ))}
      </div>

      {filteredEvents.length === 0 && (
        <Card className="p-12 text-center">
          <Activity className="h-12 w-12 text-[var(--text-tertiary)] mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">No hay eventos</h3>
          <p className="text-[var(--text-secondary)]">
            No se encontraron eventos para el período y categoría seleccionados.
          </p>
        </Card>
      )}
    </div>
  );
};

export default EventsPage;