"use client";

import { useMemo } from "react";
import DateInput from "@/components/widgets/DateInput/DateInput";
import Typography from "@/components/ui/Typography/Typography";
import PrivacySecurityBanner from "@/components/widgets/PrivacySecurityBanner/PrivacySecurityBanner";
import type { DateScreenDefinition, DefaultTexts } from "@/lib/funnel/types";
import { TemplateLayout } from "../layouts/TemplateLayout";
import { createTemplateLayoutProps } from "@/lib/funnel/templateHelpers";

// Утилита для форматирования даты на основе паттерна
// Принимает год, месяц, день как числа (без зависимости от часовых зон)
function formatDateByPattern(year: number, month: number, day: number, pattern: string): string {
  const monthNames = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];

  return pattern
    .replace("MMMM", monthNames[month - 1])
    .replace("MMM", monthNames[month - 1].substring(0, 3))
    .replace("yyyy", year.toString())
    .replace("dd", day.toString().padStart(2, '0'))
    .replace("d", day.toString());
}

interface DateTemplateProps {
  screen: DateScreenDefinition;
  selectedDate: { month?: string; day?: string; year?: string };
  onDateChange: (date: { month?: string; day?: string; year?: string }) => void;
  onContinue: () => void;
  canGoBack: boolean;
  onBack: () => void;
  screenProgress?: { current: number; total: number };
  defaultTexts?: DefaultTexts;
}

export function DateTemplate({
  screen,
  selectedDate,
  onDateChange,
  onContinue,
  canGoBack,
  onBack,
  screenProgress,
  defaultTexts,
}: DateTemplateProps) {
  const isoDate = useMemo(() => {
    const { month, day, year } = selectedDate;
    if (!month || !day || !year) return null;
    
    const monthNum = parseInt(month);
    const dayNum = parseInt(day);
    const yearNum = parseInt(year);
    
    if (monthNum >= 1 && monthNum <= 12 && dayNum >= 1 && dayNum <= 31 && yearNum > 1900) {
      return `${yearNum}-${monthNum.toString().padStart(2, '0')}-${dayNum.toString().padStart(2, '0')}`;
    }
    
    return null;
  }, [selectedDate]);

  const handleDateChange = (newIsoDate: string | null) => {
    if (!newIsoDate) {
      onDateChange({ month: "", day: "", year: "" });
      return;
    }
    
    const match = newIsoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (!match) {
      onDateChange({ month: "", day: "", year: "" });
      return;
    }
    
    const [, year, month, day] = match;
    onDateChange({
      month: parseInt(month).toString(),
      day: parseInt(day).toString(), 
      year: year
    });
  };

  const isFormValid = Boolean(isoDate);

  // Форматированная дата для отображения
  const formattedDate = useMemo(() => {
    const { month, day, year } = selectedDate;
    if (!month || !day || !year) return null;
    
    const monthNum = parseInt(month);
    const dayNum = parseInt(day);
    const yearNum = parseInt(year);
    
    // Валидация даты
    if (monthNum >= 1 && monthNum <= 12 && dayNum >= 1 && dayNum <= 31 && yearNum > 1900) {
      const pattern = screen.dateInput?.selectedDateFormat || "MMMM d, yyyy";
      return formatDateByPattern(yearNum, monthNum, dayNum, pattern);
    }
    
    return null;
  }, [selectedDate, screen.dateInput?.selectedDateFormat]);

  // Компонент отображения выбранной даты над кнопкой
  const selectedDateDisplay = formattedDate && screen.dateInput?.showSelectedDate !== false ? (
    <div className="text-center space-y-1 mb-4">
      <Typography
        as="p"
        size="sm"
        color="muted"
        align="center"
        className="font-medium"
      >
        {screen.dateInput?.selectedDateLabel || "Выбранная дата:"}
      </Typography>
      <Typography
        as="p"
        size="xl"
        weight="bold"
        color="default"
        align="center"
        className="font-semibold"
      >
        {formattedDate}
      </Typography>
    </div>
  ) : null;

  const layoutProps = createTemplateLayoutProps(
    screen,
    { canGoBack, onBack },
    screenProgress,
    {
      preset: "left",
      actionButton: {
        defaultText: defaultTexts?.nextButton || "Next",
        disabled: !isFormValid,
        onClick: onContinue,
      },
      childrenAboveButton: selectedDateDisplay,
    }
  );

  return (
    <TemplateLayout {...layoutProps}>
      <div className="w-full mt-[22px] space-y-6">
        <DateInput
          value={isoDate}
          onChange={handleDateChange}
          maxYear={new Date().getFullYear() - 11}
          yearsRange={100}
        />

        {defaultTexts?.privacyBanner && (
          <div className="flex justify-center">
            <PrivacySecurityBanner 
              className="mt-5"
              text={{ 
                children: defaultTexts.privacyBanner,
                size: "sm",
                color: "default",
                font: "inter",
                weight: "medium"
              }}
            />
          </div>
        )}
      </div>
    </TemplateLayout>
  );
}
