// admin-spa/src/components/filters/DateRange.tsx
import React, { useEffect, useMemo, useState } from "react";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { __ } from "@/lib/i18n";

type Props = {
  value?: { date_start?: string; date_end?: string };
  onChange?: (next: { date_start?: string; date_end?: string; preset?: string }) => void;
};

function fmt(d: Date): string {
  return d.toISOString().slice(0, 10); // YYYY-MM-DD
}

export default function DateRange({ value, onChange }: Props) {
  const [preset, setPreset] = useState<string>(() => "last30");
  const [start, setStart] = useState<string | undefined>(value?.date_start);
  const [end, setEnd] = useState<string | undefined>(value?.date_end);

  const presets = useMemo(() => {
    const today = new Date();
    const todayStr = fmt(today);
    const last7 = new Date(); last7.setDate(today.getDate() - 6);
    const last30 = new Date(); last30.setDate(today.getDate() - 29);
    return {
      today: { date_start: todayStr, date_end: todayStr },
      last7: { date_start: fmt(last7), date_end: todayStr },
      last30: { date_start: fmt(last30), date_end: todayStr },
      custom: { date_start: start, date_end: end },
    };
  }, [start, end]);

  useEffect(() => {
    if (preset === "custom") {
      onChange?.({ date_start: start, date_end: end, preset });
    } else {
      const pr = (presets as any)[preset] || presets.last30;
      onChange?.({ ...pr, preset });
      setStart(pr.date_start);
      setEnd(pr.date_end);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [preset, start, end]);

  return (
    <div className="flex flex-col lg:flex-row gap-2 w-full">
      <Select value={preset} onValueChange={(v) => setPreset(v)}>
        <SelectTrigger className="w-full">
          <SelectValue placeholder={__("Last 30 days")} />
        </SelectTrigger>
        <SelectContent position="popper" className="z-[1000]">
          <SelectGroup>
            <SelectItem value="today">{__("Today")}</SelectItem>
            <SelectItem value="last7">{__("Last 7 days")}</SelectItem>
            <SelectItem value="last30">{__("Last 30 days")}</SelectItem>
            <SelectItem value="custom">{__("Custom…")}</SelectItem>
          </SelectGroup>
        </SelectContent>
      </Select>

      {preset === "custom" && (
        <div className="flex flex-col lg:flex-row gap-2 w-full">
          <input
            type="date"
            className="w-full border !bg-transparent !border-input !rounded-md !shadow-sm px-3 py-2 text-sm bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:cursor-pointer"
            style={{ WebkitAppearance: 'none', MozAppearance: 'textfield' } as any}
            value={start || ""}
            onChange={(e) => setStart(e.target.value || undefined)}
            placeholder={__("Start date")}
          />
          <input
            type="date"
            className="w-full border !bg-transparent !border-input !rounded-md !shadow-sm px-3 py-2 text-sm bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:cursor-pointer"
            style={{ WebkitAppearance: 'none', MozAppearance: 'textfield' } as any}
            value={end || ""}
            onChange={(e) => setEnd(e.target.value || undefined)}
            placeholder={__("End date")}
          />
        </div>
      )}
    </div>
  );
}