"use client";

import React, { useState, useEffect } from "react";
import { Card, CardHeader, CardContent } from "../ui/Card";
import { Button } from "../ui/Button";
import { Input } from "../ui/Input";

interface AgentConfig {
  systemMessage: string;
  model: string;
  temperature: number;
  maxTokens: number;
  topP: number;
  frequencyPenalty: number;
  presencePenalty: number;
}

const defaultConfig: AgentConfig = {
  systemMessage: "당신은 친절하고 도움이 되는 AI 어시스턴트입니다.",
  model: "gpt-3.5-turbo",
  temperature: 0.7,
  maxTokens: 1000,
  topP: 1.0,
  frequencyPenalty: 0.0,
  presencePenalty: 0.0,
};

export function ConfigManager() {
  const [config, setConfig] = useState<AgentConfig>(defaultConfig);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  const loadConfig = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/rag/config");
      const data = await response.json();

      if (data.success) {
        setConfig({ ...defaultConfig, ...data.config });
      }
    } catch (error) {
      console.error("설정 로드 오류:", error);
    } finally {
      setLoading(false);
    }
  };

  const saveConfig = async () => {
    setSaving(true);
    try {
      const response = await fetch("/api/rag/config", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(config),
      });

      const data = await response.json();
      if (data.success) {
        alert("설정이 저장되었습니다.");
      } else {
        alert("설정 저장 실패: " + data.error);
      }
    } catch (error) {
      console.error("설정 저장 오류:", error);
      alert("설정 저장 중 오류가 발생했습니다.");
    } finally {
      setSaving(false);
    }
  };

  const resetConfig = async () => {
    if (!confirm("설정을 초기화하시겠습니까?")) return;

    setConfig(defaultConfig);
    alert("설정이 초기화되었습니다. 저장 버튼을 눌러 적용하세요.");
  };

  useEffect(() => {
    loadConfig();
  }, []);

  const handleInputChange = (
    field: keyof AgentConfig,
    value: string | number
  ) => {
    setConfig((prev) => ({ ...prev, [field]: value }));
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold">⚙️ AI 설정 관리</h3>
            <p className="text-sm text-gray-600">
              AI 모델의 동작 방식을 조정할 수 있습니다.
            </p>
          </div>
          <div className="flex space-x-2">
            <Button onClick={resetConfig} variant="outline" size="sm">
              초기화
            </Button>
            <Button onClick={saveConfig} disabled={saving} size="sm">
              {saving ? "저장 중..." : "저장"}
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-2 text-gray-600">설정을 로드하는 중...</p>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 시스템 메시지 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                시스템 메시지
              </label>
              <textarea
                value={config.systemMessage}
                onChange={(e) =>
                  handleInputChange("systemMessage", e.target.value)
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                rows={4}
                placeholder="AI의 역할과 행동 방식을 설명하세요..."
              />
              <p className="text-xs text-gray-500 mt-1">
                AI가 어떻게 행동해야 하는지 설명합니다.
              </p>
            </div>

            {/* 모델 선택 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                모델
              </label>
              <select
                value={config.model}
                onChange={(e) => handleInputChange("model", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
                <option value="gpt-4">GPT-4</option>
                <option value="gpt-4-turbo">GPT-4 Turbo</option>
              </select>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Temperature */}
              <div>
                <Input
                  label="Temperature"
                  type="number"
                  min="0"
                  max="2"
                  step="0.1"
                  value={config.temperature}
                  onChange={(e) =>
                    handleInputChange("temperature", parseFloat(e.target.value))
                  }
                  helperText="창의성 (0=일관적, 2=창의적)"
                />
              </div>

              {/* Max Tokens */}
              <div>
                <Input
                  label="Max Tokens"
                  type="number"
                  min="1"
                  max="4000"
                  value={config.maxTokens}
                  onChange={(e) =>
                    handleInputChange("maxTokens", parseInt(e.target.value))
                  }
                  helperText="최대 응답 길이"
                />
              </div>

              {/* Top P */}
              <div>
                <Input
                  label="Top P"
                  type="number"
                  min="0"
                  max="1"
                  step="0.1"
                  value={config.topP}
                  onChange={(e) =>
                    handleInputChange("topP", parseFloat(e.target.value))
                  }
                  helperText="단어 선택 다양성"
                />
              </div>

              {/* Frequency Penalty */}
              <div>
                <Input
                  label="Frequency Penalty"
                  type="number"
                  min="-2"
                  max="2"
                  step="0.1"
                  value={config.frequencyPenalty}
                  onChange={(e) =>
                    handleInputChange(
                      "frequencyPenalty",
                      parseFloat(e.target.value)
                    )
                  }
                  helperText="반복 단어 억제"
                />
              </div>

              {/* Presence Penalty */}
              <div>
                <Input
                  label="Presence Penalty"
                  type="number"
                  min="-2"
                  max="2"
                  step="0.1"
                  value={config.presencePenalty}
                  onChange={(e) =>
                    handleInputChange(
                      "presencePenalty",
                      parseFloat(e.target.value)
                    )
                  }
                  helperText="새로운 주제 장려"
                />
              </div>
            </div>

            {/* 설정 미리보기 */}
            <div className="mt-6 p-4 bg-gray-50 rounded-lg">
              <h4 className="text-sm font-medium text-gray-700 mb-2">
                설정 미리보기
              </h4>
              <pre className="text-xs text-gray-600 overflow-x-auto">
                {JSON.stringify(config, null, 2)}
              </pre>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
