"use client";

import { useState, useEffect } from "react";
import { Save, RotateCcw, DollarSign, Bot, FileText, Bell } from "lucide-react";
import { cn } from "@/lib/utils";

// Config types
interface TradingConfig {
  initialCapital: number;
  maxPositions: number;
  stopLossPercent: number;
}

interface AgentsConfig {
  maxAgents: number;
  skillLearningRate: number;
}

interface LoggingConfig {
  logLevel: "debug" | "info" | "warn" | "error";
  retentionDays: number;
}

interface NotificationsConfig {
  webhookUrl: string;
  notificationLevel: "all" | "important" | "critical" | "none";
}

interface SystemConfig {
  trading: TradingConfig;
  agents: AgentsConfig;
  logging: LoggingConfig;
  notifications: NotificationsConfig;
}

const defaultConfig: SystemConfig = {
  trading: {
    initialCapital: 10000,
    maxPositions: 10,
    stopLossPercent: 5,
  },
  agents: {
    maxAgents: 5,
    skillLearningRate: 0.1,
  },
  logging: {
    logLevel: "info",
    retentionDays: 30,
  },
  notifications: {
    webhookUrl: "",
    notificationLevel: "important",
  },
};

interface ConfigSectionProps {
  title: string;
  icon: React.ElementType;
  children: React.ReactNode;
}

function ConfigSection({ title, icon: Icon, children }: ConfigSectionProps) {
  return (
    <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 shadow-xl">
      <h3 className="text-[#e1e1e1] text-lg font-black mb-6 flex items-center gap-3 uppercase tracking-tight">
        <div className="p-2 bg-[#00ffcc]/10 rounded-xl">
          <Icon className="w-5 h-5 text-[#00ffcc]" />
        </div>
        {title}
      </h3>
      {children}
    </div>
  );
}

interface FormFieldProps {
  label: string;
  children: React.ReactNode;
  error?: string;
}

function FormField({ label, children, error }: FormFieldProps) {
  return (
    <div className="mb-4">
      <label className="block text-[#666666] text-[10px] font-black uppercase tracking-widest mb-2">
        {label}
      </label>
      {children}
      {error && (
        <p className="text-[#ff5252] text-[10px] font-bold mt-1 uppercase tracking-tighter">
          {error}
        </p>
      )}
    </div>
  );
}

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  className?: string;
}

function Input({ className, ...props }: InputProps) {
  return (
    <input
      className={cn(
        "w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3",
        "text-[#e1e1e1] text-sm font-bold placeholder-[#666666]",
        "focus:outline-none focus:border-[#00ffcc] focus:ring-1 focus:ring-[#00ffcc]",
        "transition-all",
        className,
      )}
      {...props}
    />
  );
}

interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  className?: string;
}

function Select({ className, children, ...props }: SelectProps) {
  return (
    <select
      className={cn(
        "w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3",
        "text-[#e1e1e1] text-sm font-bold",
        "focus:outline-none focus:border-[#00ffcc] focus:ring-1 focus:ring-[#00ffcc]",
        "transition-all appearance-none cursor-pointer",
        className,
      )}
      {...props}
    >
      {children}
    </select>
  );
}

