'use client';

import { useMemo, useState } from 'react';
import { CalendarRange, ChevronDown, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';

export function toDatetimeLocalValue(date: Date) {
  const pad = (value: number) => String(value).padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

export function defaultInsightsPeriodLocal(days = 7) {
  const to = new Date();
  const from = new Date();
  from.setDate(from.getDate() - days);
  from.setSeconds(0, 0);
  to.setSeconds(0, 0);
  return {
    from: toDatetimeLocalValue(from),
    to: toDatetimeLocalValue(to)
  };
}

export function localDatetimeToIso(value: string) {
  if (!value.trim()) return undefined;
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return undefined;
  return parsed.toISOString();
}

function pluralDays(value: number) {
  const mod10 = value % 10;
  const mod100 = value % 100;
  if (mod10 === 1 && mod100 !== 11) return 'день';
  if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return 'дня';
  return 'дней';
}

function formatPeriodLabel(from: string, to: string) {
  const format = (value: string) => {
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return value;
    return new Intl.DateTimeFormat('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    }).format(parsed);
  };
  return `${format(from)} — ${format(to)}`;
}

export function AdminInsightsDateFilter({
  from,
  to,
  retentionDays,
  onFromChange,
  onToChange,
  onReset
}: {
  from: string;
  to: string;
  retentionDays: number;
  onFromChange: (value: string) => void;
  onToChange: (value: string) => void;
  onReset: () => void;
}) {
  const [open, setOpen] = useState(false);
  const periodLabel = useMemo(() => formatPeriodLabel(from, to), [from, to]);

  return (
    <div className="rounded-2xl border border-[#eceef4] bg-[#fafbff]">
      <button
        type="button"
        className="flex w-full items-center gap-3 px-3 py-2.5 text-left transition hover:bg-[#f4f5f8]"
        onClick={() => setOpen((current) => !current)}
        aria-expanded={open}
      >
        <CalendarRange className="h-4 w-4 shrink-0 text-[#667085]" />
        <div className="min-w-0 flex-1">
          <p className="text-xs font-medium text-[#667085]">Период просмотра</p>
          <p className="truncate text-sm text-[#1f2430]">{periodLabel}</p>
        </div>
        <ChevronDown className={cn('h-4 w-4 shrink-0 text-[#667085] transition', open && 'rotate-180')} />
      </button>

      {open ? (
        <div className="border-t border-[#eceef4] px-3 pb-3 pt-3">
          <div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]">
            <div className="space-y-1">
              <label className="text-xs text-[#667085]" htmlFor="insights-from">
                С даты и времени
              </label>
              <Input
                id="insights-from"
                type="datetime-local"
                value={from}
                onChange={(event) => onFromChange(event.target.value)}
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs text-[#667085]" htmlFor="insights-to">
                По дату и время
              </label>
              <Input
                id="insights-to"
                type="datetime-local"
                value={to}
                onChange={(event) => onToChange(event.target.value)}
              />
            </div>
            <div className="flex items-end">
              <Button type="button" variant="secondary" className="w-full gap-2 sm:w-auto" onClick={onReset}>
                <RotateCcw className="h-4 w-4" />
                Сбросить
              </Button>
            </div>
          </div>
          <p className="mt-2 text-xs text-[#667085]">
            Журналы хранятся не более {retentionDays} {pluralDays(retentionDays)}. Старые записи удаляются автоматически.
          </p>
        </div>
      ) : null}
    </div>
  );
}
