'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 { Label } from '@/components/ui/label'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/components/ui/dialog'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Plus, Trash2, BookOpen, Loader2, ChevronDown, ChevronUp } from 'lucide-react'
import { toast } from 'sonner'
import type { Product, RawMaterial } from '@/lib/supabase/types'
import { formatMNT } from '@/lib/format'

type CardRow = {
  id: string
  product_id: string
  raw_material_id: string
  amount: number
  products: { name: string; category: string } | null
  raw_materials: { name: string; unit: string } | null
}

export function TechCardsClient({
  products,
  materials,
  initialCards,
}: {
  orgId: string
  products: Product[]
  materials: RawMaterial[]
  initialCards: CardRow[]
}) {
  const [cards, setCards] = useState<CardRow[]>(initialCards)
  const [open, setOpen] = useState(false)
  const [selectedProduct, setSelectedProduct] = useState('')
  const [materialId, setMaterialId] = useState('')
  const [amount, setAmount] = useState('')
  const [saving, setSaving] = useState(false)
  const [expandedProducts, setExpandedProducts] = useState<Record<string, boolean>>({})
  const supabase = createClient()

  const byProduct = useMemo(() => {
    const map: Record<string, CardRow[]> = {}
    cards.forEach(c => {
      if (!map[c.product_id]) map[c.product_id] = []
      map[c.product_id].push(c)
    })
    return map
  }, [cards])

  function computeCost(productId: string): number {
    const rows = byProduct[productId] ?? []
    return rows.reduce((sum, c) => {
      const mat = materials.find(m => m.id === c.raw_material_id)
      return sum + (mat?.price_per_unit ?? 0) * c.amount
    }, 0)
  }

  function toggleProduct(id: string) {
    setExpandedProducts(prev => ({ ...prev, [id]: !prev[id] }))
  }

  async function handleAddCard() {
    if (!selectedProduct || !materialId || !amount) {
      toast.error('Бүх талбарыг бөглөнө үү')
      return
    }
    const existing = cards.find(c => c.product_id === selectedProduct && c.raw_material_id === materialId)
    if (existing) {
      toast.error('Энэ түүхий эд аль хэдийн нэмэгдсэн байна')
      return
    }
    setSaving(true)
    const { data, error } = await supabase
      .from('technology_cards')
      .insert({ product_id: selectedProduct, raw_material_id: materialId, amount: Number(amount) })
      .select('*, products(name, category), raw_materials(name, unit)')
      .single()
    if (error) { toast.error(error.message); setSaving(false); return }
    setCards(prev => [...prev, data as CardRow])
    setAmount('')
    setMaterialId('')
    toast.success('Орц нэмэгдлээ')
    setSaving(false)
  }

  async function handleDelete(id: string) {
    const { error } = await supabase.from('technology_cards').delete().eq('id', id)
    if (error) { toast.error(error.message); return }
    setCards(prev => prev.filter(c => c.id !== id))
    toast.success('Устгагдлаа')
  }

  const productsWithCards = products.filter(p => byProduct[p.id]?.length > 0)
  const productsWithoutCards = products.filter(p => !byProduct[p.id]?.length)

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Технологийн карт</h1>
          <p className="text-gray-500 text-sm mt-1">Бүтээгдэхүүний орц, зардлын тооцоо</p>
        </div>
        <Button onClick={() => setOpen(true)} className="bg-amber-600 hover:bg-amber-700">
          <Plus className="h-4 w-4 mr-2" /> Орц нэмэх
        </Button>
      </div>

      {products.length === 0 && (
        <div className="text-center py-16 text-gray-400">
          <BookOpen className="h-12 w-12 mx-auto mb-3 opacity-30" />
          <p>Эхлээд бүтээгдэхүүн нэмнэ үү</p>
        </div>
      )}

      {productsWithoutCards.length > 0 && productsWithCards.length > 0 && (
        <p className="text-sm text-amber-600 bg-amber-50 border border-amber-100 rounded-lg px-4 py-2">
          {productsWithoutCards.length} бүтээгдэхүүнд технологийн карт бүртгэгдээгүй байна
        </p>
      )}

      <div className="space-y-3">
        {products.map(product => {
          const rows = byProduct[product.id] ?? []
          const expanded = expandedProducts[product.id] !== false
          const cost = computeCost(product.id)
          const margin = product.selling_price > 0
            ? Math.round(((product.selling_price - cost) / product.selling_price) * 100)
            : 0

          return (
            <Card key={product.id} className="overflow-hidden">
              <CardHeader
                className="py-3 px-4 cursor-pointer hover:bg-gray-50 transition-colors"
                onClick={() => toggleProduct(product.id)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    {expanded ? (
                      <ChevronUp className="h-4 w-4 text-gray-400" />
                    ) : (
                      <ChevronDown className="h-4 w-4 text-gray-400" />
                    )}
                    <CardTitle className="text-base font-semibold">{product.name}</CardTitle>
                    <span className="text-xs text-gray-400">{rows.length} орц</span>
                  </div>
                  <div className="flex items-center gap-6 text-sm">
                    <div className="text-right">
                      <p className="text-xs text-gray-400">Өртөг</p>
                      <p className="font-medium text-gray-700">{formatMNT(cost)}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-gray-400">Зарах үнэ</p>
                      <p className="font-medium text-gray-700">{formatMNT(product.selling_price)}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-gray-400">Маржин</p>
                      <p className={`font-bold ${margin >= 50 ? 'text-green-600' : margin >= 20 ? 'text-amber-600' : 'text-red-600'}`}>
                        {margin}%
                      </p>
                    </div>
                  </div>
                </div>
              </CardHeader>
              {expanded && (
                <CardContent className="px-4 pb-4 pt-0">
                  {rows.length === 0 ? (
                    <p className="text-sm text-gray-400 py-3 text-center">Орц бүртгэгдээгүй байна</p>
                  ) : (
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-gray-100">
                          <th className="text-left py-2 text-gray-500 font-medium">Түүхий эд</th>
                          <th className="text-right py-2 text-gray-500 font-medium">Хэмжээ</th>
                          <th className="text-right py-2 text-gray-500 font-medium">Нэгжийн үнэ</th>
                          <th className="text-right py-2 text-gray-500 font-medium">Нийт зардал</th>
                          <th className="w-8"></th>
                        </tr>
                      </thead>
                      <tbody>
                        {rows.map(c => {
                          const mat = materials.find(m => m.id === c.raw_material_id)
                          const lineCost = (mat?.price_per_unit ?? 0) * c.amount
                          return (
                            <tr key={c.id} className="border-b border-gray-50 last:border-0 hover:bg-gray-50">
                              <td className="py-2">{c.raw_materials?.name}</td>
                              <td className="text-right py-2">{c.amount} {c.raw_materials?.unit}</td>
                              <td className="text-right py-2 text-gray-500">{mat ? formatMNT(mat.price_per_unit) : '—'}</td>
                              <td className="text-right py-2 font-medium">{formatMNT(lineCost)}</td>
                              <td className="text-right py-2">
                                <Button
                                  variant="ghost" size="sm"
                                  className="h-6 w-6 p-0 text-red-400 hover:text-red-600 hover:bg-red-50"
                                  onClick={() => handleDelete(c.id)}
                                >
                                  <Trash2 className="h-3.5 w-3.5" />
                                </Button>
                              </td>
                            </tr>
                          )
                        })}
                      </tbody>
                      <tfoot>
                        <tr>
                          <td colSpan={3} className="pt-2 text-right text-xs text-gray-400">Нийт өртөг:</td>
                          <td className="pt-2 text-right font-bold text-gray-800">{formatMNT(cost)}</td>
                          <td></td>
                        </tr>
                      </tfoot>
                    </table>
                  )}
                </CardContent>
              )}
            </Card>
          )
        })}
      </div>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Орц нэмэх</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label>Бүтээгдэхүүн</Label>
              <Select value={selectedProduct} onValueChange={v => v && setSelectedProduct(v)}>
                <SelectTrigger>
                  <SelectValue placeholder="Бүтээгдэхүүн сонгох" />
                </SelectTrigger>
                <SelectContent>
                  {products.map(p => (
                    <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>Түүхий эд</Label>
              <Select value={materialId} onValueChange={v => v && setMaterialId(v)}>
                <SelectTrigger>
                  <SelectValue placeholder="Түүхий эд сонгох" />
                </SelectTrigger>
                <SelectContent>
                  {materials.map(m => (
                    <SelectItem key={m.id} value={m.id}>
                      {m.name} ({m.unit})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>
                Хэмжээ
                {materialId && (
                  <span className="text-gray-400 ml-1 text-xs">
                    ({materials.find(m => m.id === materialId)?.unit})
                  </span>
                )}
              </Label>
              <Input
                type="number"
                placeholder="0"
                value={amount}
                onChange={e => setAmount(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Цуцлах</Button>
            <Button className="bg-amber-600 hover:bg-amber-700" onClick={handleAddCard} disabled={saving}>
              {saving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
              Нэмэх
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
