import React, { useState, useMemo } from 'react';
import { Calendar, TrendingUp, Euro, ShoppingCart, Download, Filter, Eye, Users, Package, CreditCard, BarChart3, AlertTriangle, Clock } from 'lucide-react';
import { Button, Card, Badge, StatusCard, getStatusColor } from '../../../../components/ui';
import { AnalyticsPageLayout, AnalyticsCard } from '../../../../components/analytics';
import { LoadingSpinner } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { useSalesAnalytics, useSalesRecords, useProductCategories } from '../../../../api/hooks/sales';
import { useTenantId } from '../../../../hooks/useTenantId';
import { SalesDataResponse } from '../../../../api/types/sales';

const SalesAnalyticsPage: React.FC = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('year');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [viewMode, setViewMode] = useState<'overview' | 'detailed' | 'patterns'>('overview');
  const [exportLoading, setExportLoading] = useState(false);

  const tenantId = useTenantId();

  // Calculate date range based on selected period
  const { startDate, endDate } = useMemo(() => {
    const end = new Date();
    const start = new Date();

    switch (selectedPeriod) {
      case 'day':
        start.setHours(0, 0, 0, 0);
        end.setHours(23, 59, 59, 999);
        break;
      case 'week':
        start.setDate(start.getDate() - 7);
        break;
      case 'month':
        start.setDate(start.getDate() - 30);
        break;
      case 'quarter':
        start.setDate(start.getDate() - 90);
        break;
      case 'year':
        start.setFullYear(start.getFullYear() - 1);
        break;
    }

    return {
      startDate: start.toISOString(),
      endDate: end.toISOString()
    };
  }, [selectedPeriod]);

  // Fetch real sales analytics data
  const {
    data: analyticsData,
    isLoading: analyticsLoading,
    error: analyticsError
  } = useSalesAnalytics(tenantId, startDate, endDate, {
    enabled: !!tenantId,
    retry: 1,
    retryDelay: 1000
  });

  // Fetch sales records for detailed view
  const {
    data: salesRecords,
    isLoading: recordsLoading,
    error: recordsError
  } = useSalesRecords(tenantId, {
    start_date: startDate,
    end_date: endDate,
    ...(selectedCategory !== 'all' && { product_category: selectedCategory }),
    limit: 100,
    order_by: 'date',
    order_direction: 'desc'
  }, {
    enabled: !!tenantId,
    retry: 1,
    retryDelay: 1000
  });

  // Fetch product categories
  const {
    data: categoriesData,
    isLoading: categoriesLoading
  } = useProductCategories(tenantId, {
    enabled: !!tenantId,
    retry: 1,
    retryDelay: 1000
  });

  const periods = [
    { value: 'day', label: 'Hoy' },
    { value: 'week', label: 'Esta Semana' },
    { value: 'month', label: 'Este Mes' },
    { value: 'quarter', label: 'Este Trimestre' },
    { value: 'year', label: 'Este Año' },
  ];

  // Process analytics data
  const salesMetrics = useMemo(() => {
    if (!analyticsData) {
      return {
        totalRevenue: 0,
        totalOrders: 0,
        averageOrderValue: 0,
        totalQuantity: 0,
        averageUnitPrice: 0,
        topProducts: [],
        revenueByCategory: [],
        revenueByChannel: []
      };
    }

    return {
      totalRevenue: analyticsData.total_revenue,
      totalOrders: analyticsData.total_transactions,
      averageOrderValue: analyticsData.total_transactions > 0 ? analyticsData.total_revenue / analyticsData.total_transactions : 0,
      totalQuantity: analyticsData.total_quantity,
      averageUnitPrice: analyticsData.average_unit_price,
      topProducts: analyticsData.top_products || [],
      revenueByCategory: analyticsData.revenue_by_category || [],
      revenueByChannel: analyticsData.revenue_by_channel || []
    };
  }, [analyticsData]);

  // Transform sales records for table
  const transformedSalesData = useMemo(() => {
    if (!salesRecords) return [];

    return salesRecords.map(record => ({
      id: record.id,
      date: record.date,
      productName: record.product_name,
      category: record.product_category || 'Sin categoría',
      quantity: record.quantity_sold,
      unitPrice: record.unit_price,
      totalRevenue: record.total_revenue,
      channel: record.sales_channel || 'N/A',
      discount: record.discount_applied || 0,
      profit: record.profit_margin || 0,
      validated: record.is_validated || false
    }));
  }, [salesRecords]);

  // Process traffic patterns from sales data
  const trafficPatterns = useMemo(() => {
    if (!salesRecords || salesRecords.length === 0) {
      return {
        hourlyTraffic: [],
        weeklyTraffic: []
      };
    }

    // Hourly traffic: count transactions per hour
    const hourlyMap = new Map<number, number>();
    const weeklyMap = new Map<number, number>();

    salesRecords.forEach(record => {
      const date = new Date(record.date);
      const hour = date.getHours();
      const dayOfWeek = date.getDay(); // 0 = Sunday, 6 = Saturday

      // Count transactions per hour
      hourlyMap.set(hour, (hourlyMap.get(hour) || 0) + 1);

      // Count transactions per day of week
      weeklyMap.set(dayOfWeek, (weeklyMap.get(dayOfWeek) || 0) + 1);
    });

    // Format hourly traffic data (0-23 hours)
    const hourlyTraffic = Array.from({ length: 24 }, (_, hour) => ({
      hour: `${hour.toString().padStart(2, '0')}:00`,
      transactions: hourlyMap.get(hour) || 0
    }));

    // Format weekly traffic data (Sun-Sat)
    const dayNames = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
    const weeklyTraffic = dayNames.map((day, index) => ({
      day,
      transactions: weeklyMap.get(index) || 0
    }));

    return {
      hourlyTraffic,
      weeklyTraffic
    };
  }, [salesRecords]);

  // Categories for filter
  const categories = useMemo(() => {
    const allCategories = [{ value: 'all', label: 'Todas las Categorías' }];
    if (categoriesData) {
      allCategories.push(...categoriesData.map(cat => ({ value: cat, label: cat })));
    }
    return allCategories;
  }, [categoriesData]);

  // Handle export functionality
  const handleExport = async (format: 'csv' | 'excel' | 'pdf') => {
    if (!salesRecords || salesRecords.length === 0) {
      alert('No hay datos para exportar');
      return;
    }

    setExportLoading(true);
    try {
      // Simple CSV export implementation
      if (format === 'csv') {
        const headers = ['Fecha', 'Producto', 'Categoría', 'Cantidad', 'Precio Unitario', 'Ingresos Totales', 'Canal', 'Descuento', 'Validado'];
        const csvContent = [
          headers.join(','),
          ...transformedSalesData.map(row => [
            row.date,
            `"${row.productName}"`,
            `"${row.category}"`,
            row.quantity,
            row.unitPrice,
            row.totalRevenue,
            `"${row.channel}"`,
            row.discount,
            row.validated ? 'Sí' : 'No'
          ].join(','))
        ].join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `analisis-ventas-${startDate}-${endDate}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    } catch (error) {
      console.error('Error exporting data:', error);
      alert('Error al exportar los datos');
    } finally {
      setExportLoading(false);
    }
  };

  // Table columns definition
  const salesColumns: TableColumn[] = [
    {
      key: 'date',
      title: 'Fecha',
      dataIndex: 'date',
      render: (value) => new Date(value).toLocaleDateString('es-ES')
    },
    {
      key: 'productName',
      title: 'Producto',
      dataIndex: 'productName'
    },
    {
      key: 'category',
      title: 'Categoría',
      dataIndex: 'category'
    },
    {
      key: 'quantity',
      title: 'Cantidad',
      dataIndex: 'quantity',
      render: (value) => value.toLocaleString()
    },
    {
      key: 'unitPrice',
      title: 'Precio Unit.',
      dataIndex: 'unitPrice',
      render: (value) => formatters.currency(value)
    },
    {
      key: 'totalRevenue',
      title: 'Ingresos',
      dataIndex: 'totalRevenue',
      render: (value) => (
        <span className="font-medium text-[var(--color-success)]">
          {formatters.currency(value)}
        </span>
      )
    },
    {
      key: 'channel',
      title: 'Canal',
      dataIndex: 'channel'
    },
    {
      key: 'validated',
      title: 'Estado',
      dataIndex: 'validated',
      render: (value) => (
        <Badge variant={value ? 'success' : 'warning'}>
          {value ? 'Validado' : 'Pendiente'}
        </Badge>
      )
    }
  ];

  // Check if it's a 422 error (API endpoint not available)
  const isApiUnavailable = (error: any) => {
    return error?.status === 422 || error?.response?.status === 422;
  };

  // Loading and error states
  const isLoading = analyticsLoading || recordsLoading || categoriesLoading || !tenantId;
  const hasError = analyticsError || recordsError;
  const isApiEndpointUnavailable = isApiUnavailable(analyticsError) && isApiUnavailable(recordsError);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <LoadingSpinner text="Cargando análisis de ventas..." />
      </div>
    );
  }

  // Special handling for when the sales API endpoints are not available
  if (isApiEndpointUnavailable) {
    return (
      <div className="space-y-6">
        <PageHeader
          title="Análisis de Ventas"
          description="Análisis detallado del rendimiento de ventas y tendencias de tu panadería"
        />

        <Card className="p-12 text-center">
          <ShoppingCart className="mx-auto h-16 w-16 text-[var(--color-info)] mb-6" />
          <h3 className="text-xl font-semibold text-[var(--text-primary)] mb-4">
            Funcionalidad en Desarrollo
          </h3>
          <p className="text-[var(--text-secondary)] mb-6 max-w-md mx-auto">
            El módulo de análisis de ventas está siendo desarrollado.
            Los endpoints de la API de ventas aún no están disponibles en el backend.
          </p>
          <div className="space-y-4">
            <div className="p-4 bg-[var(--bg-secondary)] rounded-lg max-w-md mx-auto">
              <h4 className="font-medium text-[var(--text-primary)] mb-2">Funcionalidades Planeadas:</h4>
              <ul className="text-sm text-[var(--text-secondary)] space-y-1 text-left">
                <li>• Análisis de ingresos y transacciones</li>
                <li>• Productos más vendidos</li>
                <li>• Análisis por categorías y canales</li>
                <li>• Exportación de datos de ventas</li>
                <li>• Filtrado por períodos y categorías</li>
              </ul>
            </div>
            <Badge variant="info">
              Estado: En desarrollo
            </Badge>
          </div>
        </Card>
      </div>
    );
  }

  if (hasError) {
    // Extract error message properly
    const getErrorMessage = (error: any) => {
      if (!error) return null;

      // Handle different error formats
      if (typeof error === 'string') return error;
      if (error.message && typeof error.message === 'string') return error.message;
      if (error.detail && typeof error.detail === 'string') return error.detail;
      if (error.msg && typeof error.msg === 'string') return error.msg;

      // If it's an array of validation errors
      if (Array.isArray(error)) {
        return error.map(e => e.msg || e.message || JSON.stringify(e)).join(', ');
      }

      return 'Error de conexión con el servidor';
    };

    const errorMessage = getErrorMessage(analyticsError) || getErrorMessage(recordsError) || 'Ha ocurrido un error inesperado';

    return (
      <div className="text-center py-12">
        <AlertTriangle className="mx-auto h-12 w-12 text-[var(--color-error)] mb-4" />
        <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
          Error al cargar datos de ventas
        </h3>
        <p className="text-[var(--text-secondary)] mb-4">
          {errorMessage}
        </p>
        <div className="space-y-2">
          <Button onClick={() => window.location.reload()}>
            Reintentar
          </Button>
          <p className="text-xs text-[var(--text-tertiary)]">
            Si el problema persiste, es posible que el endpoint de ventas no esté disponible
          </p>
        </div>
      </div>
    );
  }

  return (
    <AnalyticsPageLayout
      title="Análisis de Ventas"
      description="Análisis detallado del rendimiento de ventas y tendencias de tu panadería"
      subscriptionLoading={false}
      hasAccess={true}
      dataLoading={isLoading}
      actions={[
        {
          id: "export-data",
          label: "Exportar",
          variant: "outline" as const,
          icon: Download,
          onClick: () => handleExport('csv'),
          disabled: exportLoading || !salesRecords?.length
        }
      ]}
      filters={
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1 grid grid-cols-1 sm:grid-cols-3 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="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-primary)] text-[var(--text-primary)]"
              >
                {periods.map(period => (
                  <option key={period.value} value={period.value}>{period.label}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Categoría</label>
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-primary)] text-[var(--text-primary)]"
              >
                {categories.map(category => (
                  <option key={category.value} value={category.value}>{category.label}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Vista</label>
              <div className="flex rounded-md border border-[var(--border-secondary)] overflow-hidden">
                <Button
                  variant={viewMode === 'overview' ? 'primary' : 'outline'}
                  onClick={() => setViewMode('overview')}
                  size="sm"
                  className="rounded-none flex-1"
                >
                  <BarChart3 className="w-4 h-4 mr-1" />
                  General
                </Button>
                <Button
                  variant={viewMode === 'patterns' ? 'primary' : 'outline'}
                  onClick={() => setViewMode('patterns')}
                  size="sm"
                  className="rounded-none flex-1 border-l-0"
                >
                  <Users className="w-4 h-4 mr-1" />
                  Patrones
                </Button>
                <Button
                  variant={viewMode === 'detailed' ? 'primary' : 'outline'}
                  onClick={() => setViewMode('detailed')}
                  size="sm"
                  className="rounded-none flex-1 border-l-0"
                >
                  <Eye className="w-4 h-4 mr-1" />
                  Detallado
                </Button>
              </div>
            </div>
          </div>
        </div>
      }
      stats={[
        {
          title: 'Ingresos Totales',
          value: formatters.currency(salesMetrics.totalRevenue),
          variant: 'success' as const,
          icon: Euro,
        },
        {
          title: 'Total Transacciones',
          value: salesMetrics.totalOrders.toLocaleString(),
          variant: 'info' as const,
          icon: ShoppingCart,
        },
        {
          title: 'Ticket Promedio',
          value: formatters.currency(salesMetrics.averageOrderValue),
          variant: 'warning' as const,
          icon: CreditCard,
        },
        {
          title: 'Cantidad Total',
          value: salesMetrics.totalQuantity.toLocaleString(),
            variant: 'default' as const,
            icon: Package,
          },
          {
            title: 'Precio Unitario Promedio',
            value: formatters.currency(salesMetrics.averageUnitPrice),
            variant: 'info' as const,
            icon: TrendingUp,
          },
          {
            title: 'Productos Top',
            value: salesMetrics.topProducts.length,
            variant: 'success' as const,
            icon: Users,
          },
        ]}
        statsColumns={6}
        showMobileNotice={true}
      >
      {viewMode === 'patterns' ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Hourly Traffic Pattern */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <Clock className="w-5 h-5 mr-2" />
              Tráfico por Hora
            </h3>
            {trafficPatterns.hourlyTraffic.length === 0 || trafficPatterns.hourlyTraffic.every(h => h.transactions === 0) ? (
              <div className="text-center py-12">
                <Clock className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
                <p className="text-[var(--text-secondary)]">No hay datos de tráfico horario para este período</p>
              </div>
            ) : (
              <div className="h-64 flex items-end space-x-1 justify-between">
                {trafficPatterns.hourlyTraffic.map((data, index) => {
                  const maxTransactions = Math.max(...trafficPatterns.hourlyTraffic.map(h => h.transactions));
                  const height = maxTransactions > 0 ? (data.transactions / maxTransactions) * 200 : 4;

                  return (
                    <div key={index} className="flex flex-col items-center flex-1 group relative">
                      {data.transactions > 0 && (
                        <div className="text-xs text-[var(--text-secondary)] mb-1">{data.transactions}</div>
                      )}
                      <div
                        className="w-full bg-[var(--color-info)]/70 hover:bg-[var(--color-info)] rounded-t transition-colors cursor-pointer"
                        style={{
                          height: `${height}px`,
                          minHeight: '4px'
                        }}
                        title={`${data.hour}: ${data.transactions} transacciones`}
                      ></div>
                      <span className="text-xs text-[var(--text-tertiary)] mt-2 transform -rotate-45 origin-center whitespace-nowrap">
                        {data.hour}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
            <div className="mt-4 pt-4 border-t border-[var(--border-secondary)]">
              <p className="text-sm text-[var(--text-secondary)]">
                Patrones de transacciones por hora del día basados en datos de ventas
              </p>
            </div>
          </Card>

          {/* Weekly Traffic Pattern */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <Calendar className="w-5 h-5 mr-2" />
              Tráfico Semanal
            </h3>
            {trafficPatterns.weeklyTraffic.length === 0 || trafficPatterns.weeklyTraffic.every(d => d.transactions === 0) ? (
              <div className="text-center py-12">
                <Calendar className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
                <p className="text-[var(--text-secondary)]">No hay datos de tráfico semanal para este período</p>
              </div>
            ) : (
              <div className="h-64 flex items-end space-x-2 justify-between">
                {trafficPatterns.weeklyTraffic.map((data, index) => {
                  const maxTransactions = Math.max(...trafficPatterns.weeklyTraffic.map(d => d.transactions));
                  const height = maxTransactions > 0 ? (data.transactions / maxTransactions) * 200 : 8;

                  return (
                    <div key={index} className="flex flex-col items-center flex-1">
                      <div className="text-xs text-[var(--text-secondary)] mb-1">{data.transactions}</div>
                      <div
                        className="w-full bg-[var(--color-success)] hover:bg-[var(--color-success)]/80 rounded-t transition-colors cursor-pointer"
                        style={{
                          height: `${height}px`,
                          minHeight: '8px'
                        }}
                        title={`${data.day}: ${data.transactions} transacciones`}
                      ></div>
                      <span className="text-sm text-[var(--text-secondary)] mt-2 font-medium">
                        {data.day}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
            <div className="mt-4 pt-4 border-t border-[var(--border-secondary)]">
              <p className="text-sm text-[var(--text-secondary)]">
                Distribución de transacciones por día de la semana
              </p>
            </div>
          </Card>

          {/* Peak Hours Summary */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <TrendingUp className="w-5 h-5 mr-2" />
              Resumen de Horarios Pico
            </h3>
            {trafficPatterns.hourlyTraffic.length > 0 && trafficPatterns.hourlyTraffic.some(h => h.transactions > 0) ? (
              <div className="space-y-4">
                {(() => {
                  const sorted = [...trafficPatterns.hourlyTraffic]
                    .filter(h => h.transactions > 0)
                    .sort((a, b) => b.transactions - a.transactions)
                    .slice(0, 5);

                  return sorted.map((data, index) => (
                    <div key={data.hour} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                      <div className="flex items-center space-x-3">
                        <span className="text-sm font-medium text-[var(--text-tertiary)] w-6">{index + 1}.</span>
                        <div>
                          <p className="text-sm font-medium text-[var(--text-primary)]">{data.hour}</p>
                          <p className="text-xs text-[var(--text-tertiary)]">Horario pico</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium text-[var(--color-info)]">
                          {data.transactions} transacciones
                        </p>
                      </div>
                    </div>
                  ));
                })()}
              </div>
            ) : (
              <div className="text-center py-8">
                <TrendingUp className="mx-auto h-8 w-8 text-[var(--text-tertiary)] mb-2" />
                <p className="text-[var(--text-secondary)]">No hay datos suficientes para mostrar horarios pico</p>
              </div>
            )}
          </Card>

          {/* Busiest Days Summary */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <Calendar className="w-5 h-5 mr-2" />
              Días Más Activos
            </h3>
            {trafficPatterns.weeklyTraffic.length > 0 && trafficPatterns.weeklyTraffic.some(d => d.transactions > 0) ? (
              <div className="space-y-4">
                {(() => {
                  const sorted = [...trafficPatterns.weeklyTraffic]
                    .filter(d => d.transactions > 0)
                    .sort((a, b) => b.transactions - a.transactions)
                    .slice(0, 5);

                  return sorted.map((data, index) => (
                    <div key={data.day} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                      <div className="flex items-center space-x-3">
                        <div className={`w-3 h-3 rounded-full ${
                          index === 0 ? 'bg-[var(--color-success)]' :
                          index === 1 ? 'bg-[var(--color-info)]' :
                          index === 2 ? 'bg-[var(--color-warning)]' :
                          'bg-[var(--color-primary)]'
                        }`}></div>
                        <div>
                          <p className="text-sm font-medium text-[var(--text-primary)]">{data.day}</p>
                          <p className="text-xs text-[var(--text-tertiary)]">Día activo</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium text-[var(--color-success)]">
                          {data.transactions} transacciones
                        </p>
                      </div>
                    </div>
                  ));
                })()}
              </div>
            ) : (
              <div className="text-center py-8">
                <Calendar className="mx-auto h-8 w-8 text-[var(--text-tertiary)] mb-2" />
                <p className="text-[var(--text-secondary)]">No hay datos suficientes para mostrar días más activos</p>
              </div>
            )}
          </Card>
        </div>
      ) : viewMode === 'overview' ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Top Products */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <TrendingUp className="w-5 h-5 mr-2" />
              Productos Más Vendidos
            </h3>
            <div className="space-y-3">
              {salesMetrics.topProducts.length === 0 ? (
                <div className="text-center py-8">
                  <Package className="mx-auto h-8 w-8 text-[var(--text-tertiary)] mb-2" />
                  <p className="text-[var(--text-secondary)]">No hay datos de productos para este período</p>
                </div>
              ) : (
                salesMetrics.topProducts.slice(0, 5).map((product, index) => (
                  <div key={product.product_name} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <div className="flex items-center space-x-3">
                      <span className="text-sm font-medium text-[var(--text-tertiary)] w-6">{index + 1}.</span>
                      <div>
                        <p className="text-sm font-medium text-[var(--text-primary)]">{product.product_name}</p>
                        <p className="text-xs text-[var(--text-tertiary)]">{product.total_quantity} vendidos • {product.transaction_count} transacciones</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-medium text-[var(--color-success)]">
                        {formatters.currency(product.total_revenue)}
                      </p>
                    </div>
                  </div>
                ))
              )}
            </div>
          </Card>

          {/* Revenue by Category */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <BarChart3 className="w-5 h-5 mr-2" />
              Ingresos por Categoría
            </h3>
            <div className="space-y-3">
              {salesMetrics.revenueByCategory.length === 0 ? (
                <div className="text-center py-8">
                  <BarChart3 className="mx-auto h-8 w-8 text-[var(--text-tertiary)] mb-2" />
                  <p className="text-[var(--text-secondary)]">No hay datos de categorías para este período</p>
                </div>
              ) : (
                salesMetrics.revenueByCategory.map((category, index) => {
                  const maxRevenue = Math.max(...salesMetrics.revenueByCategory.map(c => c.revenue));
                  const percentage = maxRevenue > 0 ? (category.revenue / maxRevenue) * 100 : 0;

                  return (
                    <div key={category.category} className="space-y-2">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium text-[var(--text-primary)]">{category.category}</span>
                        <span className="text-sm font-medium text-[var(--color-success)]">
                          {formatters.currency(category.revenue)}
                        </span>
                      </div>
                      <div className="w-full bg-[var(--bg-quaternary)] rounded-full h-2">
                        <div
                          className="bg-[var(--color-info)] h-2 rounded-full transition-all duration-300"
                          style={{ width: `${percentage}%` }}
                        ></div>
                      </div>
                      <div className="flex justify-between text-xs text-[var(--text-tertiary)]">
                        <span>{category.quantity} unidades</span>
                        <span>{percentage.toFixed(1)}% del total</span>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </Card>

          {/* Revenue by Channel */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <ShoppingCart className="w-5 h-5 mr-2" />
              Ingresos por Canal
            </h3>
            <div className="space-y-3">
              {salesMetrics.revenueByChannel.length === 0 ? (
                <div className="text-center py-8">
                  <ShoppingCart className="mx-auto h-8 w-8 text-[var(--text-tertiary)] mb-2" />
                  <p className="text-[var(--text-secondary)]">No hay datos de canales para este período</p>
                </div>
              ) : (
                salesMetrics.revenueByChannel.map((channel, index) => (
                  <div key={channel.channel} className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
                    <div className="flex items-center space-x-3">
                      <div className={`w-3 h-3 rounded-full ${
                        index === 0 ? 'bg-[var(--color-success)]' :
                        index === 1 ? 'bg-[var(--color-info)]' :
                        index === 2 ? 'bg-[var(--color-warning)]' :
                        'bg-[var(--color-primary)]'
                      }`}></div>
                      <div>
                        <p className="text-sm font-medium text-[var(--text-primary)]">{channel.channel}</p>
                        <p className="text-xs text-[var(--text-tertiary)]">{channel.quantity} unidades</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-medium text-[var(--color-success)]">
                        {formatters.currency(channel.revenue)}
                      </p>
                    </div>
                  </div>
                ))
              )}
            </div>
          </Card>

          {/* Period Summary */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center">
              <Calendar className="w-5 h-5 mr-2" />
              Resumen del Período
            </h3>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
                  <p className="text-xs text-[var(--text-tertiary)] mb-1">Período Seleccionado</p>
                  <p className="text-sm font-medium text-[var(--text-primary)]">
                    {periods.find(p => p.value === selectedPeriod)?.label}
                  </p>
                </div>
                <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
                  <p className="text-xs text-[var(--text-tertiary)] mb-1">Registros Encontrados</p>
                  <p className="text-sm font-medium text-[var(--text-primary)]">
                    {salesRecords?.length || 0}
                  </p>
                </div>
              </div>

              <div className="border-t pt-4">
                <div className="flex justify-between items-center text-sm">
                  <span className="text-[var(--text-secondary)]">Fecha inicio:</span>
                  <span className="font-medium text-[var(--text-primary)]">
                    {new Date(startDate).toLocaleDateString('es-ES')}
                  </span>
                </div>
                <div className="flex justify-between items-center text-sm mt-1">
                  <span className="text-[var(--text-secondary)]">Fecha fin:</span>
                  <span className="font-medium text-[var(--text-primary)]">
                    {new Date(endDate).toLocaleDateString('es-ES')}
                  </span>
                </div>
              </div>
            </div>
          </Card>
        </div>
      ) : (
        <Card className="p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] flex items-center">
              <Eye className="w-5 h-5 mr-2" />
              Registro Detallado de Ventas
            </h3>
            <div className="flex items-center space-x-2">
              <Badge variant="info">
                {transformedSalesData.length} registros
              </Badge>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleExport('csv')}
                disabled={exportLoading || transformedSalesData.length === 0}
              >
                {exportLoading ? (
                  <Clock className="w-4 h-4 mr-2 animate-spin" />
                ) : (
                  <Download className="w-4 h-4 mr-2" />
                )}
                Exportar CSV
              </Button>
            </div>
          </div>

          {transformedSalesData.length === 0 ? (
            <div className="text-center py-12">
              <ShoppingCart className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
              <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
                No hay registros de ventas
              </h3>
              <p className="text-[var(--text-secondary)] mb-4">
                No se encontraron registros de ventas para el período y filtros seleccionados
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {/* Sales Records as Cards */}
              {transformedSalesData.slice(0, 50).map((record, index) => (
                <Card key={record.id} className="p-4 hover:shadow-md transition-shadow">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    {/* Left Side - Product Info */}
                    <div className="flex-1">
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <h4 className="font-medium text-[var(--text-primary)] text-sm sm:text-base">
                            {record.productName}
                          </h4>
                          <p className="text-xs text-[var(--text-tertiary)]">
                            {record.category} • {new Date(record.date).toLocaleDateString('es-ES')}
                          </p>
                        </div>
                        <Badge variant={record.validated ? 'success' : 'warning'} className="text-xs">
                          {record.validated ? 'Validado' : 'Pendiente'}
                        </Badge>
                      </div>

                      {/* Details Grid */}
                      <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
                        <div>
                          <span className="text-[var(--text-tertiary)]">Cantidad:</span>
                          <p className="font-medium text-[var(--text-primary)]">{record.quantity.toLocaleString()}</p>
                        </div>
                        <div>
                          <span className="text-[var(--text-tertiary)]">Precio Unit.:</span>
                          <p className="font-medium text-[var(--text-primary)]">{formatters.currency(record.unitPrice)}</p>
                        </div>
                        <div>
                          <span className="text-[var(--text-tertiary)]">Canal:</span>
                          <p className="font-medium text-[var(--text-primary)]">{record.channel}</p>
                        </div>
                        {record.discount > 0 && (
                          <div>
                            <span className="text-[var(--text-tertiary)]">Descuento:</span>
                            <p className="font-medium text-[var(--color-warning)]">{formatters.currency(record.discount)}</p>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Right Side - Revenue */}
                    <div className="flex items-center justify-between sm:flex-col sm:items-end sm:justify-center gap-2">
                      <div className="text-right">
                        <p className="text-xs text-[var(--text-tertiary)]">Ingresos</p>
                        <p className="text-lg font-bold text-[var(--color-success)]">
                          {formatters.currency(record.totalRevenue)}
                        </p>
                      </div>
                      <div className="flex items-center gap-1">
                        <Euro className="w-3 h-3 text-[var(--color-success)]" />
                        <span className="text-xs text-[var(--text-tertiary)]">#{index + 1}</span>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}

              {/* Load More / Pagination Info */}
              {transformedSalesData.length > 50 && (
                <Card className="p-4 text-center">
                  <p className="text-sm text-[var(--text-secondary)] mb-3">
                    Mostrando 50 de {transformedSalesData.length} registros
                  </p>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleExport('csv')}
                    className="mr-2"
                  >
                    <Download className="w-4 h-4 mr-2" />
                    Exportar todos los datos
                  </Button>
                </Card>
              )}
            </div>
          )}
        </Card>
      )}
    </AnalyticsPageLayout>
  );
};

export default SalesAnalyticsPage;