"use client";

import * as React from "react";
import { cn } from "./utils";
import { DatePicker } from "./date-picker";
import { TimePicker } from "./time-picker";

interface DateTimePickerProps {
  /** "YYYY-MM-DD HH:mm" 또는 "YYYY-MM-DDTHH:mm" 형식 */
  value?: string;
  /** 동일 형식으로 반환 */
  onChange?: (value: string) => void;
  disabled?: boolean;
  className?: string;
  /** DatePicker/TimePicker에 전달 */
  size?: "default" | "sm" | "lg";
  /** TimePicker 분 단위 간격 (기본 5) */
  minuteStep?: number;
  datePlaceholder?: string;
  timePlaceholder?: string;
}

function DateTimePicker({
  value,
  onChange,
  disabled = false,
  className,
  size = "default",
  minuteStep = 5,
  datePlaceholder = "날짜 선택",
  timePlaceholder = "시간 선택",
}: DateTimePickerProps) {
  // 구분자 감지: T 또는 공백
  const separator = React.useMemo(() => {
    if (!value) return "T";
    return value.includes("T") ? "T" : " ";
  }, [value]);

  // value를 date / time 파트로 분리
  const [datePart, timePart] = React.useMemo(() => {
    if (!value) return ["", ""];
    const sep = value.includes("T") ? "T" : " ";
    const parts = value.split(sep);
    return [parts[0] || "", parts[1] || ""];
  }, [value]);

  const handleDateChange = React.useCallback(
    (newDate: string) => {
      const time = timePart || "00:00";
      onChange?.(`${newDate}${separator}${time}`);
    },
    [timePart, separator, onChange]
  );

  const handleTimeChange = React.useCallback(
    (newTime: string) => {
      const date = datePart || new Date().toISOString().slice(0, 10);
      onChange?.(`${date}${separator}${newTime}`);
    },
    [datePart, separator, onChange]
  );

  const sizeClasses = {
    default: "h-10",
    sm: "h-8 text-sm",
    lg: "h-12 text-base",
  };

  return (
    <div className={cn("flex gap-2", className)}>
      <DatePicker
        value={datePart}
        onChange={handleDateChange}
        disabled={disabled}
        size={size}
        placeholder={datePlaceholder}
        className="flex-1 min-w-0"
      />
      <TimePicker
        value={timePart}
        onChange={handleTimeChange}
        disabled={disabled}
        minuteStep={minuteStep}
        placeholder={timePlaceholder}
        className={cn("w-[130px] shrink-0", sizeClasses[size])}
      />
    </div>
  );
}

export { DateTimePicker };
export type { DateTimePickerProps };
