import React, { useState, useEffect } from 'react';
import { ClipboardList, Clock } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';

const Orders = () => {
  const [establishments, setEstablishments] = useState<any[]>([]);
  const [selectedEstablishment, setSelectedEstablishment] = useState('');
  const [orders, setOrders] = useState<any[]>([]);
  const { toast } = useToast();

  useEffect(() => {
    loadEstablishments();
  }, []);

  useEffect(() => {
    if (selectedEstablishment) {
      loadOrders();
    }
  }, [selectedEstablishment]);

  const loadEstablishments = async () => {
    try {
      const response = await apiClient.get('/commerce/establishments');
      setEstablishments(Array.isArray(response) ? response : (response as any)?.establishments || []);
    } catch (error) {
      console.error('Error loading establishments:', error);
    }
  };

  const loadOrders = async () => {
    try {
      const response = await apiClient.get(`/restaurant/establishments/${selectedEstablishment}/orders`);
      setOrders(Array.isArray(response) ? response : (response as any)?.orders || []);
    } catch (error) {
      console.error('Error loading orders:', error);
    }
  };

  const handleUpdateStatus = async (orderId: number, status: string) => {
    try {
      await apiClient.patch(`/restaurant/orders/${orderId}/status`, { status });
      toast({ title: 'Éxito', description: 'Estado actualizado' });
      loadOrders();
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo actualizar', variant: 'destructive' });
    }
  };

  const getStatusVariant = (status: string) => {
    const variants: Record<string, any> = {
      pending: 'secondary',
      preparing: 'default',
      ready: 'outline',
      delivered: 'default',
      paid: 'outline'
    };
    return variants[status] || 'default';
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center gap-3 mb-6">
          <ClipboardList className="w-8 h-8 text-orange-600" />
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Gestión de Pedidos</h1>
            <p className="text-gray-600">Administra todas las órdenes</p>
          </div>
        </div>

        <div className="mb-4">
          <Select value={selectedEstablishment} onValueChange={setSelectedEstablishment}>
            <SelectTrigger className="w-64">
              <SelectValue placeholder="Selecciona establecimiento" />
            </SelectTrigger>
            <SelectContent>
              {establishments.map((est) => (
                <SelectItem key={est.id} value={est.id.toString()}>
                  {est.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="grid gap-4">
          {orders.map((order) => (
            <Card key={order.id}>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <div className="flex items-center space-x-4">
                  <ClipboardList className="w-8 h-8 text-primary" />
                  <div>
                    <CardTitle>Orden #{order.id}</CardTitle>
                    <p className="text-sm text-muted-foreground">Mesa {order.tableNumber}</p>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Clock className="w-4 h-4" />
                    {new Date(order.createdAt).toLocaleTimeString()}
                  </div>
                  <span className="text-lg font-bold">${order.total?.toFixed(2)}</span>
                  <Select
                    value={order.status}
                    onValueChange={(value) => handleUpdateStatus(order.id, value)}
                  >
                    <SelectTrigger className="w-32">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="pending">Pendiente</SelectItem>
                      <SelectItem value="preparing">Preparando</SelectItem>
                      <SelectItem value="ready">Lista</SelectItem>
                      <SelectItem value="delivered">Entregada</SelectItem>
                      <SelectItem value="paid">Pagada</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-1">
                  {order.items?.map((item: any, idx: number) => (
                    <div key={idx} className="flex justify-between text-sm">
                      <span>{item.quantity}x {item.menuItem?.name || 'Item'}</span>
                      <span>${(item.quantity * item.price).toFixed(2)}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Orders;
