"use client";

import * as React from "react";
import { Clock } from "lucide-react";
import { cn } from "./utils";
import { Button } from "./button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "./popover";
import { ScrollArea } from "./scroll-area";

interface TimePickerProps {
  /** "HH:mm" 또는 showSeconds 시 "HH:mm:ss" 형식 */
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  /** 분 단위 간격 (기본값: 5) */
  minuteStep?: number;
  /** 초 선택 표시 여부 (기본값: false) */
  showSeconds?: boolean;
  /** 초 단위 간격 (기본값: 5) */
  secondStep?: number;
}

function TimePicker({
  value,
  onChange,
  placeholder = "시간 선택",
  disabled = false,
  className,
  minuteStep = 5,
  showSeconds = false,
  secondStep = 5,
}: TimePickerProps) {
  const [open, setOpen] = React.useState(false);

  // 현재 선택된 시/분/초 파싱
  const [selectedHour, selectedMinute, selectedSecond] = React.useMemo(() => {
    if (!value) return [null, null, null];
    const parts = value.split(":").map(Number);
    return [parts[0] ?? null, parts[1] ?? null, parts[2] ?? null];
  }, [value]);

  // 시간 배열 생성 (0-23)
  const hours = Array.from({ length: 24 }, (_, i) => i);

  // 분 배열 생성 (minuteStep 간격)
  const minutes = Array.from(
    { length: Math.ceil(60 / minuteStep) },
    (_, i) => i * minuteStep
  );

  // 초 배열 생성 (secondStep 간격)
  const seconds = React.useMemo(
    () => Array.from({ length: Math.ceil(60 / secondStep) }, (_, i) => i * secondStep),
    [secondStep]
  );

  // 시간 문자열 빌더
  const buildTimeValue = React.useCallback(
    (h: number, m: number, s?: number) => {
      const base = `${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}`;
      if (showSeconds) return `${base}:${(s ?? 0).toString().padStart(2, "0")}`;
      return base;
    },
    [showSeconds]
  );

  // 시간 선택 핸들러
  const handleHourSelect = (hour: number) => {
    onChange?.(buildTimeValue(hour, selectedMinute ?? 0, selectedSecond ?? 0));
  };

  // 분 선택 핸들러
  const handleMinuteSelect = (minute: number) => {
    onChange?.(buildTimeValue(selectedHour ?? 0, minute, selectedSecond ?? 0));
  };

  // 초 선택 핸들러
  const handleSecondSelect = (second: number) => {
    onChange?.(buildTimeValue(selectedHour ?? 0, selectedMinute ?? 0, second));
  };

  // 표시할 시간 텍스트
  const displayValue = value || placeholder;

  // 스크롤 영역 ref
  const hourScrollRef = React.useRef<HTMLDivElement>(null);
  const minuteScrollRef = React.useRef<HTMLDivElement>(null);
  const secondScrollRef = React.useRef<HTMLDivElement>(null);

  // 팝오버 열릴 때 선택된 시간으로 스크롤
  React.useEffect(() => {
    if (open) {
      setTimeout(() => {
        if (selectedHour !== null && hourScrollRef.current) {
          const hourElement = hourScrollRef.current.querySelector(
            `[data-hour="${selectedHour}"]`
          );
          hourElement?.scrollIntoView({ block: "center" });
        }
        if (selectedMinute !== null && minuteScrollRef.current) {
          const minuteElement = minuteScrollRef.current.querySelector(
            `[data-minute="${selectedMinute}"]`
          );
          minuteElement?.scrollIntoView({ block: "center" });
        }
        if (showSeconds && selectedSecond !== null && secondScrollRef.current) {
          const secondElement = secondScrollRef.current.querySelector(
            `[data-second="${selectedSecond}"]`
          );
          secondElement?.scrollIntoView({ block: "center" });
        }
      }, 0);
    }
  }, [open, selectedHour, selectedMinute, selectedSecond, showSeconds]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          disabled={disabled}
          className={cn(
            "w-full justify-start text-left font-normal",
            !value && "text-muted-foreground",
            className
          )}
        >
          <Clock className="mr-2 h-4 w-4" />
          {displayValue}
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="w-auto p-0"
        align="start"
        onPointerDownOutside={(e) => {
          e.preventDefault();
          setOpen(false);
        }}
        onInteractOutside={(e) => {
          e.preventDefault();
          setOpen(false);
        }}
      >
        <div className="p-3">
          {/* 헤더 */}
          <div className="text-center mb-3">
            <span className="text-lg font-bold">시간 선택</span>
          </div>

          {/* 시간/분 선택 영역 */}
          <div className="flex gap-2">
            {/* 시간 선택 */}
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
                시
              </span>
              <ScrollArea className="h-[200px] w-[70px] rounded-md border">
                <div className="p-1" ref={hourScrollRef}>
                  {hours.map((hour) => (
                    <button
                      key={hour}
                      data-hour={hour}
                      onClick={() => handleHourSelect(hour)}
                      className={cn(
                        "w-full px-3 py-2 text-sm rounded-md transition-colors",
                        "hover:bg-primary/10",
                        selectedHour === hour
                          ? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
                          : "text-foreground"
                      )}
                    >
                      {hour.toString().padStart(2, "0")}
                    </button>
                  ))}
                </div>
              </ScrollArea>
            </div>

            {/* 구분자 */}
            <div className="flex items-center justify-center pt-5">
              <span className="text-2xl font-bold text-muted-foreground">:</span>
            </div>

            {/* 분 선택 */}
            <div className="flex flex-col">
              <span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
                분
              </span>
              <ScrollArea className="h-[200px] w-[70px] rounded-md border">
                <div className="p-1" ref={minuteScrollRef}>
                  {minutes.map((minute) => (
                    <button
                      key={minute}
                      data-minute={minute}
                      onClick={() => handleMinuteSelect(minute)}
                      className={cn(
                        "w-full px-3 py-2 text-sm rounded-md transition-colors",
                        "hover:bg-primary/10",
                        selectedMinute === minute
                          ? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
                          : "text-foreground"
                      )}
                    >
                      {minute.toString().padStart(2, "0")}
                    </button>
                  ))}
                </div>
              </ScrollArea>
            </div>

            {/* 초 선택 (showSeconds일 때만) */}
            {showSeconds && (
              <>
                <div className="flex items-center justify-center pt-5">
                  <span className="text-2xl font-bold text-muted-foreground">:</span>
                </div>
                <div className="flex flex-col">
                  <span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
                    초
                  </span>
                  <ScrollArea className="h-[200px] w-[70px] rounded-md border">
                    <div className="p-1" ref={secondScrollRef}>
                      {seconds.map((second) => (
                        <button
                          key={second}
                          data-second={second}
                          onClick={() => handleSecondSelect(second)}
                          className={cn(
                            "w-full px-3 py-2 text-sm rounded-md transition-colors",
                            "hover:bg-primary/10",
                            selectedSecond === second
                              ? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
                              : "text-foreground"
                          )}
                        >
                          {second.toString().padStart(2, "0")}
                        </button>
                      ))}
                    </div>
                  </ScrollArea>
                </div>
              </>
            )}
          </div>

          {/* 현재 선택된 시간 표시 */}
          {value && (
            <div className="mt-3 pt-3 border-t text-center">
              <span className="text-sm text-muted-foreground">선택: </span>
              <span className="text-sm font-semibold">{value}</span>
            </div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}

export { TimePicker };
export type { TimePickerProps };
