"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Calendar } from "lucide-react";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, DateTypeConfig } from "@/types/screen";

export const DateConfigPanel: React.FC<WebTypeConfigPanelProps> = ({
  component,
  onUpdateComponent,
  onUpdateProperty,
}) => {
  const widget = component as WidgetComponent;
  const config = (widget.webTypeConfig as DateTypeConfig) || {};

  // 로컬 상태
  const [localConfig, setLocalConfig] = useState<DateTypeConfig>({
    format: config.format || "YYYY-MM-DD",
    showTime: config.showTime || false,
    minDate: config.minDate || "",
    maxDate: config.maxDate || "",
    defaultValue: config.defaultValue || "",
    placeholder: config.placeholder || "",
    required: config.required || false,
    readonly: config.readonly || false,
  });

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.webTypeConfig as DateTypeConfig) || {};
    setLocalConfig({
      format: currentConfig.format || "YYYY-MM-DD",
      showTime: currentConfig.showTime || false,
      minDate: currentConfig.minDate || "",
      maxDate: currentConfig.maxDate || "",
      defaultValue: currentConfig.defaultValue || "",
      placeholder: currentConfig.placeholder || "",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
    });
  }, [widget.webTypeConfig]);

  // 설정 업데이트 핸들러
  const updateConfig = (field: keyof DateTypeConfig, value: any) => {
    const newConfig = { ...localConfig, [field]: value };
    setLocalConfig(newConfig);
    onUpdateProperty("webTypeConfig", newConfig);
  };

  // 현재 날짜 설정
  const setCurrentDate = (field: "minDate" | "maxDate" | "defaultValue") => {
    const now = new Date();
    const dateString = localConfig.showTime
      ? now.toISOString().slice(0, 16) // YYYY-MM-DDTHH:mm
      : now.toISOString().slice(0, 10); // YYYY-MM-DD
    updateConfig(field, dateString);
  };

  // 날짜 형식 옵션
  const formatOptions = [
    { value: "YYYY-MM-DD", label: "2024-12-25", description: "ISO 표준 형식" },
    { value: "YYYY-MM-DD HH:mm", label: "2024-12-25 14:30", description: "날짜 + 시간" },
    { value: "YYYY-MM-DD HH:mm:ss", label: "2024-12-25 14:30:45", description: "날짜 + 시간 + 초" },
    { value: "DD/MM/YYYY", label: "25/12/2024", description: "유럽 형식" },
    { value: "MM/DD/YYYY", label: "12/25/2024", description: "미국 형식" },
    { value: "YYYY년 MM월 DD일", label: "2024년 12월 25일", description: "한국 형식" },
  ];

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-sm">
          <Calendar className="h-4 w-4" />
          날짜 설정
        </CardTitle>
        <CardDescription className="text-xs">날짜/시간 입력 필드의 세부 설정을 관리합니다.</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 기본 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">기본 설정</h4>

          <div className="space-y-2">
            <Label htmlFor="placeholder" className="text-xs">
              플레이스홀더
            </Label>
            <Input
              id="placeholder"
              value={localConfig.placeholder || ""}
              onChange={(e) => updateConfig("placeholder", e.target.value)}
              placeholder="날짜를 선택하세요"
              className="text-xs"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="format" className="text-xs">
              날짜 형식
            </Label>
            <Select value={localConfig.format || "YYYY-MM-DD"} onValueChange={(value) => updateConfig("format", value)}>
              <SelectTrigger className="text-xs">
                <SelectValue placeholder="형식 선택" />
              </SelectTrigger>
              <SelectContent>
                {formatOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    <div className="flex flex-col">
                      <span>{option.label}</span>
                      <span className="text-muted-foreground text-xs">{option.description}</span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="showTime" className="text-xs">
                시간 포함
              </Label>
              <p className="text-muted-foreground text-xs">날짜와 함께 시간도 입력받습니다.</p>
            </div>
            <Switch
              id="showTime"
              checked={localConfig.showTime || false}
              onCheckedChange={(checked) => updateConfig("showTime", checked)}
            />
          </div>
        </div>

        {/* 날짜 범위 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">날짜 범위</h4>

          <div className="space-y-2">
            <Label htmlFor="minDate" className="text-xs">
              최소 날짜
            </Label>
            <div className="flex gap-2">
              <Input
                id="minDate"
                type={localConfig.showTime ? "datetime-local" : "date"}
                value={localConfig.minDate || ""}
                onChange={(e) => updateConfig("minDate", e.target.value)}
                className="flex-1 text-xs"
              />
              <Button size="sm" variant="outline" onClick={() => setCurrentDate("minDate")} className="text-xs">
                오늘
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="maxDate" className="text-xs">
              최대 날짜
            </Label>
            <div className="flex gap-2">
              <Input
                id="maxDate"
                type={localConfig.showTime ? "datetime-local" : "date"}
                value={localConfig.maxDate || ""}
                onChange={(e) => updateConfig("maxDate", e.target.value)}
                className="flex-1 text-xs"
              />
              <Button size="sm" variant="outline" onClick={() => setCurrentDate("maxDate")} className="text-xs">
                오늘
              </Button>
            </div>
          </div>
        </div>

        {/* 기본값 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">기본값</h4>

          <div className="space-y-2">
            <Label htmlFor="defaultValue" className="text-xs">
              기본 날짜
            </Label>
            <div className="flex gap-2">
              <Input
                id="defaultValue"
                type={localConfig.showTime ? "datetime-local" : "date"}
                value={localConfig.defaultValue || ""}
                onChange={(e) => updateConfig("defaultValue", e.target.value)}
                className="flex-1 text-xs"
              />
              <Button size="sm" variant="outline" onClick={() => setCurrentDate("defaultValue")} className="text-xs">
                현재
              </Button>
            </div>
            <p className="text-muted-foreground text-xs">입력 필드의 초기값으로 사용됩니다.</p>
          </div>
        </div>

        {/* 상태 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">상태 설정</h4>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="required" className="text-xs">
                필수 입력
              </Label>
              <p className="text-muted-foreground text-xs">날짜가 선택되어야 합니다.</p>
            </div>
            <Switch
              id="required"
              checked={localConfig.required || false}
              onCheckedChange={(checked) => updateConfig("required", checked)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="readonly" className="text-xs">
                읽기 전용
              </Label>
              <p className="text-muted-foreground text-xs">날짜를 수정할 수 없습니다.</p>
            </div>
            <Switch
              id="readonly"
              checked={localConfig.readonly || false}
              onCheckedChange={(checked) => updateConfig("readonly", checked)}
            />
          </div>
        </div>

        {/* 미리보기 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">미리보기</h4>
          <div className="bg-muted/50 rounded-md border p-3">
            <Input
              type={localConfig.showTime ? "datetime-local" : "date"}
              placeholder={localConfig.placeholder || "날짜 선택 미리보기"}
              disabled={localConfig.readonly}
              required={localConfig.required}
              min={localConfig.minDate}
              max={localConfig.maxDate}
              defaultValue={localConfig.defaultValue}
              className="text-xs"
            />
            <div className="text-muted-foreground mt-2 text-xs">
              형식: {localConfig.format}
              {localConfig.showTime && " (시간 포함)"}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

DateConfigPanel.displayName = "DateConfigPanel";


