"use client";

import { useEffect, useState } from "react";
import { Lock, Save, Sparkles, Type, Upload, Download, Loader2, History, Trash2 } from "lucide-react";
import { ResizableSidebar } from "@/components/sidebar";
import { PromptManagement } from "@/components/settings/prompt-management";
import { ImportProvider } from "@/components/import-context";
import { useSettingsStore, fontOptions, timezoneOptions } from "@/lib/settings-store";
import { useConfirm } from "@/components/confirm-provider";
import { cleanupAllPageHistories, estimateAllPageHistoriesUsage, trimAllPageHistoriesToRecent } from "@/lib/page-history";

export default function SettingsPage() {
    const confirm = useConfirm();
    const {
        fontSize,
        setFontSize,
        fontFamily,
        setFontFamily,
        lineHeight,
        setLineHeight,
        tableLineHeight,
        setTableLineHeight,
        timezone,
        setTimezone,
        localHistory,
        setLocalHistory,
        aiConfig,
        setAIConfig,
    } = useSettingsStore();

    const [currentPassword, setCurrentPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [isExporting, setIsExporting] = useState(false);
    const [isRestoring, setIsRestoring] = useState(false);
    const [historyMsg, setHistoryMsg] = useState<string | null>(null);
    const [trimRecentCount, setTrimRecentCount] = useState(10);
    const [historyStats, setHistoryStats] = useState({ keys: 0, snapshots: 0, bytes: 0 });
    const [msg, setMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);

    useEffect(() => {
        setHistoryStats(estimateAllPageHistoriesUsage());
    }, []);

    const handlePasswordChange = async (e: React.FormEvent) => {
        e.preventDefault();
        setMsg(null);

        if (newPassword !== confirmPassword) {
            setMsg({ type: "error", text: "两次输入的新密码不一致" });
            return;
        }

        try {
            const res = await fetch("/api/settings/password", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ currentPassword, newPassword }),
            });

            if (res.ok) {
                setMsg({ type: "success", text: "密码修改成功" });
                setCurrentPassword("");
                setNewPassword("");
                setConfirmPassword("");
            } else {
                const data = await res.json();
                setMsg({ type: "error", text: data.error || "修改失败" });
            }
        } catch {
            setMsg({ type: "error", text: "系统错误，请重试" });
        }
    };

    return (
        <ImportProvider>
            <div className="flex h-[100dvh] w-full overflow-hidden bg-background">
                <ResizableSidebar />
                <main className="flex-1 h-full overflow-y-auto p-4 md:p-10">
                    <div className="mx-auto max-w-3xl space-y-8 pb-16">
                        <header className="ui-enter space-y-2">
                            <h1 className="text-3xl font-bold tracking-tight">设置</h1>
                            <p className="text-muted-foreground">管理外观、AI、安全与备份。</p>
                        </header>

                        <section className="ui-card ui-enter-delayed space-y-5 p-4 md:p-6">
                            <div className="flex items-center gap-2 border-b pb-2">
                                <Type size={18} className="text-primary" />
                                <h2 className="text-lg font-semibold md:text-xl">外观设置</h2>
                            </div>

                            <div className="grid gap-4 md:grid-cols-2">
                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">字体</span>
                                    <select
                                        value={fontFamily}
                                        onChange={(e) => setFontFamily(e.target.value)}
                                        className="ui-select"
                                    >
                                        {fontOptions.map((opt) => (
                                            <option key={opt.value} value={opt.value}>
                                                {opt.label}
                                            </option>
                                        ))}
                                    </select>
                                </label>

                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">字号: {fontSize}px</span>
                                    <input
                                        type="range"
                                        min="12"
                                        max="32"
                                        step="1"
                                        value={fontSize}
                                        onChange={(e) => setFontSize(parseInt(e.target.value, 10))}
                                        className="w-full accent-primary"
                                    />
                                </label>

                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">正文行距: {lineHeight}</span>
                                    <input
                                        type="range"
                                        min="1"
                                        max="3"
                                        step="0.1"
                                        value={lineHeight}
                                        onChange={(e) => setLineHeight(parseFloat(e.target.value))}
                                        className="w-full accent-primary"
                                    />
                                </label>

                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">表格行距: {tableLineHeight}</span>
                                    <input
                                        type="range"
                                        min="1"
                                        max="3"
                                        step="0.1"
                                        value={tableLineHeight}
                                        onChange={(e) => setTableLineHeight(parseFloat(e.target.value))}
                                        className="w-full accent-primary"
                                    />
                                </label>
                            </div>

                            <label className="space-y-2 text-sm block">
                                <span className="font-medium">时区</span>
                                <select
                                    value={timezone}
                                    onChange={(e) => setTimezone(e.target.value)}
                                    className="ui-select"
                                >
                                    {timezoneOptions.map((opt) => (
                                        <option key={opt.value} value={opt.value}>
                                            {opt.label}
                                        </option>
                                    ))}
                                </select>
                            </label>
                        </section>

                        <section className="ui-card ui-enter-delayed space-y-5 p-4 md:p-6">
                            <div className="flex items-center gap-2 border-b pb-2">
                                <History size={18} className="text-primary" />
                                <h2 className="text-lg font-semibold md:text-xl">本地历史策略</h2>
                            </div>
                            <p className="text-sm text-muted-foreground">
                                控制浏览器本地历史快照占用空间。保存后会在后续写入时自动清理，也可立即手动清理一次。
                            </p>
                            <div className="grid gap-4 md:grid-cols-2">
                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">每篇最多保留: {localHistory.maxSnapshotsPerPage} 条</span>
                                    <input
                                        type="range"
                                        min="5"
                                        max="200"
                                        step="1"
                                        value={localHistory.maxSnapshotsPerPage}
                                        onChange={(e) =>
                                            setLocalHistory({ maxSnapshotsPerPage: parseInt(e.target.value, 10) })
                                        }
                                        className="w-full accent-primary"
                                    />
                                </label>
                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">保留时长: {localHistory.retentionDays} 天</span>
                                    <input
                                        type="range"
                                        min="1"
                                        max="365"
                                        step="1"
                                        value={localHistory.retentionDays}
                                        onChange={(e) => setLocalHistory({ retentionDays: parseInt(e.target.value, 10) })}
                                        className="w-full accent-primary"
                                    />
                                </label>
                            </div>
                            <div className="rounded-md border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground">
                                <div>本地历史键: {historyStats.keys}</div>
                                <div>快照总数: {historyStats.snapshots}</div>
                                <div>估算占用: {(historyStats.bytes / 1024).toFixed(1)} KB</div>
                            </div>
                            <div className="flex flex-wrap items-center gap-3">
                                <button
                                    onClick={() => {
                                        const result = cleanupAllPageHistories();
                                        setHistoryStats(estimateAllPageHistoriesUsage());
                                        setHistoryMsg(`已清理本地历史键 ${result.touched} 项`);
                                    }}
                                    className="ui-btn-secondary"
                                >
                                    <Trash2 size={14} />
                                    立即清理一次
                                </button>
                                <div className="flex items-center gap-2">
                                    <input
                                        type="number"
                                        min={1}
                                        max={200}
                                        value={trimRecentCount}
                                        onChange={(e) => setTrimRecentCount(Math.max(1, Math.min(200, parseInt(e.target.value || "1", 10))))}
                                        className="ui-input h-9 w-24"
                                    />
                                    <button
                                        onClick={() => {
                                            const result = trimAllPageHistoriesToRecent(trimRecentCount);
                                            setHistoryStats(estimateAllPageHistoriesUsage());
                                            setHistoryMsg(
                                                `已处理 ${result.touched} 项，删除快照 ${result.removedSnapshots} 条（每篇保留最近 ${trimRecentCount} 条）`
                                            );
                                        }}
                                        className="ui-btn-secondary"
                                    >
                                        仅保留最近 N 条
                                    </button>
                                </div>
                                {historyMsg && <span className="text-xs text-muted-foreground">{historyMsg}</span>}
                            </div>
                        </section>

                        <section className="ui-card ui-enter-delayed space-y-5 p-4 md:p-6">
                            <div className="flex items-center gap-2 border-b pb-2">
                                <Sparkles size={18} className="text-primary" />
                                <h2 className="text-lg font-semibold md:text-xl">AI 配置</h2>
                            </div>

                            <div className="space-y-3">
                                <label className="space-y-1 text-sm block">
                                    <span className="font-medium">API Base URL</span>
                                    <input
                                        type="text"
                                        value={aiConfig.baseURL}
                                        onChange={(e) => setAIConfig({ baseURL: e.target.value })}
                                        className="ui-input"
                                        placeholder="https://api.openai.com/v1"
                                    />
                                </label>

                                <label className="space-y-1 text-sm block">
                                    <span className="font-medium">API Key</span>
                                    <input
                                        type="password"
                                        value={aiConfig.apiKey}
                                        onChange={(e) => setAIConfig({ apiKey: e.target.value })}
                                        className="ui-input"
                                        placeholder="sk-..."
                                    />
                                </label>

                                <label className="space-y-1 text-sm block">
                                    <span className="font-medium">Model</span>
                                    <input
                                        type="text"
                                        value={aiConfig.model}
                                        onChange={(e) => setAIConfig({ model: e.target.value })}
                                        className="ui-input"
                                        placeholder="gpt-4o-mini"
                                    />
                                </label>
                            </div>
                        </section>

                        <section className="ui-card ui-enter-delayed p-4 md:p-6">
                            <PromptManagement />
                        </section>

                        <section className="ui-card ui-enter-delayed space-y-5 p-4 md:p-6">
                            <div className="flex items-center gap-2 border-b pb-2">
                                <Lock size={18} className="text-primary" />
                                <h2 className="text-lg font-semibold md:text-xl">安全设置</h2>
                            </div>

                            <form onSubmit={handlePasswordChange} className="space-y-3 max-w-md">
                                <input
                                    type="password"
                                    value={currentPassword}
                                    onChange={(e) => setCurrentPassword(e.target.value)}
                                    className="ui-input"
                                    placeholder="当前密码"
                                    required
                                />
                                <input
                                    type="password"
                                    value={newPassword}
                                    onChange={(e) => setNewPassword(e.target.value)}
                                    className="ui-input"
                                    placeholder="新密码"
                                    required
                                />
                                <input
                                    type="password"
                                    value={confirmPassword}
                                    onChange={(e) => setConfirmPassword(e.target.value)}
                                    className="ui-input"
                                    placeholder="确认新密码"
                                    required
                                />

                                {msg && (
                                    <div className={msg.type === "success" ? "rounded-md bg-green-500/10 p-3 text-sm text-green-600" : "rounded-md bg-red-500/10 p-3 text-sm text-red-600"}>
                                        {msg.text}
                                    </div>
                                )}

                                <button
                                    type="submit"
                                    className="ui-btn-primary"
                                >
                                    <Save size={14} />
                                    保存密码
                                </button>
                            </form>
                        </section>

                        <section className="ui-card ui-enter-delayed space-y-4 p-4 md:p-6">
                            <h2 className="text-lg font-semibold md:text-xl">备份与恢复</h2>
                            <p className="text-sm text-muted-foreground">恢复会覆盖当前全部文档，请谨慎操作。</p>

                            <div className="flex flex-col gap-3 sm:flex-row">
                                <button
                                    onClick={async () => {
                                        if (isExporting || isRestoring) return;
                                        setIsExporting(true);
                                        try {
                                            const { pages } = await import("@/lib/store").then((m) => m.useEditorStore.getState());
                                            const { exportAllPagesAsZip } = await import("@/lib/export");
                                            await exportAllPagesAsZip(pages);
                                        } finally {
                                            setIsExporting(false);
                                        }
                                    }}
                                    disabled={isExporting || isRestoring}
                                    aria-busy={isExporting}
                                    className="ui-btn-secondary"
                                >
                                    {isExporting ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
                                    {isExporting ? "导出中..." : "下载备份 (Zip)"}
                                </button>

                                <label
                                    className={`ui-btn inline-flex border border-destructive/30 bg-destructive/10 text-destructive hover:bg-destructive/20 ${
                                        isExporting || isRestoring ? "cursor-not-allowed opacity-55" : "cursor-pointer"
                                    }`}
                                >
                                    {isRestoring ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
                                    {isRestoring ? "恢复中..." : "上传备份并恢复"}
                                    <input
                                        type="file"
                                        accept=".zip"
                                        className="hidden"
                                        disabled={isExporting || isRestoring}
                                        onChange={async (e) => {
                                            const file = e.target.files?.[0];
                                            if (!file) return;

                                            const ok = await confirm({
                                                title: "确认恢复备份",
                                                description: "该操作将覆盖当前所有文档，且无法撤销。",
                                                confirmText: "继续恢复",
                                                cancelText: "取消",
                                                tone: "danger",
                                            });
                                            if (!ok) {
                                                e.target.value = "";
                                                return;
                                            }

                                            try {
                                                setIsRestoring(true);
                                                const formData = new FormData();
                                                formData.append("file", file);
                                                const res = await fetch("/api/settings/restore", { method: "POST", body: formData });
                                                if (!res.ok) {
                                                    const err = await res.json().catch(() => ({}));
                                                    throw new Error(err.error || "恢复失败");
                                                }
                                                window.location.reload();
                                            } catch (error) {
                                                alert(String(error));
                                            } finally {
                                                setIsRestoring(false);
                                                e.target.value = "";
                                            }
                                        }}
                                    />
                                </label>
                            </div>
                        </section>

                        <div className="pt-6 text-center text-xs text-muted-foreground/70">
                            NoteAI v{process.env.NEXT_PUBLIC_APP_VERSION || "0.1.0"}
                        </div>
                    </div>
                </main>
            </div>
        </ImportProvider>
    );
}
