import React, { useState, useEffect } from 'react';
import { CreditCard, Plus, Minus, Trash2, DollarSign, Package, Barcode } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';
import { useLanguage } from '@/contexts/LanguageContext';
import { useCurrency } from '@/contexts/CurrencyContext';

const POSTerminal = () => {
  const { t } = useLanguage();
  const { formatAmount } = useCurrency();
  const [products, setProducts] = useState<any[]>([]);
  const [cart, setCart] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const { toast } = useToast();

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

  const loadProducts = async () => {
    try {
      // Load inventory products for POS
      // For now using mock data
      const mock = [
        { id: 1, name: 'T-Shirt', category: 'Apparel', price: 20, stock: 15, barcode: '123456' },
        { id: 2, name: 'Mug', category: 'Gifts', price: 8.5, stock: 40, barcode: '789012' },
      ].map(p => ({ ...p, formattedPrice: formatAmount(p.price) }));
      setProducts(mock);
    } catch (error) {
      console.error('Error loading products:', error);
    }
  };

  const addToCart = (item: any) => {
    const existingItem = cart.find(i => i.id === item.id);
    if (existingItem) {
      setCart(cart.map(i => 
        i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
      ));
    } else {
      setCart([...cart, { ...item, quantity: 1 }]);
    }
  };

  const updateQuantity = (itemId: number, delta: number) => {
    setCart(cart.map(item => {
      if (item.id === itemId) {
        const newQuantity = item.quantity + delta;
        return newQuantity > 0 ? { ...item, quantity: newQuantity } : item;
      }
      return item;
    }).filter(item => item.quantity > 0));
  };

  const removeFromCart = (itemId: number) => {
    setCart(cart.filter(item => item.id !== itemId));
  };

  const getTotal = () => {
    return cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  };

  const handleCheckout = async () => {
    if (cart.length === 0) {
      toast({ title: t('error'), description: t('cartEmpty'), variant: 'destructive' });
      return;
    }

    try {
      toast({ title: t('success'), description: `${t('total')}: $${getTotal().toFixed(2)}` });
      setCart([]);
    } catch (error: any) {
      toast({ title: t('error'), description: error?.message || t('error'), variant: 'destructive' });
    }
  };

  const filteredProducts = products.filter(p =>
    p.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    p.barcode?.includes(searchTerm)
  );

  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">
          <CreditCard className="w-8 h-8 text-orange-600" />
          <div>
            <h1 className="text-3xl font-bold text-gray-900">{t('posTerminal')}</h1>
            <p className="text-gray-600">{t('currentSale')}</p>
          </div>
        </div>

        <div className="mb-4">
          <Input
            placeholder={t('searchPlaceholder')}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="max-w-md"
          />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Products */}
          <div className="lg:col-span-2 grid gap-4 md:grid-cols-2">
            {filteredProducts.length === 0 ? (
              <div className="col-span-2 text-center py-12">
                <Package className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
                <p className="text-muted-foreground">{t('noProducts')}</p>
                <p className="text-sm text-muted-foreground">{t('addProducts')}</p>
              </div>
            ) : (
              filteredProducts.map((item) => (
                <Card key={item.id} className="cursor-pointer hover:shadow-lg transition-shadow" onClick={() => addToCart(item)}>
                  <CardHeader>
                    <CardTitle className="text-base">{item.name}</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      {item.barcode && (
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <Barcode className="w-3 h-3" />
                          {item.barcode}
                        </div>
                      )}
                        <div className="flex justify-between items-center">
                          <Badge variant="outline">{item.category}</Badge>
                          <span className="text-lg font-bold">{item.formattedPrice || `$${item.price}`}</span>
                        </div>
                      <p className="text-xs text-muted-foreground">{t('stock')}: {item.stock}</p>
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
          </div>

            {/* Cart */}
            <div className="lg:col-span-1">
              <Card className="sticky top-6">
                <CardHeader>
                  <CardTitle>{t('currentSale')}</CardTitle>
                </CardHeader>
                <CardContent>
                  {cart.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-8">
                      {t('cartEmpty')}
                    </p>
                  ) : (
                    <>
                      <div className="space-y-2 mb-4">
                        {cart.map((item) => (
                          <div key={item.id} className="flex items-center justify-between border-b pb-2">
                            <div className="flex-1">
                              <p className="font-medium text-sm">{item.name}</p>
                              <p className="text-xs text-muted-foreground">{item.formattedPrice || `$${item.price}`}</p>
                            </div>
                            <div className="flex items-center gap-2">
                              <Button size="sm" variant="outline" onClick={() => updateQuantity(item.id, -1)}>
                                <Minus className="w-3 h-3" />
                              </Button>
                              <span className="w-8 text-center">{item.quantity}</span>
                              <Button size="sm" variant="outline" onClick={() => updateQuantity(item.id, 1)}>
                                <Plus className="w-3 h-3" />
                              </Button>
                              <Button size="sm" variant="ghost" onClick={() => removeFromCart(item.id)}>
                                <Trash2 className="w-4 h-4 text-red-500" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                      <div className="border-t pt-4 space-y-2">
                        <div className="flex justify-between text-lg font-bold">
                          <span>{t('total')}:</span>
                          <span>${getTotal().toFixed(2)}</span>
                        </div>
                        <Button className="w-full" onClick={handleCheckout}>
                          <DollarSign className="w-4 h-4 mr-2" />
                          {t('processPay')}
                        </Button>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            </div>
          </div>
      </div>
    </div>
  );
};

export default POSTerminal;
