'use client'

import { Product, Category } from '@/lib/types'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Edit2, Trash2, Layers, ArrowUpDown, Copy } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { deleteProduct, transferModules } from '@/lib/actions/products'
import { useState, useEffect, useMemo, Fragment } from 'react'
import { CreateProductDialog } from './create-product-dialog'
import { useRouter } from 'next/navigation'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"

export function ProductList({ initialProducts, categories }: { initialProducts: Product[], categories: Category[] }) {
  const [products, setProducts] = useState(initialProducts)
  const [isGroupedByCategory, setIsGroupedByCategory] = useState(false)
  const [showKauf, setShowKauf] = useState(true)
  const [showAbo, setShowAbo] = useState(true)
  const [copySourceProduct, setCopySourceProduct] = useState<Product | null>(null)
  const [copyTargetProductId, setCopyTargetProductId] = useState<string>('')
  const [copyMode, setCopyMode] = useState<'overwrite' | 'append'>('overwrite')
  const [isCopying, setIsCopying] = useState(false)
  const router = useRouter()

  const handleCopyModules = async () => {
    if (!copySourceProduct || !copyTargetProductId) return
    setIsCopying(true)
    try {
      await transferModules(copySourceProduct.id, copyTargetProductId, copyMode)
      setCopySourceProduct(null)
      setCopyTargetProductId('')
      router.refresh()
    } catch (err) {
      console.error('Error copying modules:', err)
      alert('Fehler beim Kopieren der Module.')
    } finally {
      setIsCopying(false)
    }
  }

  useEffect(() => {
    setProducts(initialProducts)
  }, [initialProducts])

  const handleDelete = async (id: string) => {
    if (confirm('Möchten Sie dieses Produkt wirklich löschen?')) {
      await deleteProduct(id)
      setProducts(products.filter(p => p.id !== id))
    }
  }

  const toggleGroupByCategory = () => {
    setIsGroupedByCategory(!isGroupedByCategory)
  }

  const filteredProducts = useMemo(() => {
    return products.filter(p => {
      const inKauf = p.show_in_kauf ?? true
      const inAbo = p.show_in_abo ?? true
      if (showKauf && inKauf) return true
      if (showAbo && inAbo) return true
      return false
    })
  }, [products, showKauf, showAbo])

  const groupedProducts = useMemo(() => {
    const groups: Record<string, { category: Category | null; products: Product[] }> = {}
    filteredProducts.forEach(p => {
      const catId = p.category_id || 'no-category'
      if (!groups[catId]) {
        groups[catId] = {
          category: p.category || null,
          products: []
        }
      }
      groups[catId].products.push(p)
    })
    return Object.values(groups).sort((a, b) => {
      const orderA = a.category?.sort_order ?? 9999
      const orderB = b.category?.sort_order ?? 9999
      return orderA - orderB
    })
  }, [filteredProducts])

  const renderProductRow = (product: Product) => (
    <TableRow key={product.id} className="border-slate-100 dark:border-white/5 hover:bg-slate-50 dark:hover:bg-white/5 transition-colors">
      <TableCell className="font-medium text-slate-900 dark:text-white">
        <div className="flex flex-col gap-1">
          <div className="flex items-center gap-2">
            {product.name}
            {product.category && (
              <Badge variant="outline" className="text-[10px] uppercase border-primary/30 text-primary py-0 h-4">
                {product.category.name}
              </Badge>
            )}
            {product.billing_interval === 'monthly' && (
              <Badge className="text-[10px] bg-blue-500/20 text-blue-600 dark:text-blue-400 border border-blue-500/30 py-0 h-4">Abo/Monat</Badge>
            )}
            {product.billing_interval === 'one_time' && (
              <Badge className="text-[10px] bg-slate-500/20 text-slate-600 dark:text-slate-300 border border-slate-500/30 py-0 h-4">Einmalig</Badge>
            )}
          </div>
          <p className="text-xs text-slate-500 dark:text-slate-400 font-normal">{product.description}</p>
        </div>
      </TableCell>
      <TableCell className="text-slate-900 dark:text-white font-semibold">{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(product.base_price)}</TableCell>
      <TableCell>
        <div className="flex items-center gap-1">
          <Layers className="w-3 h-3 text-primary" />
          <span className="text-slate-700 dark:text-slate-200">{product.modules?.length || 0} Module</span>
        </div>
      </TableCell>
      <TableCell>
        <Badge variant={product.billing_interval === 'monthly' ? 'default' : 'secondary'}>
          {product.billing_interval === 'monthly' ? 'Abo/Monat' : 'Einmalig'}
        </Badge>
      </TableCell>
      <TableCell className="text-right">
        <div className="flex justify-end gap-2">
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
            onClick={() => {
              setCopySourceProduct(product)
              setCopyTargetProductId('')
            }}
            title="Module kopieren"
          >
            <Copy className="h-4 w-4" />
          </Button>
          <CreateProductDialog categories={categories} product={product} products={products}>
            <Button variant="ghost" size="icon" className="h-8 w-8 text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white">
              <Edit2 className="h-4 w-4" />
            </Button>
          </CreateProductDialog>
          <Button 
            variant="ghost" 
            size="icon" 
            className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
            onClick={() => handleDelete(product.id)}
          >
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      </TableCell>
    </TableRow>
  )

  return (
    <>
      <Card className="bg-white dark:bg-slate-900/50 border border-slate-200 dark:border-white/10 shadow-sm overflow-hidden text-slate-900 dark:text-white">
        <CardHeader className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
          <div>
            <CardTitle>Produktübersicht</CardTitle>
            <CardDescription className="text-slate-500 dark:text-slate-400">
              Alle konfigurierten Software-Lösungen und Erweiterungen.
            </CardDescription>
          </div>
          <div className="flex flex-wrap items-center gap-6">
            <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 cursor-pointer select-none">
              <Checkbox
                checked={showKauf}
                onCheckedChange={(checked) => setShowKauf(!!checked)}
              />
              In Kaufauswahl
            </label>
            <label className="flex items-center gap-2 text-sm font-medium text-slate-700 dark:text-slate-300 cursor-pointer select-none">
              <Checkbox
                checked={showAbo}
                onCheckedChange={(checked) => setShowAbo(!!checked)}
              />
              In Aboauswahl
            </label>
            <Button
              variant="outline"
              size="sm"
              onClick={toggleGroupByCategory}
              className={`border-slate-200 dark:border-white/10 hover:bg-slate-100 dark:hover:bg-white/10 text-slate-700 dark:text-white ${
                isGroupedByCategory ? 'bg-primary/10 border-primary text-primary hover:bg-primary/20 dark:bg-primary/20 dark:border-primary dark:text-primary-foreground' : ''
              }`}
            >
              <ArrowUpDown className="w-4 h-4 mr-2" />
              {isGroupedByCategory ? 'Kategoriengruppierung aktiv' : 'Nach Kategorien gruppieren'}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow className="border-slate-200 dark:border-white/10 hover:bg-slate-50 dark:hover:bg-white/5">
                <TableHead className="text-slate-700 dark:text-white font-bold">Name</TableHead>
                <TableHead className="text-slate-700 dark:text-white font-bold">Basispreis</TableHead>
                <TableHead className="text-slate-700 dark:text-white font-bold">Module</TableHead>
                <TableHead className="text-slate-700 dark:text-white font-bold">Status</TableHead>
                <TableHead className="text-right text-slate-700 dark:text-white font-bold">Aktionen</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isGroupedByCategory ? (
                groupedProducts.map((group) => (
                  <Fragment key={group.category?.id || 'no-category'}>
                    <TableRow className="bg-slate-100 dark:bg-slate-800/40 hover:bg-slate-100 dark:hover:bg-slate-800/40 border-b border-slate-200 dark:border-white/10">
                      <TableCell colSpan={5} className="text-primary font-bold py-2.5 text-xs uppercase tracking-wider">
                        {group.category ? group.category.name : 'Keine Kategorie'}
                      </TableCell>
                    </TableRow>
                    {group.products.map((product) => renderProductRow(product))}
                  </Fragment>
                ))
              ) : (
                filteredProducts.map((product) => renderProductRow(product))
              )}
              {filteredProducts.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-10 text-slate-500 dark:text-slate-400">
                    Keine Produkte gefunden. Passen Sie Ihre Filter an.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={!!copySourceProduct} onOpenChange={(open) => { if (!open) setCopySourceProduct(null) }}>
        <DialogContent className="sm:max-w-[425px] bg-white dark:bg-slate-950 text-slate-900 dark:text-white border-slate-200 dark:border-white/10 shadow-2xl">
          <DialogHeader>
            <DialogTitle>Module übertragen</DialogTitle>
            <DialogDescription className="text-slate-500 dark:text-slate-400">
              Kopieren Sie alle Module von <strong>{copySourceProduct?.name}</strong> auf ein anderes Produkt.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-4">
            <div className="flex flex-col gap-2">
              <Label htmlFor="target-product">Ziel-Produkt</Label>
              <Select value={copyTargetProductId} onValueChange={setCopyTargetProductId}>
                <SelectTrigger id="target-product" className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white">
                  <SelectValue placeholder="Ziel-Produkt auswählen" />
                </SelectTrigger>
                <SelectContent className="bg-white dark:bg-slate-950 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white">
                  {products
                    .filter(p => p.id !== copySourceProduct?.id)
                    .map(p => (
                      <SelectItem key={p.id} value={p.id} className="focus:bg-slate-100 dark:focus:bg-white/5">
                        {p.name}
                      </SelectItem>
                    ))
                  }
                </SelectContent>
              </Select>
            </div>

            <div className="flex flex-col gap-2">
              <Label>Übertragungsmodus</Label>
              <RadioGroup value={copyMode} onValueChange={(val: any) => setCopyMode(val)} className="flex flex-col gap-2">
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="overwrite" id="mode-overwrite" />
                  <Label htmlFor="mode-overwrite" className="font-normal cursor-pointer text-slate-700 dark:text-slate-300">
                    Bestehende Module überschreiben
                  </Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="append" id="mode-append" />
                  <Label htmlFor="mode-append" className="font-normal cursor-pointer text-slate-700 dark:text-slate-300">
                    Module anfügen (bestehende behalten)
                  </Label>
                </div>
              </RadioGroup>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setCopySourceProduct(null)} disabled={isCopying} className="border-slate-200 dark:border-white/10 text-slate-900 dark:text-white">
              Abbrechen
            </Button>
            <Button onClick={handleCopyModules} disabled={!copyTargetProductId || isCopying} className="bg-primary text-white hover:bg-primary/90">
              {isCopying ? 'Wird kopiert...' : 'Module übertragen'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
