'use client'

import { useState } 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 {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Plus, Pencil, Trash2, Coffee, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import type { Product } from '@/lib/supabase/types'
import { formatMNT } from '@/lib/format'

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

const categoryBadge: Record<string, string> = {
  coffee: 'bg-amber-100 text-amber-700',
  tea: 'bg-green-100 text-green-700',
  cake: 'bg-pink-100 text-pink-700',
  cookie: 'bg-orange-100 text-orange-700',
  sandwich: 'bg-yellow-100 text-yellow-700',
  juice: 'bg-cyan-100 text-cyan-700',
  other: 'bg-gray-100 text-gray-600',
}

type Form = { name: string; category: string; selling_price: string }
const emptyForm: Form = { name: '', category: 'coffee', selling_price: '' }

export function ProductsClient({ orgId, initialProducts }: {
  orgId: string; initialProducts: Product[]
}) {
  const [products, setProducts] = useState(initialProducts)
  const [open, setOpen] = useState(false)
  const [form, setForm] = useState<Form>(emptyForm)
  const [editing, setEditing] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)
  const [search, setSearch] = useState('')
  const supabase = createClient()

  function openNew() {
    setEditing(null)
    setForm(emptyForm)
    setOpen(true)
  }

  function openEdit(p: Product) {
    setEditing(p.id)
    setForm({ name: p.name, category: p.category, selling_price: String(p.selling_price) })
    setOpen(true)
  }

  async function handleSave() {
    if (!form.name || !form.selling_price) {
      toast.error('Нэр болон үнэ заавал оруулна уу')
      return
    }
    setSaving(true)
    const payload = {
      name: form.name.trim(),
      category: form.category,
      selling_price: Number(form.selling_price),
    }
    if (editing) {
      const { data, error } = await supabase.from('products').update(payload).eq('id', editing).select().single()
      if (error) { toast.error(error.message); setSaving(false); return }
      setProducts(prev => prev.map(p => p.id === editing ? data : p))
      toast.success('Амжилттай шинэчлэгдлээ')
    } else {
      const { data, error } = await supabase.from('products').insert({ ...payload, org_id: orgId }).select().single()
      if (error) { toast.error(error.message); setSaving(false); return }
      setProducts(prev => [...prev, data])
      toast.success('Бүтээгдэхүүн нэмэгдлээ')
    }
    setSaving(false)
    setOpen(false)
  }

  async function handleDelete(id: string) {
    if (!confirm('Устгах уу? Технологийн карт ч устгагдана.')) return
    const { error } = await supabase.from('products').delete().eq('id', id)
    if (error) { toast.error(error.message); return }
    setProducts(prev => prev.filter(p => p.id !== id))
    toast.success('Устгагдлаа')
  }

  const filtered = products.filter(p =>
    p.name.toLowerCase().includes(search.toLowerCase())
  )

  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">Нийт {products.length} бүтээгдэхүүн</p>
        </div>
        <Button onClick={openNew} className="bg-amber-600 hover:bg-amber-700">
          <Plus className="h-4 w-4 mr-2" /> Нэмэх
        </Button>
      </div>

      <Input
        placeholder="Хайх..."
        value={search}
        onChange={e => setSearch(e.target.value)}
        className="max-w-xs"
      />

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-gray-50">
              <TableHead>Нэр</TableHead>
              <TableHead>Ангилал</TableHead>
              <TableHead className="text-right">Зарах үнэ</TableHead>
              <TableHead className="text-right">Үйлдэл</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="text-center py-12 text-gray-400">
                  <Coffee className="h-10 w-10 mx-auto mb-2 opacity-30" />
                  Бүтээгдэхүүн олдсонгүй
                </TableCell>
              </TableRow>
            ) : (
              filtered.map(p => (
                <TableRow key={p.id} className="hover:bg-gray-50">
                  <TableCell className="font-medium">{p.name}</TableCell>
                  <TableCell>
                    <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${categoryBadge[p.category] ?? categoryBadge.other}`}>
                      {CATEGORIES.find(c => c.value === p.category)?.label ?? p.category}
                    </span>
                  </TableCell>
                  <TableCell className="text-right font-medium">{formatMNT(p.selling_price)}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex gap-1 justify-end">
                      <Button variant="ghost" size="sm" onClick={() => openEdit(p)}>
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost" size="sm"
                        className="text-red-500 hover:text-red-700 hover:bg-red-50"
                        onClick={() => handleDelete(p.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{editing ? 'Бүтээгдэхүүн засах' : 'Шинэ бүтээгдэхүүн нэмэх'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label>Нэр</Label>
              <Input
                placeholder="Жишээ: Капучино"
                value={form.name}
                onChange={e => setForm(p => ({ ...p, name: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>Ангилал</Label>
                <Select value={form.category} onValueChange={v => v && setForm(p => ({ ...p, category: v }))}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {CATEGORIES.map(c => (
                      <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label>Зарах үнэ (₮)</Label>
                <Input
                  type="number"
                  placeholder="0"
                  value={form.selling_price}
                  onChange={e => setForm(p => ({ ...p, selling_price: e.target.value }))}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Цуцлах</Button>
            <Button className="bg-amber-600 hover:bg-amber-700" onClick={handleSave} disabled={saving}>
              {saving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
              Хадгалах
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
