"use client";
// components/main/analogInputs/AnalogInputsDatePicker.tsx
import React, { useEffect, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

type Props = {
  from: string;
  to: string;
  onChange: (from: string, to: string) => void;
};

export default function AnalogInputsDatePicker({ from, to, onChange }: Props) {
  const today = new Date();

  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(today.getDate() - 30);

  const sixMonthsAgo = new Date();
  sixMonthsAgo.setMonth(today.getMonth() - 6);

  // interne Date-Objekte für react-datepicker
  const parseISO = (dateStr: string) => {
    if (!dateStr) return null;
    const [year, month, day] = dateStr.split("-").map(Number);
    return new Date(year, month - 1, day);
  };

  const formatISO = (date: Date) => date.toLocaleDateString("sv-SE"); // yyyy-MM-dd

  const [localFromDate, setLocalFromDate] = useState<Date | null>(
    from ? parseISO(from) : thirtyDaysAgo
  );
  const [localToDate, setLocalToDate] = useState<Date | null>(
    to ? parseISO(to) : today
  );

  // Wenn Props von außen kommen (z.B. Reset), synchronisieren
  useEffect(() => {
    if (from) setLocalFromDate(parseISO(from));
    if (to) setLocalToDate(parseISO(to));
  }, [from, to]);

  const handleFromChange = (date: Date | null) => {
    setLocalFromDate(date);
    if (date && localToDate) {
      onChange(formatISO(date), formatISO(localToDate));
    }
  };

  const handleToChange = (date: Date | null) => {
    setLocalToDate(date);
    if (localFromDate && date) {
      onChange(formatISO(localFromDate), formatISO(date));
    }
  };

  return (
    <div className="flex space-x-4 items-center">
      {/* Von */}
      <div className="flex items-center space-x-2">
        <label className="block text-sm font-semibold">Von</label>
        <DatePicker
          selected={localFromDate}
          onChange={handleFromChange}
          selectsStart
          startDate={localFromDate}
          endDate={localToDate}
          minDate={sixMonthsAgo}
          maxDate={today}
          dateFormat="dd.MM.yyyy"
          className="border px-2 py-1 rounded"
        />
      </div>

      {/* Bis */}
      <div className="flex items-center space-x-2">
        <label className="block text-sm font-semibold">Bis</label>
        <DatePicker
          selected={localToDate}
          onChange={handleToChange}
          selectsEnd
          startDate={localFromDate}
          endDate={localToDate}
          minDate={sixMonthsAgo}
          maxDate={today}
          dateFormat="dd.MM.yyyy"
          className="border px-2 py-1 rounded"
        />
      </div>
    </div>
  );
}
