'use client'

import React from 'react'
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { Checkbox } from '@/components/ui/checkbox'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { ShoppingCart, Check, AlertCircle } from 'lucide-react'
import * as Icons from 'lucide-react'
import { Category, Product, CategorySelection } from '@/lib/types'

interface StepSoftwareProps {
  visibleCategories: Category[]
  products: Product[]
  selections: Record<string, CategorySelection>
  selectProduct: (catId: string, prodId: string) => void
  isProductDisabled: (prod: Product, catId: string) => boolean
  isModuleDisabled: (mod: any, selectedModIds: string[]) => boolean
  toggleModule: (catId: string, modId: string) => void
  moduleQuantities: Record<string, number>
  setModuleQuantities: React.Dispatch<React.SetStateAction<Record<string, number>>>
  selectedBillingInterval: 'one_time' | 'monthly'
  billingLabel: (interval: string) => string
  billingBadgeClass: (interval: string) => string
}

function CategoryIcon({ icon, className }: { icon?: string | null; className?: string }) {
  const LucideIcon = icon ? (Icons as any)[icon] : null
  if (!LucideIcon) return <Icons.HelpCircle className={className} />
  return <LucideIcon className={className} />
}

export function StepSoftware({
  visibleCategories,
  products,
  selections,
  selectProduct,
  isProductDisabled,
  isModuleDisabled,
  toggleModule,
  moduleQuantities,
  setModuleQuantities,
  selectedBillingInterval,
  billingLabel,
  billingBadgeClass,
}: StepSoftwareProps) {
  return (
    <Card className="glass-dark border-white/10">
      <CardHeader>
        <CardTitle className="text-2xl flex items-center gap-2 text-white">
          <ShoppingCart className="w-6 h-6 text-blue-400" />
          Software wählen
        </CardTitle>
        <CardDescription className="text-slate-300">
          Wählen Sie pro Kategorie mindestens einen Artikel aus.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-8">
            {visibleCategories.map((cat, idx) => {
              const catProducts = products.filter(p => {
                if (p.category_id !== cat.id) return false
                return selectedBillingInterval === 'one_time'
                  ? p.show_in_kauf !== false
                  : p.show_in_abo !== false
              })
              const sel = selections[cat.id]
              const selectedProduct = catProducts.find(p => p.id === sel?.productId) ?? null

              return (
                <div key={cat.id}>
                  {idx > 0 && <Separator className="bg-white/10 mb-8" />}

                  {/* Category header */}
                  <div className="flex items-center gap-3 mb-4">
                    <div className="w-8 h-8 rounded-lg bg-primary/20 flex items-center justify-center">
                      <CategoryIcon icon={cat.icon} className="w-4 h-4 text-primary" />
                    </div>
                    <div>
                      <h3 className="font-bold text-white text-lg">{cat.name}</h3>
                      {cat.description && (
                        <p className="text-slate-400 text-xs">{cat.description}</p>
                      )}
                    </div>
                    {sel?.productIds && sel.productIds.length > 0 ? (
                      <Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30">
                        <Check className="w-3 h-3 mr-1" /> {sel.productIds.length} Ausgewählt
                      </Badge>
                    ) : sel?.productId ? (
                      <Badge className="ml-auto bg-green-500/20 text-green-400 border border-green-500/30">
                        <Check className="w-3 h-3 mr-1" /> Ausgewählt
                      </Badge>
                    ) : cat.is_required ? (
                      <Badge variant="destructive" className="ml-auto opacity-80">
                        <AlertCircle className="w-3 h-3 mr-1" /> Pflichtfeld
                      </Badge>
                    ) : (
                      <Badge variant="outline" className="ml-auto border-white/20 text-slate-400">
                        Optional
                      </Badge>
                    )}
                  </div>

                  {catProducts.length === 0 ? (
                    <p className="text-slate-500 text-sm italic">
                      Keine Produkte in dieser Kategorie im aktuellen Abrechnungsmodell vorhanden.
                    </p>
                  ) : cat.allow_multiselect ? (
                    <div className="grid gap-3">
                      {catProducts.map(product => {
                        const isChecked = sel?.productIds?.includes(product.id) ?? false
                        const disabled = isProductDisabled(product, cat.id)
                        return (
                          <div key={product.id} className="relative">
                            <Label
                              onClick={() => !disabled && selectProduct(cat.id, product.id)}
                              className={`flex flex-col items-start p-4 rounded-xl border-2 transition-all ${disabled
                                ? 'border-white/5 bg-white/5 opacity-50 cursor-not-allowed'
                                : isChecked
                                  ? 'border-primary bg-primary/5 cursor-pointer'
                                  : 'border-white/5 bg-white/5 hover:bg-white/10 cursor-pointer'
                              }`}
                            >
                              <div className="flex justify-between w-full items-center">
                                <div className="flex items-center gap-3">
                                  <Checkbox
                                    checked={isChecked}
                                    disabled={disabled}
                                    onCheckedChange={() => { }}
                                    className="border-white/20 data-[state=checked]:bg-primary"
                                  />
                                  <span className="font-bold text-base text-white">{product.name}</span>
                                  <span className={`text-[10px] px-1.5 py-0.5 rounded border ${billingBadgeClass(product.billing_interval)}`}>
                                    {product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo/Monat'}
                                  </span>
                                </div>
                                <span className="text-primary font-semibold text-sm">
                                  {new Intl.NumberFormat('de-DE', {
                                    style: 'currency',
                                    currency: 'EUR',
                                  }).format(product.base_price)}{' '}
                                  <span className="text-xs text-slate-400">{billingLabel(product.billing_interval)}</span>
                                </span>
                              </div>
                              {product.description && (
                                <span className="text-sm text-slate-300 mt-1 pl-7">{product.description}</span>
                              )}
                              {product.modules && product.modules.length > 0 && (
                                <span className="text-xs text-slate-500 mt-1 pl-7">
                                  {product.modules.length} optionale Module verfügbar
                                </span>
                              )}
                            </Label>
                          </div>
                        )
                      })}
                    </div>
                  ) : (
                    <RadioGroup
                      value={sel?.productId ?? ''}
                      onValueChange={id => selectProduct(cat.id, id)}
                      className="grid gap-3"
                    >
                      {catProducts.map(product => {
                        const disabled = isProductDisabled(product, cat.id)
                        return (
                          <div key={product.id} className="relative">
                            <RadioGroupItem
                              value={product.id}
                              id={`${cat.id}-${product.id}`}
                              disabled={disabled}
                              className="peer sr-only"
                            />
                            <Label
                              htmlFor={disabled ? undefined : `${cat.id}-${product.id}`}
                              className={`flex flex-col items-start p-4 rounded-xl border-2 border-white/5 bg-white/5 transition-all ${disabled
                                ? 'opacity-50 cursor-not-allowed'
                                : 'hover:bg-white/10 peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer'
                              }`}
                            >
                              <div className="flex justify-between w-full items-center">
                                <div className="flex items-center gap-2">
                                  <span className="font-bold text-base text-white">{product.name}</span>
                                  <span className={`text-[10px] px-1.5 py-0.5 rounded border ${billingBadgeClass(product.billing_interval)}`}>
                                    {product.billing_interval === 'one_time' ? 'Einmalig' : 'Abo/Monat'}
                                  </span>
                                </div>
                                <span className="text-primary font-semibold text-sm">
                                  {new Intl.NumberFormat('de-DE', {
                                    style: 'currency',
                                    currency: 'EUR',
                                  }).format(product.base_price)}{' '}
                                  <span className="text-xs text-slate-400">{billingLabel(product.billing_interval)}</span>
                                </span>
                              </div>
                              {product.description && (
                                <span className="text-sm text-slate-300 mt-1">{product.description}</span>
                              )}
                              {product.modules && product.modules.length > 0 && (
                                <span className="text-xs text-slate-500 mt-1">
                                  {product.modules.length} optionale Module verfügbar
                                </span>
                              )}
                            </Label>
                          </div>
                        )
                      })}
                    </RadioGroup>
                  )}

                  {/* Modules */}
                  {selectedProduct?.modules && selectedProduct.modules.length > 0 && (
                    <div className="mt-4 space-y-3 pl-2 border-l-2 border-primary/30">
                      <p className="text-sm font-semibold text-white ml-2">Zusatzmodule:</p>
                      {selectedProduct.modules.map(module => {
                        const disabled = isModuleDisabled(module, sel?.moduleIds ?? [])
                        const checked = sel?.moduleIds.includes(module.id) ?? false
                        return (
                          <div
                            key={module.id}
                            className={`flex flex-col p-3 rounded-lg border border-white/5 bg-white/5 ml-2 transition-colors ${disabled ? 'opacity-50' : 'hover:bg-white/10'}`}
                          >
                            <div className="flex items-start space-x-3">
                              <Checkbox
                                id={`mod-${cat.id}-${module.id}`}
                                checked={checked}
                                onCheckedChange={() => toggleModule(cat.id, module.id)}
                                disabled={disabled}
                              />
                              <div className="flex-1">
                                <Label
                                  htmlFor={`mod-${cat.id}-${module.id}`}
                                  className={`font-medium cursor-pointer flex justify-between text-white ${disabled ? 'cursor-not-allowed' : ''}`}
                                >
                                  <span>{module.name}</span>
                                  <span className="text-primary font-bold">
                                    +{new Intl.NumberFormat('de-DE', {
                                      style: 'currency',
                                      currency: 'EUR',
                                    }).format(module.price)}
                                  </span>
                                </Label>
                                {module.description && (
                                  <p className="text-xs text-slate-400">{module.description}</p>
                                )}
                                {disabled && (
                                  <p className="text-[10px] text-destructive mt-1">
                                    {module.requirements?.length && !module.requirements.some(
                                      reqId => sel?.moduleIds.includes(reqId)
                                    )
                                      ? 'Benötigt weitere Module'
                                      : 'Nicht kombinierbar mit aktueller Auswahl'}
                                  </p>
                                )}
                              </div>
                            </div>

                            {/* Scalable Quantity */}
                            {checked && module.has_quantity && (
                              <div className="flex items-center gap-3 mt-3 pl-8 pt-2 border-t border-white/5">
                                <Label htmlFor={`qty-${module.id}`} className="text-xs text-slate-400">Menge:</Label>
                                <Input
                                  id={`qty-${module.id}`}
                                  type="number"
                                  min={1}
                                  max={999}
                                  value={moduleQuantities[module.id] || 1}
                                  onChange={(e) => {
                                    const val = Math.max(1, parseInt(e.target.value) || 1)
                                    setModuleQuantities(prev => ({ ...prev, [module.id]: val }))
                                  }}
                                  className="w-20 h-8 bg-white/5 border-white/10 text-white text-xs text-center rounded-lg"
                                />
                                <span className="text-xs text-slate-500">
                                  Gesamt: {new Intl.NumberFormat('de-DE', {
                                    style: 'currency',
                                    currency: 'EUR',
                                  }).format(module.price * (moduleQuantities[module.id] || 1))}
                                </span>
                              </div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  )}
                </div>
              )
            })}
      </CardContent>
    </Card>
  )
}
