import React, { useState } from 'react';
import { Plus, Calendar, Clock, Users, AlertCircle } from 'lucide-react';
import { Button, Card, Badge, Table } from '../../../../components/ui';
import type { TableColumn } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';
import { ProductionSchedule, BatchTracker, QualityControl } from '../../../../components/domain/production';

const ProductionPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('schedule');

  const mockProductionStats = {
    dailyTarget: 150,
    completed: 85,
    inProgress: 12,
    pending: 53,
    efficiency: 78,
    quality: 94,
  };

  const mockProductionOrders = [
    {
      id: '1',
      recipeName: 'Pan de Molde Integral',
      quantity: 20,
      status: 'in_progress',
      priority: 'high',
      assignedTo: 'Juan Panadero',
      startTime: '2024-01-26T06:00:00Z',
      estimatedCompletion: '2024-01-26T10:00:00Z',
      progress: 65,
    },
    {
      id: '2',
      recipeName: 'Croissants de Mantequilla',
      quantity: 50,
      status: 'pending',
      priority: 'medium',
      assignedTo: 'María González',
      startTime: '2024-01-26T08:00:00Z',
      estimatedCompletion: '2024-01-26T12:00:00Z',
      progress: 0,
    },
    {
      id: '3',
      recipeName: 'Baguettes Francesas',
      quantity: 30,
      status: 'completed',
      priority: 'medium',
      assignedTo: 'Carlos Ruiz',
      startTime: '2024-01-26T04:00:00Z',
      estimatedCompletion: '2024-01-26T08:00:00Z',
      progress: 100,
    },
  ];

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      pending: { color: 'yellow', text: 'Pendiente' },
      in_progress: { color: 'blue', text: 'En Proceso' },
      completed: { color: 'green', text: 'Completado' },
      cancelled: { color: 'red', text: 'Cancelado' },
    };
    
    const config = statusConfig[status as keyof typeof statusConfig];
    return <Badge variant={config.color as any}>{config.text}</Badge>;
  };

  const getPriorityBadge = (priority: string) => {
    const priorityConfig = {
      low: { color: 'gray', text: 'Baja' },
      medium: { color: 'yellow', text: 'Media' },
      high: { color: 'orange', text: 'Alta' },
      urgent: { color: 'red', text: 'Urgente' },
    };
    
    const config = priorityConfig[priority as keyof typeof priorityConfig];
    return <Badge variant={config.color as any}>{config.text}</Badge>;
  };

  const columns: TableColumn[] = [
    {
      key: 'recipeName',
      title: 'Receta',
      dataIndex: 'recipeName',
      render: (value) => (
        <div className="text-sm font-medium text-[var(--text-primary)]">{value}</div>
      ),
    },
    {
      key: 'quantity',
      title: 'Cantidad',
      dataIndex: 'quantity',
      render: (value) => `${value} unidades`,
    },
    {
      key: 'status',
      title: 'Estado',
      dataIndex: 'status',
      render: (value) => getStatusBadge(value),
    },
    {
      key: 'priority',
      title: 'Prioridad',
      dataIndex: 'priority',
      render: (value) => getPriorityBadge(value),
    },
    {
      key: 'assignedTo',
      title: 'Asignado a',
      dataIndex: 'assignedTo',
      render: (value) => (
        <div className="flex items-center">
          <Users className="h-4 w-4 text-[var(--text-tertiary)] mr-2" />
          <span className="text-sm text-[var(--text-primary)]">{value}</span>
        </div>
      ),
    },
    {
      key: 'progress',
      title: 'Progreso',
      dataIndex: 'progress',
      render: (value) => (
        <div className="flex items-center">
          <div className="w-full bg-[var(--bg-quaternary)] rounded-full h-2 mr-2">
            <div
              className="bg-blue-600 h-2 rounded-full"
              style={{ width: `${value}%` }}
            ></div>
          </div>
          <span className="text-sm text-[var(--text-primary)]">{value}%</span>
        </div>
      ),
    },
    {
      key: 'estimatedCompletion',
      title: 'Tiempo Estimado',
      dataIndex: 'estimatedCompletion',
      render: (value) => new Date(value).toLocaleTimeString('es-ES', { 
        hour: '2-digit', 
        minute: '2-digit' 
      }),
    },
    {
      key: 'actions',
      title: 'Acciones',
      align: 'right' as const,
      render: () => (
        <div className="flex space-x-2">
          <Button variant="outline" size="sm">
            Ver
          </Button>
          <Button variant="outline" size="sm">
            Editar
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Gestión de Producción"
        description="Planifica y controla la producción diaria de tu panadería"
        action={
          <Button>
            <Plus className="w-4 h-4 mr-2" />
            Nueva Orden de Producción
          </Button>
        }
      />

      {/* Production Stats */}
      <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)]">Meta Diaria</p>
              <p className="text-2xl font-bold text-[var(--text-primary)]">{mockProductionStats.dailyTarget}</p>
            </div>
            <Calendar 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)]">Completado</p>
              <p className="text-2xl font-bold text-[var(--color-success)]">{mockProductionStats.completed}</p>
            </div>
            <div className="h-8 w-8 bg-[var(--color-success)]/10 rounded-full flex items-center justify-center">
              <svg className="h-5 w-5 text-[var(--color-success)]" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
              </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)]">En Proceso</p>
              <p className="text-2xl font-bold text-[var(--color-info)]">{mockProductionStats.inProgress}</p>
            </div>
            <Clock 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)]">Pendiente</p>
              <p className="text-2xl font-bold text-[var(--color-primary)]">{mockProductionStats.pending}</p>
            </div>
            <AlertCircle className="h-8 w-8 text-[var(--color-primary)]" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Eficiencia</p>
              <p className="text-2xl font-bold text-purple-600">{mockProductionStats.efficiency}%</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="M13 10V3L4 14h7v7l9-11h-7z" />
              </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)]">Calidad</p>
              <p className="text-2xl font-bold text-indigo-600">{mockProductionStats.quality}%</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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
          </div>
        </Card>
      </div>

      {/* Tabs Navigation */}
      <div className="border-b border-[var(--border-primary)]">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('schedule')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'schedule'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Programación
          </button>
          <button
            onClick={() => setActiveTab('batches')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'batches'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Lotes de Producción
          </button>
          <button
            onClick={() => setActiveTab('quality')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'quality'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Control de Calidad
          </button>
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'schedule' && (
        <Card>
          <div className="p-6">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-lg font-medium text-[var(--text-primary)]">Órdenes de Producción</h3>
              <div className="flex space-x-2">
                <Button variant="outline" size="sm">
                  Filtros
                </Button>
                <Button variant="outline" size="sm">
                  Vista Calendario
                </Button>
              </div>
            </div>
            
            <Table
              columns={columns}
              data={mockProductionOrders}
              rowKey="id"
              hover={true}
              variant="default"
              size="md"
            />
          </div>
        </Card>
      )}

      {activeTab === 'batches' && (
        <BatchTracker />
      )}

      {activeTab === 'quality' && (
        <QualityControl />
      )}
    </div>
  );
};

export default ProductionPage;