"use client";

import React from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Separator } from "@/components/ui/separator";
import { Plus, Trash2 } from "lucide-react";
import { WebType } from "@/types/screen";

interface WebTypeConfigPanelProps {
  webType: WebType | string;
  config: any;
  onUpdateConfig: (config: any) => void;
}

/**
 * 웹타입별 특화 설정 패널
 */
export const WebTypeConfigPanel: React.FC<WebTypeConfigPanelProps> = ({ webType, config, onUpdateConfig }) => {
  // webType을 소문자로 변환하고 기본 타입 추출
  const normalizedWebType = String(webType || "").toLowerCase();

  // 기본 타입 추출 (예: "radio-horizontal" -> "radio", "checkbox-basic" -> "checkbox")
  const getBaseType = (type: string): string => {
    if (type.startsWith("radio")) return "radio";
    if (type.startsWith("checkbox")) return "checkbox";
    if (type.startsWith("select")) return "select";
    if (type.startsWith("number")) return "number";
    if (type.startsWith("text")) return "text";
    if (type.startsWith("date")) return "date";
    if (type.startsWith("file")) return "file";
    if (type.startsWith("image")) return "image";
    return type;
  };

  const baseType = getBaseType(normalizedWebType);

  console.log("🎨 WebTypeConfigPanel:", { webType, normalizedWebType, baseType });

  // 선택형 입력 (select, radio, checkbox) - 옵션 관리
  if (baseType === "select" || baseType === "radio" || baseType === "checkbox") {
    const options = config?.options || [];
    const multiple = config?.multiple || false;
    const searchable = config?.searchable || false;

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <Label className="text-sm font-medium">옵션 관리</Label>
          <Button
            size="sm"
            variant="outline"
            onClick={() => {
              const newOptions = [
                ...options,
                { label: `옵션 ${options.length + 1}`, value: `option${options.length + 1}` },
              ];
              onUpdateConfig({ ...config, options: newOptions });
            }}
          >
            <Plus className="mr-1 h-3 w-3" />
            옵션 추가
          </Button>
        </div>

        {/* 옵션 리스트 */}
        <div className="space-y-2">
          {options.map((option: any, index: number) => (
            <div key={index} className="flex items-center gap-2">
              <Input
                placeholder="라벨"
                value={option.label || ""}
                onChange={(e) => {
                  const newOptions = [...options];
                  newOptions[index] = { ...option, label: e.target.value };
                  onUpdateConfig({ ...config, options: newOptions });
                }}
                className="flex-1"
              />
              <Input
                placeholder="값"
                value={option.value || ""}
                onChange={(e) => {
                  const newOptions = [...options];
                  newOptions[index] = { ...option, value: e.target.value };
                  onUpdateConfig({ ...config, options: newOptions });
                }}
                className="flex-1"
              />
              <Button
                size="sm"
                variant="ghost"
                onClick={() => {
                  const newOptions = options.filter((_: any, i: number) => i !== index);
                  onUpdateConfig({ ...config, options: newOptions });
                }}
              >
                <Trash2 className="h-4 w-4 text-destructive" />
              </Button>
            </div>
          ))}
        </div>

        {/* Select 전용 설정 */}
        {baseType === "select" && (
          <>
            <Separator />
            <div className="flex items-center justify-between">
              <Label htmlFor="multiple" className="text-xs">
                다중 선택
              </Label>
              <Checkbox
                id="multiple"
                checked={multiple}
                onCheckedChange={(checked) => {
                  onUpdateConfig({ ...config, multiple: checked });
                }}
              />
            </div>
            <div className="flex items-center justify-between">
              <Label htmlFor="searchable" className="text-xs">
                검색 가능
              </Label>
              <Checkbox
                id="searchable"
                checked={searchable}
                onCheckedChange={(checked) => {
                  onUpdateConfig({ ...config, searchable: checked });
                }}
              />
            </div>
          </>
        )}
      </div>
    );
  }

  // 숫자 입력 (number, decimal) - 범위 설정
  if (baseType === "number" || baseType === "decimal") {
    const min = config?.min;
    const max = config?.max;
    const step = config?.step || (baseType === "decimal" ? 0.1 : 1);

    return (
      <div className="space-y-4">
        <Label className="text-sm font-medium">숫자 범위 설정</Label>

        <div className="grid grid-cols-2 gap-2">
          <div>
            <Label htmlFor="min" className="text-xs text-muted-foreground">
              최소값
            </Label>
            <Input
              id="min"
              type="number"
              placeholder="최소값"
              value={min ?? ""}
              onChange={(e) => {
                onUpdateConfig({
                  ...config,
                  min: e.target.value ? Number(e.target.value) : undefined,
                });
              }}
            />
          </div>
          <div>
            <Label htmlFor="max" className="text-xs text-muted-foreground">
              최대값
            </Label>
            <Input
              id="max"
              type="number"
              placeholder="최대값"
              value={max ?? ""}
              onChange={(e) => {
                onUpdateConfig({
                  ...config,
                  max: e.target.value ? Number(e.target.value) : undefined,
                });
              }}
            />
          </div>
        </div>

        <div>
          <Label htmlFor="step" className="text-xs text-muted-foreground">
            증감 단위
          </Label>
          <Input
            id="step"
            type="number"
            step={webType === "decimal" ? 0.01 : 1}
            placeholder="증감 단위"
            value={step}
            onChange={(e) => {
              onUpdateConfig({
                ...config,
                step: e.target.value ? Number(e.target.value) : undefined,
              });
            }}
          />
        </div>
      </div>
    );
  }

  // 날짜/시간 입력 - 형식 설정
  if (baseType === "date" || baseType === "datetime" || baseType === "time") {
    const format =
      config?.format || (baseType === "date" ? "YYYY-MM-DD" : baseType === "datetime" ? "YYYY-MM-DD HH:mm" : "HH:mm");
    const showTime = config?.showTime || false;

    return (
      <div className="space-y-4">
        <Label className="text-sm font-medium">날짜/시간 형식 설정</Label>

        <div>
          <Label htmlFor="format" className="text-xs text-muted-foreground">
            표시 형식
          </Label>
          <Select
            value={format}
            onValueChange={(value) => {
              onUpdateConfig({ ...config, format: value });
            }}
          >
            <SelectTrigger id="format">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {baseType === "date" && (
                <>
                  <SelectItem value="YYYY-MM-DD">YYYY-MM-DD (2024-01-15)</SelectItem>
                  <SelectItem value="YYYY/MM/DD">YYYY/MM/DD (2024/01/15)</SelectItem>
                  <SelectItem value="YYYY.MM.DD">YYYY.MM.DD (2024.01.15)</SelectItem>
                  <SelectItem value="DD-MM-YYYY">DD-MM-YYYY (15-01-2024)</SelectItem>
                </>
              )}
              {baseType === "datetime" && (
                <>
                  <SelectItem value="YYYY-MM-DD HH:mm">YYYY-MM-DD HH:mm</SelectItem>
                  <SelectItem value="YYYY-MM-DD HH:mm:ss">YYYY-MM-DD HH:mm:ss</SelectItem>
                  <SelectItem value="YYYY/MM/DD HH:mm">YYYY/MM/DD HH:mm</SelectItem>
                </>
              )}
              {baseType === "time" && (
                <>
                  <SelectItem value="HH:mm">HH:mm (24시간)</SelectItem>
                  <SelectItem value="HH:mm:ss">HH:mm:ss (24시간)</SelectItem>
                  <SelectItem value="hh:mm A">hh:mm A (12시간)</SelectItem>
                </>
              )}
            </SelectContent>
          </Select>
        </div>

        {baseType === "date" && (
          <div className="flex items-center justify-between">
            <Label htmlFor="showTime" className="text-xs">
              시간 입력 포함
            </Label>
            <Checkbox
              id="showTime"
              checked={showTime}
              onCheckedChange={(checked) => {
                onUpdateConfig({ ...config, showTime: checked });
              }}
            />
          </div>
        )}
      </div>
    );
  }

  // 텍스트 입력 - 검증 규칙
  if (
    baseType === "text" ||
    baseType === "email" ||
    baseType === "tel" ||
    baseType === "url" ||
    baseType === "textarea"
  ) {
    const minLength = config?.minLength;
    const maxLength = config?.maxLength;
    const pattern = config?.pattern;

    return (
      <div className="space-y-4">
        <Label className="text-sm font-medium">텍스트 검증 설정</Label>

        <div className="grid grid-cols-2 gap-2">
          <div>
            <Label htmlFor="minLength" className="text-xs text-muted-foreground">
              최소 길이
            </Label>
            <Input
              id="minLength"
              type="number"
              placeholder="최소 길이"
              value={minLength ?? ""}
              onChange={(e) => {
                onUpdateConfig({
                  ...config,
                  minLength: e.target.value ? Number(e.target.value) : undefined,
                });
              }}
            />
          </div>
          <div>
            <Label htmlFor="maxLength" className="text-xs text-muted-foreground">
              최대 길이
            </Label>
            <Input
              id="maxLength"
              type="number"
              placeholder="최대 길이"
              value={maxLength ?? ""}
              onChange={(e) => {
                onUpdateConfig({
                  ...config,
                  maxLength: e.target.value ? Number(e.target.value) : undefined,
                });
              }}
            />
          </div>
        </div>

        {(webType === "text" || webType === "textarea") && (
          <div>
            <Label htmlFor="pattern" className="text-xs text-muted-foreground">
              정규식 패턴 (선택)
            </Label>
            <Input
              id="pattern"
              placeholder="예: ^[A-Za-z]+$"
              value={pattern ?? ""}
              onChange={(e) => {
                onUpdateConfig({
                  ...config,
                  pattern: e.target.value || undefined,
                });
              }}
            />
            <p className="mt-1 text-xs text-muted-foreground/70">입력값 검증에 사용할 정규식 패턴</p>
          </div>
        )}
      </div>
    );
  }

  // 파일 업로드 - 파일 타입 제한
  if (baseType === "file" || baseType === "image") {
    const accept = config?.accept || (baseType === "image" ? "image/*" : "*/*");
    const maxSize = config?.maxSize || 10;
    const multiple = config?.multiple || false;

    return (
      <div className="space-y-4">
        <Label className="text-sm font-medium">파일 업로드 설정</Label>

        <div>
          <Label htmlFor="accept" className="text-xs text-muted-foreground">
            허용 파일 타입
          </Label>
          <Input
            id="accept"
            placeholder="예: .jpg,.png,.pdf"
            value={accept}
            onChange={(e) => {
              onUpdateConfig({ ...config, accept: e.target.value });
            }}
          />
          <p className="mt-1 text-xs text-muted-foreground/70">쉼표로 구분된 파일 확장자 또는 MIME 타입</p>
        </div>

        <div>
          <Label htmlFor="maxSize" className="text-xs text-muted-foreground">
            최대 파일 크기 (MB)
          </Label>
          <Input
            id="maxSize"
            type="number"
            placeholder="최대 크기"
            value={maxSize}
            onChange={(e) => {
              onUpdateConfig({
                ...config,
                maxSize: e.target.value ? Number(e.target.value) : 10,
              });
            }}
          />
        </div>

        <div className="flex items-center justify-between">
          <Label htmlFor="fileMultiple" className="text-xs">
            다중 파일 선택
          </Label>
          <Checkbox
            id="fileMultiple"
            checked={multiple}
            onCheckedChange={(checked) => {
              onUpdateConfig({ ...config, multiple: checked });
            }}
          />
        </div>
      </div>
    );
  }

  // 기본 메시지 (설정 불필요)
  return (
    <div className="space-y-2 text-sm text-muted-foreground">
      <p>이 웹타입은 추가 설정이 필요하지 않습니다.</p>
    </div>
  );
};
