import React, { useState } from 'react';
import { Calendar, TrendingUp, DollarSign, ShoppingCart, Download, Filter } from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';
import { AnalyticsDashboard, ChartWidget, ReportsTable } from '../../../../components/domain/analytics';

const SalesAnalyticsPage: React.FC = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('month');
  const [selectedMetric, setSelectedMetric] = useState('revenue');
  const [viewMode, setViewMode] = useState<'overview' | 'detailed'>('overview');

  const salesMetrics = {
    totalRevenue: 45678.90,
    totalOrders: 1234,
    averageOrderValue: 37.02,
    customerCount: 856,
    growthRate: 12.5,
    conversionRate: 68.4,
  };

  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' },
  ];

  const metrics = [
    { value: 'revenue', label: 'Ingresos' },
    { value: 'orders', label: 'Pedidos' },
    { value: 'customers', label: 'Clientes' },
    { value: 'products', label: 'Productos' },
  ];

  const topProducts = [
    { 
      id: '1', 
      name: 'Pan de Molde Integral', 
      revenue: 2250.50, 
      units: 245, 
      growth: 8.2,
      category: 'Panes'
    },
    { 
      id: '2', 
      name: 'Croissants de Mantequilla', 
      revenue: 1890.75, 
      units: 412, 
      growth: 15.4,
      category: 'Bollería'
    },
    { 
      id: '3', 
      name: 'Tarta de Chocolate', 
      revenue: 1675.00, 
      units: 67, 
      growth: -2.1,
      category: 'Tartas'
    },
    { 
      id: '4', 
      name: 'Empanadas Variadas', 
      revenue: 1425.25, 
      units: 285, 
      growth: 22.8,
      category: 'Salados'
    },
    { 
      id: '5', 
      name: 'Magdalenas', 
      revenue: 1180.50, 
      units: 394, 
      growth: 5.7,
      category: 'Bollería'
    },
  ];

  const salesByHour = [
    { hour: '07:00', sales: 145, orders: 12 },
    { hour: '08:00', sales: 289, orders: 18 },
    { hour: '09:00', sales: 425, orders: 28 },
    { hour: '10:00', sales: 380, orders: 24 },
    { hour: '11:00', sales: 520, orders: 31 },
    { hour: '12:00', sales: 675, orders: 42 },
    { hour: '13:00', sales: 720, orders: 45 },
    { hour: '14:00', sales: 580, orders: 35 },
    { hour: '15:00', sales: 420, orders: 28 },
    { hour: '16:00', sales: 350, orders: 22 },
    { hour: '17:00', sales: 480, orders: 31 },
    { hour: '18:00', sales: 620, orders: 38 },
    { hour: '19:00', sales: 450, orders: 29 },
    { hour: '20:00', sales: 280, orders: 18 },
  ];

  const customerSegments = [
    { segment: 'Clientes Frecuentes', count: 123, revenue: 15678, percentage: 34.3 },
    { segment: 'Clientes Regulares', count: 245, revenue: 18950, percentage: 41.5 },
    { segment: 'Clientes Ocasionales', count: 356, revenue: 8760, percentage: 19.2 },
    { segment: 'Clientes Nuevos', count: 132, revenue: 2290, percentage: 5.0 },
  ];

  const paymentMethods = [
    { method: 'Tarjeta', count: 567, revenue: 28450, percentage: 62.3 },
    { method: 'Efectivo', count: 445, revenue: 13890, percentage: 30.4 },
    { method: 'Transferencia', count: 178, revenue: 2890, percentage: 6.3 },
    { method: 'Otros', count: 44, revenue: 448, percentage: 1.0 },
  ];

  const getGrowthBadge = (growth: number) => {
    if (growth > 0) {
      return <Badge variant="green">+{growth.toFixed(1)}%</Badge>;
    } else if (growth < 0) {
      return <Badge variant="red">{growth.toFixed(1)}%</Badge>;
    } else {
      return <Badge variant="gray">0%</Badge>;
    }
  };

  const getGrowthColor = (growth: number) => {
    return growth >= 0 ? 'text-[var(--color-success)]' : 'text-[var(--color-error)]';
  };

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Análisis de Ventas"
        description="Análisis detallado del rendimiento de ventas y tendencias de tu panadería"
        action={
          <div className="flex space-x-2">
            <Button variant="outline">
              <Filter className="w-4 h-4 mr-2" />
              Filtros
            </Button>
            <Button variant="outline">
              <Download className="w-4 h-4 mr-2" />
              Exportar
            </Button>
          </div>
        }
      />

      {/* Controls */}
      <Card className="p-6">
        <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"
              >
                {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">Métrica Principal</label>
              <select
                value={selectedMetric}
                onChange={(e) => setSelectedMetric(e.target.value)}
                className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md"
              >
                {metrics.map(metric => (
                  <option key={metric.value} value={metric.value}>{metric.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)]">
                <button
                  onClick={() => setViewMode('overview')}
                  className={`px-3 py-2 text-sm ${viewMode === 'overview' ? 'bg-blue-600 text-white' : 'bg-white text-[var(--text-secondary)]'} rounded-l-md`}
                >
                  General
                </button>
                <button
                  onClick={() => setViewMode('detailed')}
                  className={`px-3 py-2 text-sm ${viewMode === 'detailed' ? 'bg-blue-600 text-white' : 'bg-white text-[var(--text-secondary)]'} rounded-r-md border-l`}
                >
                  Detallado
                </button>
              </div>
            </div>
          </div>
        </div>
      </Card>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Ingresos Totales</p>
              <p className="text-2xl font-bold text-[var(--color-success)]">€{salesMetrics.totalRevenue.toLocaleString()}</p>
            </div>
            <DollarSign className="h-8 w-8 text-[var(--color-success)]" />
          </div>
          <div className="mt-2">
            {getGrowthBadge(salesMetrics.growthRate)}
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Total Pedidos</p>
              <p className="text-2xl font-bold text-[var(--color-info)]">{salesMetrics.totalOrders.toLocaleString()}</p>
            </div>
            <ShoppingCart className="h-8 w-8 text-[var(--color-info)]" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Valor Promedio</p>
              <p className="text-2xl font-bold text-purple-600">€{salesMetrics.averageOrderValue.toFixed(2)}</p>
            </div>
            <div className="h-8 w-8 bg-purple-100 rounded-full flex items-center justify-center">
              <svg className="h-5 w-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Clientes</p>
              <p className="text-2xl font-bold text-[var(--color-primary)]">{salesMetrics.customerCount}</p>
            </div>
            <div className="h-8 w-8 bg-[var(--color-primary)]/10 rounded-full flex items-center justify-center">
              <svg className="h-5 w-5 text-[var(--color-primary)]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-.5a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
              </svg>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Tasa Crecimiento</p>
              <p className={`text-2xl font-bold ${getGrowthColor(salesMetrics.growthRate)}`}>
                {salesMetrics.growthRate > 0 ? '+' : ''}{salesMetrics.growthRate.toFixed(1)}%
              </p>
            </div>
            <TrendingUp className={`h-8 w-8 ${getGrowthColor(salesMetrics.growthRate)}`} />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Conversión</p>
              <p className="text-2xl font-bold text-indigo-600">{salesMetrics.conversionRate}%</p>
            </div>
            <div className="h-8 w-8 bg-indigo-100 rounded-full flex items-center justify-center">
              <svg className="h-5 w-5 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
          </div>
        </Card>
      </div>

      {viewMode === 'overview' ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Sales by Hour Chart */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Ventas por Hora</h3>
            <div className="h-64 flex items-end space-x-1 justify-between">
              {salesByHour.map((data, index) => (
                <div key={index} className="flex flex-col items-center flex-1">
                  <div
                    className="w-full bg-[var(--color-info)]/50 rounded-t"
                    style={{
                      height: `${(data.sales / Math.max(...salesByHour.map(d => d.sales))) * 200}px`,
                      minHeight: '4px'
                    }}
                  ></div>
                  <span className="text-xs text-[var(--text-tertiary)] mt-2 transform -rotate-45 origin-center">
                    {data.hour}
                  </span>
                </div>
              ))}
            </div>
          </Card>

          {/* Top Products */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Productos Más Vendidos</h3>
            <div className="space-y-3">
              {topProducts.slice(0, 5).map((product, index) => (
                <div key={product.id} 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.name}</p>
                      <p className="text-xs text-[var(--text-tertiary)]">{product.category} • {product.units} unidades</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-[var(--text-primary)]">€{product.revenue.toLocaleString()}</p>
                    {getGrowthBadge(product.growth)}
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* Customer Segments */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Segmentos de Clientes</h3>
            <div className="space-y-4">
              {customerSegments.map((segment, index) => (
                <div key={index} className="space-y-2">
                  <div className="flex justify-between items-center">
                    <span className="text-sm font-medium text-[var(--text-primary)]">{segment.segment}</span>
                    <span className="text-sm text-[var(--text-secondary)]">{segment.percentage}%</span>
                  </div>
                  <div className="w-full bg-[var(--bg-quaternary)] rounded-full h-2">
                    <div
                      className="bg-blue-600 h-2 rounded-full"
                      style={{ width: `${segment.percentage}%` }}
                    ></div>
                  </div>
                  <div className="flex justify-between text-xs text-[var(--text-tertiary)]">
                    <span>{segment.count} clientes</span>
                    <span>€{segment.revenue.toLocaleString()}</span>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* Payment Methods */}
          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Métodos de Pago</h3>
            <div className="space-y-3">
              {paymentMethods.map((method, index) => (
                <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                  <div className="flex items-center space-x-3">
                    <div className="w-3 h-3 bg-[var(--color-info)]/50 rounded-full"></div>
                    <div>
                      <p className="text-sm font-medium text-[var(--text-primary)]">{method.method}</p>
                      <p className="text-xs text-[var(--text-tertiary)]">{method.count} transacciones</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-[var(--text-primary)]">€{method.revenue.toLocaleString()}</p>
                    <p className="text-xs text-[var(--text-tertiary)]">{method.percentage}%</p>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      ) : (
        <div className="space-y-6">
          {/* Detailed Analytics Dashboard */}
          <AnalyticsDashboard />
          
          {/* Detailed Reports Table */}
          <ReportsTable />
        </div>
      )}
    </div>
  );
};

export default SalesAnalyticsPage;