import { useMemo } from 'react'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import { format } from 'date-fns'
import { de } from 'date-fns/locale'
import './WeatherDashboard.css'
// Build-Informationen (werden beim Build eingef\u00fcgt)
const buildDate = __BUILD_DATE__
const version = __VERSION__
// Deutsche Lokalisierung für Highcharts
Highcharts.setOptions({
  lang: {
    months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
    shortMonths: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
    weekdays: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    resetZoom: 'Zoom zurücksetzen'
  },
  time: {
    useUTC: false
  }
})

const WeatherDashboard = ({ data, rainData = [], timeRange = '24h', onTimeRangeChange }) => {
  // Daten vorbereiten und nach Zeit sortieren (älteste zuerst)
  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => new Date(a.datetime) - new Date(b.datetime))
  }, [data])
  
  // Zeitraum-Label
  const timeRangeLabel = useMemo(() => {
    switch (timeRange) {
      case '24h': return 'Die letzten 24 Stunden'
      case '7d': return 'Die letzten 7 Tage'
      case '30d': return 'Die letzten 30 Tage'
      case '365d': return 'Die letzten 365 Tage'
      default: return 'Die letzten 24 Stunden'
    }
  }, [timeRange])

  // Aggregations-Zusatz für Chart-Titel
  const aggregationSuffix = useMemo(() => {
    switch (timeRange) {
      case '7d':
      case '30d':
        return ' (Stundenmittel)'
      case '365d':
        return ' (Tagesmittel)'
      default:
        return ''
    }
  }, [timeRange])

  // Gemeinsame Chart-Optionen (angepasst an Zeitraum)
  const getCommonOptions = () => {
    // X-Achsen-Konfiguration basierend auf Zeitraum
    let xAxisConfig = {
      type: 'datetime',
      gridLineWidth: 1,
      gridLineColor: 'rgba(0, 0, 0, 0.1)'
    }
    
    // Zeitspanne für X-Achse berechnen (für festen Zeitrahmen)
    const now = new Date().getTime()
    let xAxisMin, xAxisMax
    
    switch (timeRange) {
      case '24h':
        xAxisConfig.tickInterval = 4 * 3600 * 1000 // 4 Stunden
        xAxisConfig.labels = { format: '{value:%H:%M}', align: 'center' }
        xAxisMin = now - 24 * 3600 * 1000
        xAxisMax = now
        break
      case '7d':
        xAxisConfig.labels = { format: '{value:%d.%m}', align: 'center' }
        xAxisMin = now - 7 * 24 * 3600 * 1000
        xAxisMax = now
        break
      case '30d':
        xAxisConfig.labels = { format: '{value:%d.%m}', align: 'center' }
        xAxisMin = now - 30 * 24 * 3600 * 1000
        xAxisMax = now
        break
      case '365d':
        xAxisConfig.labels = { format: '{value:%b %Y}', align: 'center' }
        // Bei 365d: Min/Max aus vorhandenen Daten berechnen
        if (sortedData.length > 0) {
          xAxisMin = new Date(sortedData[0].datetime).getTime()
          xAxisMax = new Date(sortedData[sortedData.length - 1].datetime).getTime()
        } else {
          xAxisMin = null
          xAxisMax = null
        }
        break
    }
    
    // Min/Max für X-Achse setzen
    xAxisConfig.min = xAxisMin
    xAxisConfig.max = xAxisMax
    
    return {
      chart: {
        height: '50%',
        animation: false,
        backgroundColor: 'transparent'
      },
      accessibility: {
        enabled: false
      },
      credits: {
        enabled: false
      },
      title: {
        text: null
      },
      legend: {
        enabled: false
      },
      tooltip: {
        shared: true,
        crosshairs: true,
        xDateFormat: timeRange === '24h' ? '%d.%m.%Y %H:%M' : '%d.%m.%Y'
      },
      plotOptions: {
        series: {
          marker: {
            enabled: false,
            states: {
              hover: {
                enabled: true,
                radius: 5
              }
            }
          }
        }
      },
      xAxis: xAxisConfig,
      yAxis: {
        gridLineColor: 'rgba(0, 0, 0, 0.05)'
      }
    }
  }

  // Temperatur Chart
  const temperatureOptions = useMemo(() => {
    const temps = sortedData.filter(item => item.temperature != null).map(item => item.temperature)
    const min = Math.min(...temps)
    const max = Math.max(...temps)
    const range = max - min

    let yMin = min
    let yMax = max

    if (range < 10) {
      const center = (max + min) / 2
      yMin = center - 5
      yMax = center + 5
    }

    return {
      ...getCommonOptions(),
      yAxis: {
        ...getCommonOptions().yAxis,
        title: { text: 'Temperatur (°C)' },
        min: yMin,
        max: yMax
      },
      series: [{
        name: 'Temperatur',
        data: sortedData.filter(item => item.temperature != null).map(item => [new Date(item.datetime).getTime(), item.temperature]),
        color: 'rgb(255, 99, 132)',
        fillColor: {
          linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
          stops: [
            [0, 'rgba(255, 99, 132, 0.3)'],
            [1, 'rgba(255, 99, 132, 0.1)']
          ]
        },
        type: 'areaspline',
        threshold: null,
        connectNulls: false,
        gapSize: 2 * 24 * 3600 * 1000,
        gapUnit: 'value',
        tooltip: {
          valueSuffix: ' °C'
        }
      }]
    }
  }, [sortedData, aggregationSuffix])

  // Luftfeuchtigkeit Chart
  const humidityOptions = useMemo(() => ({
    ...getCommonOptions(),
    yAxis: {
      ...getCommonOptions().yAxis,
      title: { text: 'Feuchte (%)' },
      min: 40,
      max: 100
    },
    series: [{
      name: 'Feuchte',
      data: sortedData.filter(item => item.humidity != null).map(item => [new Date(item.datetime).getTime(), item.humidity]),
      color: 'rgb(54, 162, 235)',
      fillColor: {
        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
        stops: [
          [0, 'rgba(54, 162, 235, 0.3)'],
          [1, 'rgba(54, 162, 235, 0.1)']
        ]
      },
      type: 'area',
      connectNulls: false,
      gapSize: 2 * 24 * 3600 * 1000,
      gapUnit: 'value',
      tooltip: {
        valueSuffix: ' %'
      }
    }]
  }), [sortedData])

  // Luftdruck Chart
  const pressureOptions = useMemo(() => {
    const pressures = sortedData.filter(item => item.pressure != null).map(item => item.pressure)
    const min = Math.min(...pressures)
    const max = Math.max(...pressures)
    const range = max - min

    let yMin = min
    let yMax = max
    
    if (range < 40) {
      const center = (max + min) / 2
      yMin = center - 20
      yMax = center + 20
    }

    return {
      ...getCommonOptions(),
      yAxis: {
        ...getCommonOptions().yAxis,
        title: { text: 'Luftdruck (hPa)' },
        min: yMin,
        max: yMax
      },
      series: [{
        name: 'Luftdruck',
        data: sortedData.filter(item => item.pressure != null).map(item => [new Date(item.datetime).getTime(), item.pressure]),
        color: 'rgb(75, 192, 192)',
        fillColor: {
          linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
          stops: [
            [0, 'rgba(75, 192, 192, 0.3)'],
            [1, 'rgba(75, 192, 192, 0.1)']
          ]
        },
        type: 'area',
        connectNulls: false,
        gapSize: 2 * 24 * 3600 * 1000,
        gapUnit: 'value',
        tooltip: {
          valueSuffix: ' hPa'
        }
      }]
    }
  }, [sortedData])

  // Regen Chart (angepasst an Zeitraum)
  const rainOptions = useMemo(() => {
    let series = []
    let yAxisTitle = 'Regen (mm) / Rate (mm/h)'
    
    if (timeRange === '24h') {
      // 24h: Area Chart mit Regen und Regenrate
      yAxisTitle = 'Regen (mm) / Rate (mm/h)'
      series = [{
        name: 'Regen',
        data: sortedData.filter(item => item.rain != null).map(item => [new Date(item.datetime).getTime(), item.rain]),
        color: 'rgb(54, 162, 235)',
        fillColor: 'rgba(54, 162, 235, 0.3)',
        type: 'area',
        tooltip: {
          valueSuffix: ' mm'
        }
      }, {
        name: 'Regenrate',
        data: sortedData.filter(item => item.rain_rate != null).map(item => [new Date(item.datetime).getTime(), item.rain_rate]),
        color: 'rgb(59, 130, 246)',
        dashStyle: 'Dash',
        type: 'line',
        tooltip: {
          valueSuffix: ' mm/h'
        }
      }]
    } else if (timeRange === '7d' || timeRange === '30d') {
      // 7d/30d: Balkendiagramm mit täglichen Summen
      yAxisTitle = 'Regen (mm pro Tag)'
      series = [{
        name: 'Regen',
        data: rainData.filter(item => item.total_rain != null && item.total_rain > 0).map(item => [new Date(item.date).getTime(), item.total_rain]),
        color: 'rgb(54, 162, 235)',
        type: 'column',
        tooltip: {
          valueSuffix: ' mm'
        }
      }]
    } else if (timeRange === '365d') {
      // 365d: Balkendiagramm mit wöchentlichen Summen
      yAxisTitle = 'Regen (mm pro Woche)'
      series = [{
        name: 'Regen',
        data: rainData.filter(item => item.total_rain != null && item.total_rain > 0).map(item => [new Date(item.week_start).getTime(), item.total_rain]),
        color: 'rgb(54, 162, 235)',
        type: 'column',
        tooltip: {
          valueSuffix: ' mm'
        }
      }]
    }
    
    return {
      ...getCommonOptions(),
      yAxis: {
        ...getCommonOptions().yAxis,
        title: { text: yAxisTitle }
      },
      series
    }
  }, [sortedData, rainData, timeRange])

  // Windgeschwindigkeit Chart
  const windSpeedOptions = useMemo(() => {
    // Bei 365d nur Windgeschwindigkeit, keine Böen
    const series = timeRange === '365d' 
      ? [{
          name: 'Windgeschwindigkeit',
          data: sortedData
            .filter(item => item.wind_speed != null)
            .map(item => [new Date(item.datetime).getTime(), item.wind_speed]),
          color: 'rgb(153, 102, 255)',
          fillColor: 'rgba(153, 102, 255, 0.1)',
          type: 'area',
          connectNulls: false,
          gapSize: 2 * 24 * 3600 * 1000,
          gapUnit: 'value',
          tooltip: {
            valueSuffix: ' km/h'
          }
        }]
      : [{
          name: 'Windgeschwindigkeit',
          data: sortedData
            .filter(item => item.wind_speed != null)
            .map(item => [new Date(item.datetime).getTime(), item.wind_speed]),
          color: 'rgb(153, 102, 255)',
          fillColor: 'rgba(153, 102, 255, 0.1)',
          type: 'area',
          connectNulls: false,
          gapSize: 2 * 24 * 3600 * 1000,
          gapUnit: 'value',
          tooltip: {
            valueSuffix: ' km/h'
          }
        }, {
          name: 'Windböen',
          data: sortedData
            .filter(item => item.wind_gust != null)
            .map(item => [new Date(item.datetime).getTime(), item.wind_gust]),
          color: 'rgb(255, 159, 64)',
          fillColor: 'rgba(255, 159, 64, 0.1)',
          type: 'area',
          connectNulls: false,
          gapSize: 2 * 24 * 3600 * 1000,
          gapUnit: 'value',
          tooltip: {
            valueSuffix: ' km/h'
          }
        }]
    
    return {
      ...getCommonOptions(),
      plotOptions: {
        series: {
          marker: {
            enabled: false
          },
          lineWidth: 2
        },
        line: {
          step: 'left' // Keine Glättung
        }
      },
      yAxis: {
        ...getCommonOptions().yAxis,
        title: { 
          text: 'Windspeed (km/h)',
          style: {
            whiteSpace: 'nowrap'
          }
        }
      },
      series
    }
  }, [sortedData, timeRange])

  // Windrichtung Chart
  const windDirOptions = useMemo(() => ({
    ...getCommonOptions(),
    plotOptions: {
      scatter: {
        marker: {
          enabled: true,
          radius: 2,
          states: {
            hover: {
              enabled: true,
              radius: 3
            }
          }
        }
      }
    },
    yAxis: {
      ...getCommonOptions().yAxis,
      title: { text: 'Windrichtung' },
      min: 0,
      max: 360,
      tickInterval: 45,
      labels: {
        formatter: function() {
          const directions = {
            0: 'N', 45: 'NO', 90: 'O', 135: 'SO',
            180: 'S', 225: 'SW', 270: 'W', 315: 'NW', 360: 'N'
          }
          return directions[this.value] || ''
        }
      }
    },
    series: [{
      name: 'Windrichtung',
      data: sortedData.filter(item => item.wind_dir != null).map(item => [new Date(item.datetime).getTime(), item.wind_dir]),
      color: 'rgb(54, 162, 235)',
      type: 'scatter',
      tooltip: {
        valueSuffix: ' °'
      }
    }]
  }), [sortedData])

  // Aktuellste Werte für Übersicht
  const current = sortedData[sortedData.length - 1] || {}

  // Berechne Min/Max für den gewählten Zeitraum
  const periodStats = useMemo(() => {
    // Für den gewählten Zeitraum alle Daten verwenden
    const periodData = sortedData

    if (periodData.length === 0) {
      return { 
        minTemp: null, maxTemp: null, minTempTime: null, maxTempTime: null,
        minHumidity: null, maxHumidity: null, minHumidityTime: null, maxHumidityTime: null,
        minPressure: null, maxPressure: null, minPressureTime: null, maxPressureTime: null
      }
    }
    
    // Zeitformat basierend auf Zeitraum
    const timeFormat = timeRange === '24h' ? 'HH:mm' : 'dd.MM HH:mm'

    // Temperatur
    const minTempItem = periodData.reduce((min, item) => 
      item.temperature != null && (min === null || item.temperature < min.temperature) ? item : min, null)
    const maxTempItem = periodData.reduce((max, item) => 
      item.temperature != null && (max === null || item.temperature > max.temperature) ? item : max, null)

    // Luftfeuchtigkeit
    const minHumidityItem = periodData.reduce((min, item) => 
      item.humidity != null && (min === null || item.humidity < min.humidity) ? item : min, null)
    const maxHumidityItem = periodData.reduce((max, item) => 
      item.humidity != null && (max === null || item.humidity > max.humidity) ? item : max, null)

    // Luftdruck
    const minPressureItem = periodData.reduce((min, item) => 
      item.pressure != null && (min === null || item.pressure < min.pressure) ? item : min, null)
    const maxPressureItem = periodData.reduce((max, item) => 
      item.pressure != null && (max === null || item.pressure > max.pressure) ? item : max, null)

    // Windgeschwindigkeit
    const maxWindGustItem = periodData.reduce((max, item) => 
      item.wind_gust != null && (max === null || item.wind_gust > max.wind_gust) ? item : max, null)

    return {
      minTemp: minTempItem?.temperature ?? null,
      maxTemp: maxTempItem?.temperature ?? null,
      minTempTime: minTempItem ? format(new Date(minTempItem.datetime), timeFormat, { locale: de }) : null,
      maxTempTime: maxTempItem ? format(new Date(maxTempItem.datetime), timeFormat, { locale: de }) : null,
      minHumidity: minHumidityItem?.humidity ?? null,
      maxHumidity: maxHumidityItem?.humidity ?? null,
      minHumidityTime: minHumidityItem ? format(new Date(minHumidityItem.datetime), timeFormat, { locale: de }) : null,
      maxHumidityTime: maxHumidityItem ? format(new Date(maxHumidityItem.datetime), timeFormat, { locale: de }) : null,
      minPressure: minPressureItem?.pressure ?? null,
      maxPressure: maxPressureItem?.pressure ?? null,
      minPressureTime: minPressureItem ? format(new Date(minPressureItem.datetime), timeFormat, { locale: de }) : null,
      maxPressureTime: maxPressureItem ? format(new Date(maxPressureItem.datetime), timeFormat, { locale: de }) : null,
      maxWindGust: maxWindGustItem?.wind_gust ?? null,
      maxWindGustTime: maxWindGustItem ? format(new Date(maxWindGustItem.datetime), timeFormat, { locale: de }) : null
    }
  }, [sortedData, timeRange])        

  return (
    <div className="dashboard">
      {/* Navigation für Zeitraum-Auswahl */}
      <div className="time-range-nav">
        <button 
          className={timeRange === '24h' ? 'active' : ''}
          onClick={() => onTimeRangeChange('24h')}
        >
          24 Stunden
        </button>
        <button 
          className={timeRange === '7d' ? 'active' : ''}
          onClick={() => onTimeRangeChange('7d')}
        >
          7 Tage
        </button>
        <button 
          className={timeRange === '30d' ? 'active' : ''}
          onClick={() => onTimeRangeChange('30d')}
        >
          30 Tage
        </button>
        <button 
          className={timeRange === '365d' ? 'active' : ''}
          onClick={() => onTimeRangeChange('365d')}
        >
          365 Tage
        </button>
      </div>
      
      {/* Zeitraum-Beschreibung */}
      <div className="time-range-label">
        {timeRangeLabel}
      </div>
      
      {/* Charts Grid */}
      <div className="charts-grid">
        <div className="chart-container">
          <h3>🌡️ Temperatur{aggregationSuffix} - Aktuell: {current.temperature?.toFixed(1) || '-'}°C</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={temperatureOptions} />
          </div>
          <div className="chart-stats">
            Min: {periodStats.minTemp?.toFixed(1) || '-'}°C ({periodStats.minTempTime || '-'}) | Max: {periodStats.maxTemp?.toFixed(1) || '-'}°C ({periodStats.maxTempTime || '-'})
          </div>
        </div>

        <div className="chart-container">
          <h3>🌐 Luftdruck{aggregationSuffix} - Aktuell: {current.pressure?.toFixed(1) || '-'} hPa</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={pressureOptions} />
          </div>
          <div className="chart-stats">
            Min: {periodStats.minPressure?.toFixed(1) || '-'} hPa ({periodStats.minPressureTime || '-'}) | Max: {periodStats.maxPressure?.toFixed(1) || '-'} hPa ({periodStats.maxPressureTime || '-'})
          </div>
        </div>

        <div className="chart-container">
          <h3>💧 Luftfeuchtigkeit{aggregationSuffix} - Aktuell: {current.humidity || '-'}%</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={humidityOptions} />
          </div>
          <div className="chart-stats">
            Min: {periodStats.minHumidity || '-'}% ({periodStats.minHumidityTime || '-'}) | Max: {periodStats.maxHumidity || '-'}% ({periodStats.maxHumidityTime || '-'})
          </div>
        </div>

        <div className="chart-container">
          <h3>🌧️ Regen{aggregationSuffix} - Aktuell: {current.rain?.toFixed(1) || '-'} mm</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={rainOptions} />
          </div>
        </div>

        <div className="chart-container">
          <h3>🧭 Windrichtung{aggregationSuffix} - Aktuell: {current.wind_dir ?? '-'}°</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={windDirOptions} />
          </div>
        </div>

        <div className="chart-container">
          <h3>💨 Windspeed{aggregationSuffix} - Aktuell: {current.wind_speed?.toFixed(1) || '-'} km/h</h3>
          <div className="chart-wrapper">
            <HighchartsReact highcharts={Highcharts} options={windSpeedOptions} />
          </div>
          <div className="chart-stats">
            Max: {periodStats.maxWindGust?.toFixed(1) || '-'} km/h ({periodStats.maxWindGustTime || '-'})
          </div>
        </div>

      </div>

      {/* Footer */}
      <div className="dashboard-footer">
        <div className="version-line">
          <div><a href="mailto:rxf@gmx.de">
                mailto:rxf@gmx.de
              </a>
          </div>
          <div>
            <span className="version-full">Version</span>
            <span className="version-short">V</span>
            {' '}{version} – {buildDate}
          </div>
        </div>
        <hr />
        <div className="footer-credits">
          <div className="footer-left">Daten-Erfassung mit einer Davis VantagePro.</div>
          <div className="footer-right">Grafiken erzeugt mit HighCharts</div>
        </div>
        <div className="footer-sponsor">
          Die Wetterstation wurde vom Zeitungsverlag Waiblingen <a href="https://www.zvw.de" target="_blank" rel="noopener noreferrer">www.zvw.de</a> gestiftet.
        </div>
      </div>

    </div>
  )
}

export default WeatherDashboard