export default function Config() {
  const [config, setConfig] = useState<SystemConfig>(defaultConfig);
  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});
  const [isDirty, setIsDirty] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);

  useEffect(() => {
    const saved = localStorage.getItem("openclaw_config");
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        setConfig((prev) => ({ ...prev, ...parsed }));
      } catch {
        // Ignore parse errors
      }
    }
  }, []);

  const validate = (): boolean => {
    const newErrors: Partial<Record<string, string>> = {};

    if (config.trading.initialCapital < 100) {
      newErrors.initialCapital = "资金必须 >= $100";
    }
    if (config.trading.maxPositions < 1 || config.trading.maxPositions > 100) {
      newErrors.maxPositions = "持仓范围: 1-100";
    }
    if (
      config.trading.stopLossPercent < 0.1 ||
      config.trading.stopLossPercent > 50
    ) {
      newErrors.stopLossPercent = "止损范围: 0.1-50%";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async () => {
    if (!validate()) return;

    setIsSaving(true);
    setSaveSuccess(false);

    await new Promise((resolve) => setTimeout(resolve, 800));

    localStorage.setItem("openclaw_config", JSON.stringify(config));
    setIsDirty(false);
    setIsSaving(false);
    setSaveSuccess(true);

    setTimeout(() => setSaveSuccess(false), 3000);
  };

  const handleReset = () => {
    setConfig(defaultConfig);
    setIsDirty(true);
    setErrors({});
  };

  const updateTrading = (field: keyof TradingConfig, value: number) => {
    setConfig((prev) => ({
      ...prev,
      trading: { ...prev.trading, [field]: value },
    }));
    setIsDirty(true);
    setSaveSuccess(false);
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Header with Actions */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-black text-[#e1e1e1] tracking-tight">
            系统配置
          </h1>
          <p className="text-[#666666] text-xs font-bold uppercase tracking-wider mt-1">
            全局操作参数和风险控制
          </p>
        </div>
        <div className="flex items-center gap-4">
          {saveSuccess && (
            <span className="text-[#00ffcc] text-[10px] font-black uppercase tracking-widest animate-fade-in">
              系统已同步
            </span>
          )}
          {isDirty && !saveSuccess && (
            <span className="text-[#ffb74d] text-[10px] font-black uppercase tracking-widest animate-pulse">
              待保存更改
            </span>
          )}
          <button
            onClick={handleReset}
            className="flex items-center gap-2 border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#e1e1e1] px-4 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all"
          >
            <RotateCcw className="w-4 h-4" />
            重置
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving || !isDirty}
            className="flex items-center gap-2 bg-[#00ffcc] hover:bg-[#00e6b8] text-[#121212] px-6 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all shadow-[0_0_15px_rgba(0,255,204,0.3)] disabled:opacity-30 disabled:shadow-none"
          >
            <Save className="w-4 h-4" />
            {isSaving ? "同步中..." : "提交"}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        {/* Trading Config */}
        <ConfigSection title="风险管理" icon={DollarSign}>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <FormField label="初始资金 ($)" error={errors.initialCapital}>
              <Input
                type="number"
                value={config.trading.initialCapital}
                onChange={(e) =>
                  updateTrading(
                    "initialCapital",
                    parseFloat(e.target.value) || 0,
                  )
                }
              />
            </FormField>
            <FormField label="最大持仓数" error={errors.maxPositions}>
              <Input
                type="number"
                value={config.trading.maxPositions}
                onChange={(e) =>
                  updateTrading("maxPositions", parseInt(e.target.value) || 0)
                }
              />
            </FormField>
            <FormField label="动态止损 (%)" error={errors.stopLossPercent}>
              <Input
                type="number"
                step={0.1}
                value={config.trading.stopLossPercent}
                onChange={(e) =>
                  updateTrading(
                    "stopLossPercent",
                    parseFloat(e.target.value) || 0,
                  )
                }
              />
            </FormField>
          </div>
        </ConfigSection>

        {/* Agents Config */}
        <ConfigSection title="代理基础设施" icon={Bot}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField label="并发实例限制">
              <Input
                type="number"
                value={config.agents.maxAgents}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    agents: {
                      ...prev.agents,
                      maxAgents: parseInt(e.target.value) || 0,
                    },
                  }))
                }
              />
            </FormField>
            <FormField label="神经学习率">
              <Input
                type="number"
                step={0.01}
                value={config.agents.skillLearningRate}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    agents: {
                      ...prev.agents,
                      skillLearningRate: parseFloat(e.target.value) || 0,
                    },
                  }))
                }
              />
            </FormField>
          </div>
        </ConfigSection>

        {/* Logging Config */}
        <ConfigSection title="系统遥测" icon={FileText}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField label="详细程度">
              <Select
                value={config.logging.logLevel}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    logging: {
                      ...prev.logging,
                      logLevel: e.target.value as any,
                    },
                  }))
                }
              >
                <option value="debug">调试 (详细)</option>
                <option value="info">信息 (标准)</option>
                <option value="warn">警告 (异常)</option>
                <option value="error">错误 (严重)</option>
              </Select>
            </FormField>
            <FormField label="数据保留 (天)">
              <Input
                type="number"
                value={config.logging.retentionDays}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    logging: {
                      ...prev.logging,
                      retentionDays: parseInt(e.target.value) || 0,
                    },
                  }))
                }
              />
            </FormField>
          </div>
        </ConfigSection>

        {/* Notifications Config */}
        <ConfigSection title="告警集成" icon={Bell}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField label="Webhook 端点">
              <Input
                type="url"
                placeholder="https://alerts.infra.io/v1/..."
                value={config.notifications.webhookUrl}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    notifications: {
                      ...prev.notifications,
                      webhookUrl: e.target.value,
                    },
                  }))
                }
              />
            </FormField>
            <FormField label="告警优先级筛选">
              <Select
                value={config.notifications.notificationLevel}
                onChange={(e) =>
                  setConfig((prev) => ({
                    ...prev,
                    notifications: {
                      ...prev.notifications,
                      notificationLevel: e.target.value as any,
                    },
                  }))
                }
              >
                <option value="all">全部遥测</option>
                <option value="important">重要事件</option>
                <option value="critical">仅严重告警</option>
                <option value="none">静默模式</option>
              </Select>
            </FormField>
          </div>
        </ConfigSection>
      </div>
    </div>
  );
}
