import { useState, useEffect } from "react";
import { Droplet, Upload, Eye, Save, Loader2 } from "lucide-react";
import { useSetting, useSaveSetting } from "../../hooks/useSettings";

const SETTING_KEY = "watermark";

interface WatermarkConfig {
  enabled: boolean;
  text: string;
  position: string;
  opacity: number;
  size: string;
}

const defaultConfig: WatermarkConfig = {
  enabled: true,
  text: "AI Generated",
  position: "bottom-right",
  opacity: 30,
  size: "medium",
};

const positions = [
  { value: "top-left", label: "左上角" },
  { value: "top-right", label: "右上角" },
  { value: "bottom-left", label: "左下角" },
  { value: "bottom-right", label: "右下角" },
  { value: "center", label: "居中" },
];

const sizes = [
  { value: "small", label: "小" },
  { value: "medium", label: "中" },
  { value: "large", label: "大" },
];

export function AIWatermarkSettings() {
  const { data: rawSetting, isLoading } = useSetting(SETTING_KEY);
  const saveSetting = useSaveSetting();

  const [config, setConfig] = useState<WatermarkConfig>(defaultConfig);
  const [customLogo, setCustomLogo] = useState<File | null>(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    if (rawSetting) {
      try {
        const parsed = JSON.parse(rawSetting) as WatermarkConfig;
        setConfig({ ...defaultConfig, ...parsed });
      } catch {
        // keep default
      }
    }
  }, [rawSetting]);

  const handleSave = async () => {
    await saveSetting.mutateAsync({ key: SETTING_KEY, value: JSON.stringify(config) });
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  if (isLoading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-6 h-6 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="h-full overflow-auto bg-background p-6">
      <div className="max-w-5xl mx-auto">
        <div className="mb-6">
          <h1 className="text-2xl font-semibold text-foreground mb-1">AI生成水印设置</h1>
          <p className="text-sm text-muted-foreground">配置AI生成内容的默认水印样式</p>
        </div>

        <div className="grid grid-cols-3 gap-6">
          <div className="col-span-2 space-y-6">
            {/* Enable/Disable */}
            <div className="rounded-xl border border-border bg-card p-5">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="font-medium text-foreground mb-1">启用水印</h3>
                  <p className="text-sm text-muted-foreground">为所有AI生成的内容添加水印</p>
                </div>
                <button
                  onClick={() => setConfig({ ...config, enabled: !config.enabled })}
                  className={`relative w-12 h-6 rounded-full transition-colors ${
                    config.enabled ? "bg-primary" : "bg-muted"
                  }`}
                >
                  <div
                    className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-transform ${
                      config.enabled ? "translate-x-7" : "translate-x-1"
                    }`}
                  />
                </button>
              </div>
            </div>

            {/* Watermark Text */}
            <div className="rounded-xl border border-border bg-card p-5">
              <label className="block font-medium text-foreground mb-3">水印文字</label>
              <input
                type="text"
                value={config.text}
                onChange={(e) => setConfig({ ...config, text: e.target.value })}
                placeholder="输入水印文字"
                className="w-full px-4 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
              />
            </div>

            {/* Custom Logo */}
            <div className="rounded-xl border border-border bg-card p-5">
              <label className="block font-medium text-foreground mb-3">自定义水印Logo</label>
              <div className="border-2 border-dashed border-border rounded-lg p-8 text-center hover:border-primary transition-colors cursor-pointer">
                <input
                  type="file"
                  accept="image/*"
                  onChange={(e) => {
                    if (e.target.files && e.target.files[0]) setCustomLogo(e.target.files[0]);
                  }}
                  className="hidden"
                  id="logo-upload"
                />
                <label htmlFor="logo-upload" className="cursor-pointer">
                  {customLogo ? (
                    <div>
                      <div className="w-16 h-16 rounded-lg bg-muted mx-auto mb-3 flex items-center justify-center">
                        <Droplet className="w-8 h-8 text-primary" />
                      </div>
                      <p className="text-foreground mb-1">{customLogo.name}</p>
                      <span className="text-sm text-primary hover:underline">重新上传</span>
                    </div>
                  ) : (
                    <div>
                      <Upload className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
                      <p className="text-foreground mb-1">点击上传Logo图片</p>
                      <p className="text-sm text-muted-foreground">支持 PNG、JPG 格式，建议尺寸 200x200</p>
                    </div>
                  )}
                </label>
              </div>
            </div>

            {/* Position */}
            <div className="rounded-xl border border-border bg-card p-5">
              <label className="block font-medium text-foreground mb-3">水印位置</label>
              <div className="grid grid-cols-3 gap-3">
                {positions.map((pos) => (
                  <button
                    key={pos.value}
                    onClick={() => setConfig({ ...config, position: pos.value })}
                    className={`px-4 py-3 rounded-lg border transition-all text-sm ${
                      config.position === pos.value
                        ? "border-primary bg-accent text-primary"
                        : "border-border bg-background text-foreground hover:bg-muted"
                    }`}
                  >
                    {pos.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Size */}
            <div className="rounded-xl border border-border bg-card p-5">
              <label className="block font-medium text-foreground mb-3">水印大小</label>
              <div className="grid grid-cols-3 gap-3">
                {sizes.map((size) => (
                  <button
                    key={size.value}
                    onClick={() => setConfig({ ...config, size: size.value })}
                    className={`px-4 py-3 rounded-lg border transition-all text-sm ${
                      config.size === size.value
                        ? "border-primary bg-accent text-primary"
                        : "border-border bg-background text-foreground hover:bg-muted"
                    }`}
                  >
                    {size.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Opacity */}
            <div className="rounded-xl border border-border bg-card p-5">
              <label className="block font-medium text-foreground mb-3">
                透明度：{config.opacity}%
              </label>
              <input
                type="range"
                min="0"
                max="100"
                value={config.opacity}
                onChange={(e) => setConfig({ ...config, opacity: Number(e.target.value) })}
                className="w-full h-2 bg-muted rounded-lg appearance-none cursor-pointer accent-primary"
              />
              <div className="flex justify-between text-xs text-muted-foreground mt-2">
                <span>0%</span>
                <span>50%</span>
                <span>100%</span>
              </div>
            </div>

            <button
              onClick={handleSave}
              disabled={saveSetting.isPending}
              className="w-full py-3 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center justify-center gap-2 disabled:opacity-70"
            >
              {saveSetting.isPending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}
              {saved ? "已保存" : "保存设置"}
            </button>
          </div>

          {/* Preview Panel */}
          <div className="col-span-1">
            <div className="rounded-xl border border-border bg-card p-5 sticky top-6">
              <div className="flex items-center gap-2 mb-4">
                <Eye className="w-4 h-4 text-primary" />
                <h3 className="font-medium text-foreground">预览效果</h3>
              </div>

              <div className="aspect-video rounded-lg bg-gradient-to-br from-purple-100 to-blue-100 relative overflow-hidden">
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="text-center">
                    <Droplet className="w-16 h-16 text-muted-foreground/30 mx-auto mb-2" />
                    <p className="text-sm text-muted-foreground/50">示例内容</p>
                  </div>
                </div>

                {config.enabled && (
                  <div
                    className={`absolute ${
                      config.position === "top-left" ? "top-3 left-3"
                        : config.position === "top-right" ? "top-3 right-3"
                        : config.position === "bottom-left" ? "bottom-3 left-3"
                        : config.position === "bottom-right" ? "bottom-3 right-3"
                        : "top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
                    }`}
                    style={{ opacity: config.opacity / 100 }}
                  >
                    <div
                      className={`px-3 py-1.5 rounded bg-black/20 backdrop-blur-sm text-white ${
                        config.size === "small" ? "text-xs"
                          : config.size === "large" ? "text-base"
                          : "text-sm"
                      }`}
                    >
                      {config.text}
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-4 p-3 rounded-lg bg-muted space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">状态：</span>
                  <span className="text-foreground">{config.enabled ? "已启用" : "已禁用"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">位置：</span>
                  <span className="text-foreground">
                    {positions.find((p) => p.value === config.position)?.label}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">大小：</span>
                  <span className="text-foreground">
                    {sizes.find((s) => s.value === config.size)?.label}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">透明度：</span>
                  <span className="text-foreground">{config.opacity}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
