"use client";

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Slider } from "@/components/ui/slider";
import { CodeTypeConfig } from "@/types/screen";

interface CodeTypeConfigPanelProps {
  config: CodeTypeConfig;
  onConfigChange: (config: CodeTypeConfig) => void;
}

export const CodeTypeConfigPanel: React.FC<CodeTypeConfigPanelProps> = ({ config, onConfigChange }) => {
  // 기본값이 설정된 config 사용
  const safeConfig = {
    language: "javascript",
    theme: "light",
    fontSize: 14,
    lineNumbers: true,
    wordWrap: false,
    readOnly: false,
    autoFormat: true,
    placeholder: "",
    ...config,
  };

  // 로컬 상태로 실시간 입력 관리
  const [localValues, setLocalValues] = useState({
    language: safeConfig.language,
    theme: safeConfig.theme,
    fontSize: safeConfig.fontSize,
    lineNumbers: safeConfig.lineNumbers,
    wordWrap: safeConfig.wordWrap,
    readOnly: safeConfig.readOnly,
    autoFormat: safeConfig.autoFormat,
    placeholder: safeConfig.placeholder,
  });

  // 지원하는 프로그래밍 언어들
  const languages = [
    { value: "javascript", label: "JavaScript" },
    { value: "typescript", label: "TypeScript" },
    { value: "python", label: "Python" },
    { value: "java", label: "Java" },
    { value: "csharp", label: "C#" },
    { value: "cpp", label: "C++" },
    { value: "c", label: "C" },
    { value: "php", label: "PHP" },
    { value: "ruby", label: "Ruby" },
    { value: "go", label: "Go" },
    { value: "rust", label: "Rust" },
    { value: "kotlin", label: "Kotlin" },
    { value: "swift", label: "Swift" },
    { value: "html", label: "HTML" },
    { value: "css", label: "CSS" },
    { value: "scss", label: "SCSS" },
    { value: "json", label: "JSON" },
    { value: "xml", label: "XML" },
    { value: "yaml", label: "YAML" },
    { value: "sql", label: "SQL" },
    { value: "markdown", label: "Markdown" },
    { value: "bash", label: "Bash" },
    { value: "powershell", label: "PowerShell" },
  ];

  // 테마 옵션
  const themes = [
    { value: "light", label: "라이트" },
    { value: "dark", label: "다크" },
    { value: "monokai", label: "Monokai" },
    { value: "github", label: "GitHub" },
    { value: "vs-code", label: "VS Code" },
  ];

  // config가 변경될 때 로컬 상태 동기화
  useEffect(() => {
    setLocalValues({
      language: safeConfig.language,
      theme: safeConfig.theme,
      fontSize: safeConfig.fontSize,
      lineNumbers: safeConfig.lineNumbers,
      wordWrap: safeConfig.wordWrap,
      readOnly: safeConfig.readOnly,
      autoFormat: safeConfig.autoFormat,
      placeholder: safeConfig.placeholder,
    });
  }, [
    safeConfig.language,
    safeConfig.theme,
    safeConfig.fontSize,
    safeConfig.lineNumbers,
    safeConfig.wordWrap,
    safeConfig.readOnly,
    safeConfig.autoFormat,
    safeConfig.placeholder,
  ]);

  const updateConfig = (key: keyof CodeTypeConfig, value: any) => {
    // 로컬 상태 즉시 업데이트
    setLocalValues((prev) => ({ ...prev, [key]: value }));

    // 실제 config 업데이트
    const newConfig = { ...safeConfig, [key]: value };
    // console.log("💻 CodeTypeConfig 업데이트:", {
    // key,
    // value,
    // oldConfig: safeConfig,
    // newConfig,
    // });
    onConfigChange(newConfig);
  };

  return (
    <div className="space-y-4">
      {/* 프로그래밍 언어 */}
      <div>
        <Label htmlFor="language" className="text-sm font-medium">
          프로그래밍 언어
        </Label>
        <Select value={localValues.language} onValueChange={(value) => updateConfig("language", value)}>
          <SelectTrigger className="mt-1 h-6 w-full px-2 py-0 text-xs">
            <SelectValue placeholder="언어 선택" />
          </SelectTrigger>
          <SelectContent className="max-h-60">
            {languages.map((lang) => (
              <SelectItem key={lang.value} value={lang.value}>
                {lang.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 테마 */}
      <div>
        <Label htmlFor="theme" className="text-sm font-medium">
          테마
        </Label>
        <Select value={localValues.theme} onValueChange={(value) => updateConfig("theme", value)}>
          <SelectTrigger className="mt-1 h-6 w-full px-2 py-0 text-xs">
            <SelectValue placeholder="테마 선택" />
          </SelectTrigger>
          <SelectContent>
            {themes.map((theme) => (
              <SelectItem key={theme.value} value={theme.value}>
                {theme.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 폰트 크기 */}
      <div>
        <Label htmlFor="fontSize" className="text-sm font-medium">
          폰트 크기: {localValues.fontSize}px
        </Label>
        <div className="mt-2">
          <Slider
            value={[localValues.fontSize]}
            onValueChange={(value) => updateConfig("fontSize", value[0])}
            min={10}
            max={24}
            step={1}
            className="w-full"
          />
          <div className="mt-1 flex justify-between text-xs text-muted-foreground">
            <span>10px</span>
            <span>24px</span>
          </div>
        </div>
      </div>

      {/* 옵션 - 가로 배치 */}
      <div className="grid grid-cols-2 gap-3">
        {/* 라인 넘버 표시 */}
        <div className="flex items-center justify-between">
          <Label htmlFor="lineNumbers" className="text-sm font-medium">
            라인 넘버 표시
          </Label>
          <Checkbox
            id="lineNumbers"
            checked={localValues.lineNumbers}
            onCheckedChange={(checked) => updateConfig("lineNumbers", !!checked)}
          />
        </div>

        {/* 단어 줄바꿈 */}
        <div className="flex items-center justify-between">
          <Label htmlFor="wordWrap" className="text-sm font-medium">
            단어 자동 줄바꿈
          </Label>
          <Checkbox
            id="wordWrap"
            checked={localValues.wordWrap}
            onCheckedChange={(checked) => updateConfig("wordWrap", !!checked)}
          />
        </div>

        {/* 읽기 전용 */}
        <div className="flex items-center justify-between">
          <Label htmlFor="readOnly" className="text-sm font-medium">
            읽기 전용
          </Label>
          <Checkbox
            id="readOnly"
            checked={localValues.readOnly}
            onCheckedChange={(checked) => updateConfig("readOnly", !!checked)}
          />
        </div>

        {/* 자동 포맷팅 */}
        <div className="flex items-center justify-between">
          <Label htmlFor="autoFormat" className="text-sm font-medium">
            자동 포맷팅
          </Label>
          <Checkbox
            id="autoFormat"
            checked={localValues.autoFormat}
            onCheckedChange={(checked) => updateConfig("autoFormat", !!checked)}
          />
        </div>
      </div>

      {/* 플레이스홀더 */}
      <div>
        <Label htmlFor="placeholder" className="text-sm font-medium">
          플레이스홀더
        </Label>
        <Input
          id="placeholder"
          value={localValues.placeholder}
          onChange={(e) => updateConfig("placeholder", e.target.value)}
          placeholder="코드를 입력하세요..."
          className="mt-1"
        />
      </div>

      {/* 미리보기 */}
      <div className="rounded-md border bg-muted p-3">
        <Label className="text-sm font-medium text-foreground">미리보기</Label>
        <div className="mt-2">
          <div
            className={`rounded border p-3 font-mono ${
              localValues.theme === "dark" ? "bg-foreground text-white" : "bg-white text-black"
            }`}
            style={{ fontSize: `${localValues.fontSize}px` }}
          >
            <div className="flex">
              {localValues.lineNumbers && (
                <div className="mr-3 text-muted-foreground/70">
                  <div>1</div>
                  <div>2</div>
                  <div>3</div>
                </div>
              )}
              <div className={localValues.wordWrap ? "whitespace-pre-wrap" : "whitespace-pre"}>
                {localValues.placeholder || getCodeSample(localValues.language)}
              </div>
            </div>
          </div>
        </div>
        <div className="mt-2 text-xs text-muted-foreground">
          언어: {languages.find((l) => l.value === localValues.language)?.label}, 테마:{" "}
          {themes.find((t) => t.value === localValues.theme)?.label}, 폰트: {localValues.fontSize}px
          {localValues.readOnly && ", 읽기전용"}
        </div>
      </div>

      {/* 안내 메시지 */}
      <div className="bg-accent rounded-md p-3">
        <div className="text-sm font-medium text-primary">코드 에디터 설정</div>
        <div className="mt-1 text-xs text-primary">
          • 문법 강조 표시는 선택된 언어에 따라 적용됩니다
          <br />
          • 자동 포맷팅은 저장 시 또는 단축키로 실행됩니다
          <br />• 실제 코드 에디터는 Monaco Editor 또는 CodeMirror를 사용할 수 있습니다
        </div>
      </div>
    </div>
  );
};

// 언어별 샘플 코드
const getCodeSample = (language: string): string => {
  switch (language) {
    case "javascript":
      return "function hello() {\n  console.log('Hello World!');\n}";
    case "python":
      return "def hello():\n    print('Hello World!')\n";
    case "java":
      return 'public class Hello {\n  public static void main(String[] args) {\n    System.out.println("Hello World!");\n  }\n}';
    case "html":
      return "<div>\n  <h1>Hello World!</h1>\n</div>";
    case "css":
      return ".hello {\n  color: blue;\n  font-size: 16px;\n}";
    case "json":
      return '{\n  "message": "Hello World!",\n  "status": "success"\n}';
    default:
      return "// Hello World!\nconsole.log('Hello World!');";
  }
};

export default CodeTypeConfigPanel;
