'use client'

import { useState, useMemo } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import { Separator } from '@/components/ui/separator'
import { Plus, Minus, Trash2, ShoppingCart, CheckCircle2, Loader2, Receipt } from 'lucide-react'
import { toast } from 'sonner'
import type { Product, MaterialWithStock } from '@/lib/supabase/types'
import { formatMNT } from '@/lib/format'

type TechCard = { product_id: string; raw_material_id: string; amount: number }
type CartItem = { product: Product; qty: number }
type RecentSale = {
  id: string
  total_amount: number
  net_profit: number
  payment_method: string
  created_at: string
  sale_items: { product_name: string; quantity: number; unit_price: number }[]
}

const CATEGORIES = [
  { value: 'all', label: 'Бүгд' },
  { value: 'coffee', label: 'Кофе' },
  { value: 'tea', label: 'Цай' },
  { value: 'cake', label: 'Бялуу' },
  { value: 'cookie', label: 'Жигнэмэг' },
  { value: 'sandwich', label: 'Сэндвич' },
  { value: 'juice', label: 'Шүүс' },
  { value: 'other', label: 'Бусад' },
]

export function SalesClient({
  orgId,
  branchId,
  products,
  materials,
  techCards,
  recentSales: initialSales,
}: {
  orgId: string
  branchId: string
  products: Product[]
  materials: MaterialWithStock[]
  techCards: TechCard[]
  recentSales: RecentSale[]
}) {
  const [cart, setCart] = useState<CartItem[]>([])
  const [payMethod, setPayMethod] = useState<'cash' | 'card'>('cash')
  const [processing, setProcessing] = useState(false)
  const [successSale, setSuccessSale] = useState<{ total: number; profit: number } | null>(null)
  const [recentSales, setRecentSales] = useState(initialSales)
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [search, setSearch] = useState('')
  const supabase = createClient()

  const filteredProducts = useMemo(() =>
    products.filter(p => {
      const catMatch = categoryFilter === 'all' || p.category === categoryFilter
      const nameMatch = p.name.toLowerCase().includes(search.toLowerCase())
      return catMatch && nameMatch
    }),
    [products, categoryFilter, search]
  )

  function computeCostForProduct(productId: string): number {
    const rows = techCards.filter(t => t.product_id === productId)
    return rows.reduce((sum, t) => {
      const mat = materials.find(m => m.id === t.raw_material_id)
      return sum + (mat?.price_per_unit ?? 0) * t.amount
    }, 0)
  }

  function addToCart(product: Product) {
    setCart(prev => {
      const existing = prev.find(c => c.product.id === product.id)
      if (existing) return prev.map(c => c.product.id === product.id ? { ...c, qty: c.qty + 1 } : c)
      return [...prev, { product, qty: 1 }]
    })
  }

  function changeQty(productId: string, delta: number) {
    setCart(prev =>
      prev.map(c => c.product.id === productId ? { ...c, qty: Math.max(1, c.qty + delta) } : c)
    )
  }

  function removeFromCart(productId: string) {
    setCart(prev => prev.filter(c => c.product.id !== productId))
  }

  const totalAmount = cart.reduce((s, c) => s + c.product.selling_price * c.qty, 0)
  const totalCost = cart.reduce((s, c) => s + computeCostForProduct(c.product.id) * c.qty, 0)
  const netProfit = totalAmount - totalCost

  async function handleCheckout() {
    if (cart.length === 0) { toast.error('Сагс хоосон байна'); return }
    setProcessing(true)

    const { data: sale, error: saleErr } = await supabase
      .from('sales')
      .insert({
        org_id: orgId,
        branch_id: branchId,
        total_amount: totalAmount,
        total_cost: totalCost,
        net_profit: netProfit,
        payment_method: payMethod,
      })
      .select()
      .single()

    if (saleErr) { toast.error(saleErr.message); setProcessing(false); return }

    const saleItems = cart.map(c => ({
      sale_id: sale.id,
      product_id: c.product.id,
      product_name: c.product.name,
      quantity: c.qty,
      unit_price: c.product.selling_price,
      cost_price: computeCostForProduct(c.product.id),
    }))

    const { error: itemsErr } = await supabase.from('sale_items').insert(saleItems)
    if (itemsErr) { toast.error(itemsErr.message); setProcessing(false); return }

    // Deduct raw materials from branch_stock
    const stockUpdates: Record<string, number> = {}
    for (const c of cart) {
      const rows = techCards.filter(t => t.product_id === c.product.id)
      for (const t of rows) {
        stockUpdates[t.raw_material_id] = (stockUpdates[t.raw_material_id] ?? 0) + t.amount * c.qty
      }
    }

    await Promise.all(
      Object.entries(stockUpdates).map(async ([matId, used]) => {
        const mat = materials.find(m => m.id === matId)
        if (!mat || !mat.stock_id) return
        const newStock = Math.max(0, mat.current_stock - used)
        await supabase
          .from('branch_stock')
          .update({ current_stock: newStock })
          .eq('id', mat.stock_id)
        mat.current_stock = newStock
      })
    )

    setRecentSales(prev => [{
      id: sale.id,
      total_amount: sale.total_amount,
      total_cost: sale.total_cost,
      net_profit: sale.net_profit,
      payment_method: sale.payment_method,
      created_at: sale.created_at,
      sale_items: saleItems.map(si => ({ product_name: si.product_name, quantity: si.quantity, unit_price: si.unit_price })),
    }, ...prev.slice(0, 19)])

    setSuccessSale({ total: totalAmount, profit: netProfit })
    setCart([])
    setProcessing(false)
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-900">Борлуулалт</h1>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        {/* Left: Product picker */}
        <div className="xl:col-span-2 space-y-4">
          <div className="flex gap-2 flex-wrap">
            {CATEGORIES.map(cat => (
              <Button
                key={cat.value}
                size="sm"
                variant={categoryFilter === cat.value ? 'default' : 'outline'}
                className={categoryFilter === cat.value ? 'bg-amber-600 hover:bg-amber-700' : ''}
                onClick={() => setCategoryFilter(cat.value)}
              >
                {cat.label}
              </Button>
            ))}
          </div>
          <Input
            placeholder="Бүтээгдэхүүн хайх..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="max-w-xs"
          />
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
            {filteredProducts.map(p => {
              const inCart = cart.find(c => c.product.id === p.id)
              return (
                <button
                  key={p.id}
                  onClick={() => addToCart(p)}
                  className={`text-left p-3 rounded-xl border-2 transition-all hover:shadow-md active:scale-95 ${inCart ? 'border-amber-400 bg-amber-50' : 'border-gray-200 bg-white hover:border-amber-300'}`}
                >
                  <p className="font-medium text-sm text-gray-900 leading-tight">{p.name}</p>
                  <p className="text-amber-600 font-bold text-sm mt-1">{formatMNT(p.selling_price)}</p>
                  {inCart && (
                    <Badge className="mt-1 bg-amber-600 text-white text-xs">{inCart.qty}ш</Badge>
                  )}
                </button>
              )
            })}
          </div>
        </div>

        {/* Right: Cart & checkout */}
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                <ShoppingCart className="h-4 w-4" />
                Сагс {cart.length > 0 && <Badge variant="secondary">{cart.reduce((s, c) => s + c.qty, 0)}ш</Badge>}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {cart.length === 0 ? (
                <p className="text-sm text-gray-400 text-center py-6">Бүтээгдэхүүн сонгоно уу</p>
              ) : (
                <div className="space-y-2">
                  {cart.map(c => (
                    <div key={c.product.id} className="flex items-center gap-2">
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate">{c.product.name}</p>
                        <p className="text-xs text-gray-400">{formatMNT(c.product.selling_price)} × {c.qty}</p>
                      </div>
                      <div className="flex items-center gap-1">
                        <Button variant="outline" size="sm" className="h-6 w-6 p-0" onClick={() => changeQty(c.product.id, -1)}>
                          <Minus className="h-3 w-3" />
                        </Button>
                        <span className="text-sm w-5 text-center">{c.qty}</span>
                        <Button variant="outline" size="sm" className="h-6 w-6 p-0" onClick={() => changeQty(c.product.id, 1)}>
                          <Plus className="h-3 w-3" />
                        </Button>
                        <Button variant="ghost" size="sm" className="h-6 w-6 p-0 text-red-400" onClick={() => removeFromCart(c.product.id)}>
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {cart.length > 0 && (
                <>
                  <Separator />
                  <div className="space-y-1 text-sm">
                    <div className="flex justify-between text-gray-500">
                      <span>Нийт дүн</span>
                      <span className="font-medium text-gray-900">{formatMNT(totalAmount)}</span>
                    </div>
                    <div className="flex justify-between text-gray-500">
                      <span>Өртөг</span>
                      <span className="text-red-500">{formatMNT(totalCost)}</span>
                    </div>
                    <div className="flex justify-between font-semibold text-green-600">
                      <span>Цэвэр ашиг</span>
                      <span>{formatMNT(netProfit)}</span>
                    </div>
                  </div>
                  <Separator />
                  <div className="space-y-2">
                    <p className="text-sm text-gray-500">Төлбөрийн хэлбэр</p>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        variant={payMethod === 'cash' ? 'default' : 'outline'}
                        className={payMethod === 'cash' ? 'bg-amber-600 hover:bg-amber-700' : ''}
                        size="sm"
                        onClick={() => setPayMethod('cash')}
                      >
                        Бэлэн
                      </Button>
                      <Button
                        variant={payMethod === 'card' ? 'default' : 'outline'}
                        className={payMethod === 'card' ? 'bg-amber-600 hover:bg-amber-700' : ''}
                        size="sm"
                        onClick={() => setPayMethod('card')}
                      >
                        Картаар
                      </Button>
                    </div>
                  </div>
                  <Button
                    className="w-full bg-green-600 hover:bg-green-700 text-white"
                    onClick={handleCheckout}
                    disabled={processing}
                  >
                    {processing ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <CheckCircle2 className="h-4 w-4 mr-2" />}
                    Төлбөр авах
                  </Button>
                </>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Recent sales */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Receipt className="h-4 w-4" />
            Сүүлийн борлуулалтууд
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-50">
                <TableHead>Огноо, цаг</TableHead>
                <TableHead>Бараа</TableHead>
                <TableHead>Төлбөр</TableHead>
                <TableHead className="text-right">Нийт дүн</TableHead>
                <TableHead className="text-right">Цэвэр ашиг</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {recentSales.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8 text-gray-400">
                    Борлуулалт байхгүй
                  </TableCell>
                </TableRow>
              ) : (
                recentSales.map(sale => (
                  <TableRow key={sale.id}>
                    <TableCell className="text-sm text-gray-500">
                      {new Date(sale.created_at).toLocaleString('mn-MN', {
                        month: 'short', day: 'numeric',
                        hour: '2-digit', minute: '2-digit',
                      })}
                    </TableCell>
                    <TableCell className="text-sm">
                      {sale.sale_items.map(i => `${i.product_name} ×${i.quantity}`).join(', ')}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs">
                        {sale.payment_method === 'cash' ? 'Бэлэн' : 'Картаар'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-medium">{formatMNT(sale.total_amount)}</TableCell>
                    <TableCell className="text-right font-medium text-green-600">{formatMNT(sale.net_profit)}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Success modal */}
      <Dialog open={!!successSale} onOpenChange={() => setSuccessSale(null)}>
        <DialogContent className="max-w-sm text-center">
          <DialogHeader>
            <div className="flex justify-center mb-2">
              <div className="bg-green-100 rounded-full p-3">
                <CheckCircle2 className="h-8 w-8 text-green-600" />
              </div>
            </div>
            <DialogTitle className="text-center">Төлбөр амжилттай!</DialogTitle>
          </DialogHeader>
          {successSale && (
            <div className="space-y-3 py-2">
              <div className="bg-gray-50 rounded-lg p-4 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Нийт дүн</span>
                  <span className="font-bold text-lg">{formatMNT(successSale.total)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Цэвэр ашиг</span>
                  <span className="font-bold text-green-600">{formatMNT(successSale.profit)}</span>
                </div>
              </div>
              <Button
                className="w-full bg-amber-600 hover:bg-amber-700"
                onClick={() => setSuccessSale(null)}
              >
                Дараагийн захиалга
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
