﻿'use client'

import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import { ShoppingCart, Plus, Minus, Trash2, ArrowLeft, Package, CheckCircle2 } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { formatCurrency } from '@/lib/types'
import { useCart } from '@/lib/cart'
import { getShopConfig, type ShopConfig } from '@/lib/shop'
import { useEffect, useState } from 'react'
import { cn } from '@/lib/utils'
import { ShopHeader } from '../ShopHeader'

export default function CartPage() {
  const params = useParams()
  const router = useRouter()
  const businessSlug = params.businessSlug as string
  const { state, removeItem, updateQuantity, clearCart } = useCart()
  const { items, subtotal, itemCount } = state

  // Authoritative pricing config (P1 fix): mirrors backend fee/tax rules.
  const [config, setConfig] = useState<ShopConfig | null>(null)
  useEffect(() => {
    getShopConfig(businessSlug).then(r => {
      if (r.success) setConfig(r.data)
    }).catch(() => undefined)
  }, [businessSlug])

  const deliveryFee =
    config == null
      ? null
      : config.free_delivery_threshold != null && subtotal >= config.free_delivery_threshold
        ? 0
        : config.delivery_fee
  const tax = config ? (subtotal * config.tax_rate_pct) / 100 : null
  const total = subtotal + (deliveryFee ?? 0) + (tax ?? 0)

  if (items.length === 0) {
    return (
      <>
        <ShopHeader businessSlug={businessSlug} />
        <div className="min-h-[70vh] bg-gray-50 dark:bg-gray-950 flex items-center justify-center px-4">
        <div className="text-center max-w-md">
          <ShoppingCart className="h-16 w-16 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">Your cart is empty</h1>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            Looks like you haven't added any products yet.
          </p>
          <Link href={`/shop/${params.businessSlug}`} className="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-lg font-medium transition-colors">
            <Package className="h-4 w-4" />
            Continue Shopping
          </Link>
        </div>
        </div>
      </>
    )
  }

  return (
    <>
      <ShopHeader businessSlug={businessSlug} />
      <div className="bg-gray-50 dark:bg-gray-950 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-8">
          <Link href={`/shop/${params.businessSlug}`} className="inline-flex items-center gap-2 text-indigo-600 dark:text-indigo-400 hover:underline">
            <ArrowLeft className="h-4 w-4" />
            Back to Store
          </Link>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Shopping Cart ({itemCount} items)</h1>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Cart Items */}
          <div className="lg:col-span-2 space-y-4">
            {items.map(item => (
              <Card key={item.productId} className="flex flex-col sm:flex-row">
                <div className="relative aspect-square w-full sm:w-32 bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden flex-shrink-0">
                  {item.imageUrl ? (
                    <img src={item.imageUrl} alt={item.productName} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-400">
                      <Package className="h-8 w-8" />
                    </div>
                  )}
                </div>
                <CardContent className="flex-1 p-4 flex flex-col justify-between">
                  <div>
                    <Link href={`/shop/${params.businessSlug}/product/${item.productSlug}`} className="font-semibold text-gray-900 dark:text-white hover:text-indigo-600 dark:hover:text-indigo-400">
                      {item.productName}
                    </Link>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{item.category}</p>
                    <p className="text-lg font-semibold text-gray-900 dark:text-white mt-2">{formatCurrency(item.unitPrice)}</p>
                  </div>
                  <div className="flex items-center justify-between mt-4">
                    <div className="flex items-center gap-2 border border-gray-300 dark:border-gray-600 rounded-lg">
                      <button
                        onClick={() => updateQuantity(item.productId, item.quantity - 1)}
                        disabled={item.quantity <= 1}
                        className="p-2 rounded-l-lg border-r border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
                        aria-label="Decrease quantity"
                      >
                        <span className="text-xl">−</span>
                      </button>
                      <span className="w-10 text-center font-medium">{item.quantity}</span>
                      <button
                        onClick={() => updateQuantity(item.productId, item.quantity + 1)}
                        className="p-2 rounded-r-lg border-l border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800"
                        aria-label="Increase quantity"
                      >
                        <span className="text-xl">+</span>
                      </button>
                    </div>
                    <p className="text-lg font-semibold text-gray-900 dark:text-white">
                      {formatCurrency(item.lineTotal)}
                    </p>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Order Summary */}
          <div className="lg:col-span-1">
            <Card className="sticky top-24">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Package className="h-5 w-5" />
                  Order Summary
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Subtotal ({itemCount} items)</span>
                    <span className="font-medium">{formatCurrency(subtotal)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500 dark:text-gray-400">Delivery</span>
                    <span className="font-medium">
                      {deliveryFee === null ? (
                        '…'
                      ) : deliveryFee === 0 ? (
                        <span className="text-green-600 dark:text-green-400">Free</span>
                      ) : (
                        formatCurrency(deliveryFee)
                      )}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500 dark:text-gray-400">
                      Tax{config && config.tax_rate_pct ? ` (${config.tax_rate_pct}%)` : ''}
                    </span>
                    <span className="font-medium">{tax === null ? '…' : formatCurrency(tax)}</span>
                  </div>
                  <div className="border-t border-gray-200 dark:border-gray-700 pt-2">
                    <div className="flex justify-between text-lg font-bold">
                      <span>Total</span>
                      <span>{deliveryFee === null || tax === null ? '…' : formatCurrency(total)}</span>
                    </div>
                  </div>
                </div>

                {config?.free_delivery_threshold != null &&
                  subtotal > 0 &&
                  subtotal < config.free_delivery_threshold && (
                  <div className="p-3 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded-lg text-sm text-amber-700 dark:text-amber-400">
                    Add {formatCurrency(config.free_delivery_threshold - subtotal)} more for free delivery!
                  </div>
                )}

                <Link href={`/shop/${params.businessSlug}/checkout`}>
                  <Button className="w-full" size="lg">
                    <ShoppingCart className="h-4 w-4 mr-2" />
                    Proceed to Checkout
                  </Button>
                </Link>

                <Button
                  onClick={clearCart}
                  variant="ghost"
                  className="w-full text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  Clear Cart
                </Button>

                <div className="pt-4 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400 space-y-1">
                  <p>Secure checkout powered by IMBARAGA</p>
                  <p>Your payment information is encrypted</p>
                </div>
              </CardContent>
</Card>

          </div>

        </div>

      </div>

      </div>

      </>
    )

  }

