'use client'

import { useState, useMemo } from 'react'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { X, Ruler, Droplets, TrendingUp, TrendingDown, AlertTriangle, CheckCircle2, ChevronDown, ChevronUp } from 'lucide-react'
import {
  calcHoseLine, DEFAULT_CALC_PARAMS,
  type HoseTypeData, type MeasurementSummary,
} from '@/lib/hose-calc'

interface MeasurePanelProps {
  measurement: MeasurementSummary
  hoseTypes: HoseTypeData[]
  onClose: () => void
}

function formatDistance(m: number): string {
  return m >= 1000 ? `${(m / 1000).toFixed(2)} km` : `${Math.round(m)} m`
}

/**
 * Ergebnis-Panel des Messwerkzeugs: Streckenprofil + Leitungsrechner.
 * Ersetzt das frühere innerHTML-DOM-Overlay durch eine echte React-Komponente.
 */
export function MeasurePanel({ measurement, hoseTypes, onClose }: MeasurePanelProps) {
  const defaultHose = hoseTypes.find(h => h.isDefault) || hoseTypes[0]
  const [selectedHoseName, setSelectedHoseName] = useState<string>(defaultHose?.name || '')
  const [nozzlePressure, setNozzlePressure] = useState<string>(String(DEFAULT_CALC_PARAMS.nozzlePressure))
  const [detailsOpen, setDetailsOpen] = useState(false)

  const selectedHose = hoseTypes.find(h => h.name === selectedHoseName) || defaultHose

  const result = useMemo(() => {
    if (!selectedHose) return null
    return calcHoseLine(
      measurement.totalDistanceM,
      measurement.netDiffM,
      selectedHose,
      { ...DEFAULT_CALC_PARAMS, nozzlePressure: parseFloat(nozzlePressure) || DEFAULT_CALC_PARAMS.nozzlePressure }
    )
  }, [selectedHose, measurement, nozzlePressure])

  const noElevation = measurement.elevationSource === 'none'

  return (
    <div className="absolute bottom-12 left-4 z-[1000] w-[360px] max-w-[calc(100%-2rem)] rounded-xl border-2 border-amber-400 dark:border-amber-600 bg-white dark:bg-zinc-900 text-sm shadow-2xl overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-2.5 bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-800">
        <span className="font-bold flex items-center gap-2 text-amber-900 dark:text-amber-200">
          <Ruler className="w-4 h-4" /> Messergebnis
        </span>
        <button onClick={onClose} className="text-amber-700/60 hover:text-amber-900 dark:text-amber-400/60 dark:hover:text-amber-200 transition-colors" title="Schliessen">
          <X className="w-4 h-4" />
        </button>
      </div>

      <div className="p-4 space-y-3">
        {/* Strecke kompakt */}
        <div className="flex items-baseline justify-between">
          <span className="text-muted-foreground text-xs">Distanz</span>
          <span className="font-bold text-lg tabular-nums">{formatDistance(measurement.totalDistanceM)}</span>
        </div>
        <div className="flex items-center justify-between text-xs">
          <span className="inline-flex items-center gap-1 text-red-600 dark:text-red-400">
            <TrendingUp className="w-3.5 h-3.5" /> +{Math.round(measurement.climbM)} m
          </span>
          <span className="inline-flex items-center gap-1 text-green-600 dark:text-green-400">
            <TrendingDown className="w-3.5 h-3.5" /> −{Math.round(measurement.descentM)} m
          </span>
          <span className={`font-semibold ${measurement.netDiffM > 0 ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'}`}>
            Netto {measurement.netDiffM > 0 ? '+' : ''}{Math.round(measurement.netDiffM)} m
          </span>
        </div>

        {/* Höhen-Details (einklappbar) */}
        <button onClick={() => setDetailsOpen(!detailsOpen)} className="w-full flex items-center justify-between text-xs text-muted-foreground hover:text-foreground transition-colors">
          <span>Höhenprofil-Details</span>
          {detailsOpen ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
        </button>
        {detailsOpen && (
          <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs bg-muted/50 rounded-lg p-2.5">
            <span className="text-muted-foreground">Start</span><span className="font-medium text-right tabular-nums">{Math.round(measurement.elevationStartM)} m ü.M.</span>
            <span className="text-muted-foreground">Ende</span><span className="font-medium text-right tabular-nums">{Math.round(measurement.elevationEndM)} m ü.M.</span>
            <span className="text-muted-foreground">Min / Max</span><span className="font-medium text-right tabular-nums">{Math.round(measurement.minElevationM)} / {Math.round(measurement.maxElevationM)} m</span>
            <span className="text-muted-foreground">Messpunkte</span><span className="font-medium text-right tabular-nums">{measurement.samplePointCount}</span>
          </div>
        )}

        {noElevation && (
          <div className="flex items-start gap-2 text-xs rounded-lg bg-amber-50 dark:bg-amber-950/40 border border-amber-300 dark:border-amber-700 p-2.5 text-amber-800 dark:text-amber-300">
            <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
            <span>Höhendaten nicht verfügbar — Berechnung ohne Höhendifferenz (flach).</span>
          </div>
        )}

        {/* Leitungsrechner */}
        <div className="border-t pt-3 space-y-2.5">
          <div className="font-bold flex items-center gap-2 text-red-700 dark:text-red-400">
            <Droplets className="w-4 h-4" /> Leitungsrechner
          </div>

          <div className="grid grid-cols-[1fr_auto] gap-2">
            <Select value={selectedHoseName} onValueChange={setSelectedHoseName}>
              <SelectTrigger className="h-8 text-xs min-w-0"><SelectValue placeholder="Schlauchtyp" /></SelectTrigger>
              <SelectContent className="z-[2000]">
                {hoseTypes.map(h => (
                  <SelectItem key={h.name} value={h.name}>
                    {h.name}{h.isDefault ? ' ★' : ''} · {h.flowRateLpm} l/min
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={nozzlePressure} onValueChange={setNozzlePressure}>
              <SelectTrigger className="h-8 text-xs w-[92px] shrink-0" title="Druck am Strahlrohr/Verteiler"><SelectValue /></SelectTrigger>
              <SelectContent className="z-[2000]">
                {['4', '5', '6', '8'].map(p => <SelectItem key={p} value={p}>{p} bar</SelectItem>)}
              </SelectContent>
            </Select>
          </div>

          {result && (
            <>
              <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                <span className="text-muted-foreground">Reibungsverlust</span>
                <span className="font-medium text-right tabular-nums">{result.frictionBar.toFixed(1)} bar <span className="text-muted-foreground">({result.frictionPer100mBar.toFixed(2)}/100m)</span></span>
                <span className="text-muted-foreground">Höhendruck</span>
                <span className={`font-medium text-right tabular-nums ${result.elevationBar > 0 ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'}`}>
                  {result.elevationBar > 0 ? '+' : ''}{result.elevationBar.toFixed(1)} bar
                </span>
                <span className="text-muted-foreground">Strahlrohr</span>
                <span className="font-medium text-right tabular-nums">{parseFloat(nozzlePressure).toFixed(1)} bar</span>
                <span className="text-muted-foreground">Schläuche à {result.hose.lengthPerPieceM} m</span>
                <span className="font-medium text-right tabular-nums">{result.hoseCount} Stk. <span className="text-muted-foreground">(inkl. 10% Reserve)</span></span>
              </div>

              {/* Gesamtergebnis */}
              <div className={`rounded-lg p-3 border ${result.needsBooster
                ? 'bg-red-50 dark:bg-red-950/40 border-red-300 dark:border-red-700'
                : 'bg-green-50 dark:bg-green-950/40 border-green-300 dark:border-green-700'}`}>
                <div className="flex items-center justify-between">
                  <span className="text-xs font-medium text-muted-foreground">Pumpendruck benötigt</span>
                  <span className={`font-bold text-lg tabular-nums ${result.needsBooster ? 'text-red-700 dark:text-red-400' : 'text-green-700 dark:text-green-400'}`}>
                    {result.totalBar.toFixed(1)} bar
                  </span>
                </div>
                <div className={`flex items-center gap-1.5 mt-1 text-xs font-semibold ${result.needsBooster ? 'text-red-700 dark:text-red-400' : 'text-green-700 dark:text-green-400'}`}>
                  {result.needsBooster ? (
                    <><AlertTriangle className="w-3.5 h-3.5" /> {result.pumpCount} Pumpen nötig — Verstärker alle ~{Math.round(result.boosterSpacingM || 0)} m</>
                  ) : (
                    <><CheckCircle2 className="w-3.5 h-3.5" /> 1 Pumpe reicht</>
                  )}
                </div>
              </div>
            </>
          )}

          <p className="text-[10px] text-muted-foreground leading-snug">
            Länge inkl. 10% Verlegereserve · Höhendaten: {measurement.elevationSource === 'open-meteo' ? 'Open-Meteo DEM (~90 m Raster)' : measurement.elevationSource === 'open-elevation' ? 'Open-Elevation' : 'keine'} · Richtwerte, ersetzt keine Lagebeurteilung.
          </p>
        </div>
      </div>
    </div>
  )
}
