'use client'

import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Plus, Trash2, Save, Star, Loader2 } from 'lucide-react'
import { frictionPer100m as calcFrictionPer100m } from '@/lib/hose-calc'

interface HoseType {
  id: string
  name: string
  diameterMm: number
  lengthPerPieceM: number
  flowRateLpm: number
  frictionCoeff: number
  description: string | null
  isDefault: boolean
  isActive: boolean
  sortOrder: number
}

interface HoseSettingsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function HoseSettingsDialog({ open, onOpenChange }: HoseSettingsDialogProps) {
  const [hoseTypes, setHoseTypes] = useState<HoseType[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [showNewForm, setShowNewForm] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    diameterMm: '',
    lengthPerPieceM: '10',
    flowRateLpm: '',
    frictionCoeff: '',
    description: '',
    isDefault: false,
  })

  const fetchHoseTypes = useCallback(async () => {
    setIsLoading(true)
    try {
      const res = await fetch('/api/hose-types')
      if (res.ok) {
        const data = await res.json()
        setHoseTypes(data.hoseTypes || [])
      }
    } catch (err) {
      console.error('Failed to load hose types:', err)
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    if (open) fetchHoseTypes()
  }, [open, fetchHoseTypes])

  const resetForm = () => {
    setFormData({ name: '', diameterMm: '', lengthPerPieceM: '10', flowRateLpm: '', frictionCoeff: '', description: '', isDefault: false })
    setEditingId(null)
    setShowNewForm(false)
  }

  const startEdit = (ht: HoseType) => {
    setFormData({
      name: ht.name,
      diameterMm: String(ht.diameterMm),
      lengthPerPieceM: String(ht.lengthPerPieceM),
      flowRateLpm: String(ht.flowRateLpm),
      frictionCoeff: String(ht.frictionCoeff),
      description: ht.description || '',
      isDefault: ht.isDefault,
    })
    setEditingId(ht.id)
    setShowNewForm(false)
  }

  const handleSave = async () => {
    if (!formData.name || !formData.diameterMm || !formData.flowRateLpm || !formData.frictionCoeff) return
    setIsSaving(true)
    try {
      const url = editingId ? `/api/hose-types/${editingId}` : '/api/hose-types'
      const method = editingId ? 'PUT' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      })
      if (res.ok) {
        await fetchHoseTypes()
        resetForm()
      }
    } catch (err) {
      console.error('Save failed:', err)
    } finally {
      setIsSaving(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Schlauchtyp wirklich löschen?')) return
    try {
      await fetch(`/api/hose-types/${id}`, { method: 'DELETE' })
      await fetchHoseTypes()
      if (editingId === id) resetForm()
    } catch (err) {
      console.error('Delete failed:', err)
    }
  }

  const handleSetDefault = async (id: string) => {
    try {
      await fetch(`/api/hose-types/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isDefault: true }),
      })
      await fetchHoseTypes()
    } catch (err) {
      console.error('Set default failed:', err)
    }
  }

  // Nutzt die zentrale Formel aus lib/hose-calc — keine Duplikation mehr
  const frictionPer100m = (coeff: string, flow: string) => {
    const c = parseFloat(coeff)
    const q = parseFloat(flow)
    if (!c || !q) return '-'
    return calcFrictionPer100m({ frictionCoeff: c, flowRateLpm: q }).toFixed(2)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-lg">
            🚒 Schlauchtypen verwalten
          </DialogTitle>
        </DialogHeader>

        <div className="text-sm text-muted-foreground mb-2">
          Konfiguriere die Schlauchtypen für die Druckberechnung im Messwerkzeug. Der Standard-Schlauch wird automatisch für neue Berechnungen verwendet.
        </div>

        <ScrollArea className="flex-1 max-h-[50vh]">
          {isLoading ? (
            <div className="flex items-center justify-center py-8 gap-2 text-muted-foreground">
              <Loader2 className="w-4 h-4 animate-spin" /> Laden...
            </div>
          ) : hoseTypes.length === 0 ? (
            <div className="text-center text-muted-foreground py-8 text-sm">
              Keine Schlauchtypen vorhanden. Erstelle den ersten!
            </div>
          ) : (
            <div className="space-y-2">
              {hoseTypes.map((ht) => (
                <div
                  key={ht.id}
                  className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                    editingId === ht.id ? 'border-primary bg-primary/5' : 'hover:bg-accent'
                  }`}
                  onClick={() => startEdit(ht)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="font-semibold text-sm">{ht.name}</span>
                      {ht.isDefault && (
                        <span className="text-xs bg-primary/20 text-primary px-2 py-0.5 rounded-full font-medium">Standard</span>
                      )}
                    </div>
                    <div className="flex items-center gap-1">
                      {!ht.isDefault && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          onClick={(e) => { e.stopPropagation(); handleSetDefault(ht.id) }}
                          title="Als Standard setzen"
                        >
                          <Star className="w-4 h-4" />
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-destructive hover:text-destructive"
                        onClick={(e) => { e.stopPropagation(); handleDelete(ht.id) }}
                        title="Löschen"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                  <div className="grid grid-cols-4 gap-2 mt-2 text-xs text-muted-foreground">
                    <div><span className="font-medium">⌀</span> {ht.diameterMm}mm</div>
                    <div><span className="font-medium">L</span> {ht.lengthPerPieceM}m/Stk</div>
                    <div><span className="font-medium">Q</span> {ht.flowRateLpm} l/min</div>
                    <div><span className="font-medium">R</span> {frictionPer100m(String(ht.frictionCoeff), String(ht.flowRateLpm))} bar/100m</div>
                  </div>
                  {ht.description && (
                    <p className="text-xs text-muted-foreground mt-1">{ht.description}</p>
                  )}
                </div>
              ))}
            </div>
          )}
        </ScrollArea>

        {/* Edit/Create Form */}
        {(editingId || showNewForm) && (
          <div className="border-t pt-3 mt-2">
            <h4 className="text-sm font-semibold mb-2">{editingId ? 'Bearbeiten' : 'Neuer Schlauchtyp'}</h4>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <label className="text-xs text-muted-foreground">Name</label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="z.B. 55mm Transportleitung"
                  className="h-9 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">Durchmesser (mm)</label>
                <Input
                  type="number"
                  value={formData.diameterMm}
                  onChange={(e) => setFormData({ ...formData, diameterMm: e.target.value })}
                  placeholder="55"
                  className="h-9 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">Schlauchlänge pro Stück (m)</label>
                <Input
                  type="number"
                  value={formData.lengthPerPieceM}
                  onChange={(e) => setFormData({ ...formData, lengthPerPieceM: e.target.value })}
                  placeholder="10"
                  className="h-9 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">Durchfluss (l/min)</label>
                <Input
                  type="number"
                  value={formData.flowRateLpm}
                  onChange={(e) => setFormData({ ...formData, flowRateLpm: e.target.value })}
                  placeholder="500"
                  className="h-9 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">Reibungskoeffizient (c)</label>
                <Input
                  type="number"
                  step="0.001"
                  value={formData.frictionCoeff}
                  onChange={(e) => setFormData({ ...formData, frictionCoeff: e.target.value })}
                  placeholder="0.034"
                  className="h-9 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">
                  Reibung/100m: <strong>{frictionPer100m(formData.frictionCoeff, formData.flowRateLpm)} bar</strong>
                </label>
                <Input
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="Beschreibung (optional)"
                  className="h-9 text-sm"
                />
              </div>
            </div>
            <div className="flex items-center gap-2 mt-3">
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.isDefault}
                  onChange={(e) => setFormData({ ...formData, isDefault: e.target.checked })}
                  className="w-4 h-4"
                />
                Als Standard setzen
              </label>
              <div className="flex-1" />
              <Button variant="outline" size="sm" onClick={resetForm}>Abbrechen</Button>
              <Button size="sm" onClick={handleSave} disabled={isSaving}>
                <Save className="w-4 h-4 mr-1" />
                {isSaving ? 'Speichern...' : 'Speichern'}
              </Button>
            </div>
          </div>
        )}

        {/* Add button */}
        {!showNewForm && !editingId && (
          <Button
            variant="outline"
            className="w-full mt-2"
            onClick={() => { resetForm(); setShowNewForm(true) }}
          >
            <Plus className="w-4 h-4 mr-2" /> Neuen Schlauchtyp hinzufügen
          </Button>
        )}
      </DialogContent>
    </Dialog>
  )
}
