import { Link } from 'react-router-dom';
import { currency } from '../lib/format';
import { Card } from './ui/card';
import { Button } from './ui/button';
import { useApp } from '../context/AppContext';
import { ShoppingBag, Trash2, ShoppingCart, ArrowRight, Package, Scissors } from 'lucide-react';

export const CartPanel = () => {
  const { cart, shops, removeFromCart, placeOrder, user } = useApp();

  if (!cart.length) {
    return (
      <div className="py-20 text-center space-y-6 animate-in fade-in zoom-in duration-500">
        <div className="w-24 h-24 bg-slate-50 rounded-full flex items-center justify-center mx-auto text-slate-200 shadow-inner">
           <ShoppingCart size={48} />
        </div>
        <div className="space-y-2">
           <h3 className="text-2xl font-black text-slate-900 uppercase italic tracking-tighter">O seu carrinho está vazio</h3>
           <p className="text-slate-500 font-medium italic">Explore os melhores produtos e serviços disponíveis.</p>
        </div>
        <Button asChild className="h-14 px-8 bg-slate-900 hover:bg-slate-800 text-indigo-400 font-black rounded-2xl uppercase tracking-widest text-xs italic">
           <Link to="/explorar">Ver Barbearias</Link>
        </Button>
      </div>
    );
  }

  const grouped = cart.reduce<Record<string, typeof cart>>((acc, item) => {
    acc[item.shopId] = acc[item.shopId] || [];
    acc[item.shopId].push(item);
    return acc;
  }, {});

  const handleCheckout = async (shopId: string) => {
    if (!user) return;
    try {
      const order = await placeOrder(user.id, shopId);
      if (order) {
        alert("O seu pedido foi enviado à Barbearia com sucesso! Irá ser notificado brevemente.");
      } else {
        alert("Desculpe, ocorreu um erro a processar a sua encomenda.");
      }
    } catch (e) {
      alert("Falha técnica no processo de Checkout.");
    }
  };

  return (
    <div className="space-y-10 pb-10">
      {Object.entries(grouped).map(([shopId, items]) => {
        const shop = shops.find((s) => s.id === shopId);
        const total = items.reduce((sum, i) => {
          const price =
            i.type === 'service'
              ? shop?.services.find((s) => s.id === i.refId)?.price ?? 0
              : shop?.products.find((p) => p.id === i.refId)?.price ?? 0;
          return sum + price * i.qty;
        }, 0);

        return (
          <div key={shopId} className="space-y-4 animate-in fade-in slide-in-from-bottom-4 duration-500">
            <div className="flex items-center gap-2 px-2">
               <ShoppingBag size={14} className="text-indigo-600" />
               <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-400">Origem: <span className="text-slate-900">{shop?.name ?? 'Barbearia'}</span></h3>
            </div>

            <Card className="p-2 border-none glass-card rounded-[2.5rem] shadow-xl shadow-slate-200/50 overflow-hidden">
               <div className="p-6 md:p-8 space-y-6">
                  <div className="space-y-4">
                     {items.map((i) => {
                       const ref =
                         i.type === 'service'
                           ? shop?.services.find((s) => s.id === i.refId)
                           : shop?.products.find((p) => p.id === i.refId);
                       
                       return (
                         <div key={i.refId} className="flex items-center justify-between group py-2">
                           <div className="flex items-center gap-4">
                              <div className="w-12 h-12 bg-slate-50 rounded-xl flex items-center justify-center text-slate-400 border border-slate-100 italic font-black text-xs">
                                 {i.type === 'service' ? <Scissors size={20} /> : <Package size={20} />}
                              </div>
                              <div>
                                 <p className="font-black text-slate-900 uppercase italic tracking-tight">{ref?.name ?? 'Item'}</p>
                                 <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">
                                    {i.qty} unidade{i.qty > 1 ? 's' : ''} • {currency(ref?.price || 0)}
                                 </p>
                              </div>
                           </div>
                           <button 
                             className="w-10 h-10 rounded-full flex items-center justify-center text-slate-300 hover:text-rose-500 hover:bg-rose-50 transition-all active:scale-90" 
                             onClick={() => removeFromCart(i.refId)}
                           >
                             <Trash2 size={18} />
                           </button>
                         </div>
                       );
                     })}
                  </div>

                  <div className="pt-6 border-t border-slate-100 flex items-end justify-between">
                     <div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Total do Pedido</p>
                        <p className="text-3xl font-black text-slate-900 tracking-tighter italic">{currency(total)}</p>
                     </div>
                     {user ? (
                       <Button 
                         onClick={() => handleCheckout(shopId)}
                         className="h-14 px-8 bg-slate-900 hover:bg-slate-800 text-indigo-400 font-black rounded-2xl uppercase tracking-widest text-xs italic shadow-lg active:scale-95 transition-all"
                       >
                         Finalizar Compra
                         <ArrowRight size={14} className="ml-2" />
                       </Button>
                     ) : (
                       <Button asChild className="h-14 px-8 bg-slate-100 text-slate-900 hover:bg-slate-200 font-black rounded-2xl uppercase tracking-widest text-xs italic">
                         <Link to="/login">Entrar para Comprar</Link>
                       </Button>
                     )}
                  </div>
               </div>
            </Card>
          </div>
        );
      })}
    </div>
  );
};





