"use client";

import Link from "next/link";
import { useState, useEffect, useCallback } from "react";
import { useSession, signOut } from "next-auth/react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { User, CreditCard, Server, LogOut, FileText, AlertTriangle, Shield, Zap } from "lucide-react";
import { PLANS } from "@/lib/plans";

export default function SettingsPage() {
  const { data: session, update: updateSession } = useSession();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [plan, setPlan] = useState("free");
  const [baseline, setBaseline] = useState("200");
  const [instanceUrl, setInstanceUrl] = useState("http://localhost:11434");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState("");
  const [allowCloudRouting, setAllowCloudRouting] = useState(true);
  const [privacyMode, setPrivacyMode] = useState("standard");
  const [redactLogs, setRedactLogs] = useState(true);
  const [privacySaved, setPrivacySaved] = useState(false);

  // Token admin state
  const [tokenEnabled, setTokenEnabled] = useState(true);
  const [tokenChatModel, setTokenChatModel] = useState("google/gemini-2.5-flash");
  const [tokenResearchModel, setTokenResearchModel] = useState("anthropic/claude-sonnet-4.6");
  const [tokenReasoningModel, setTokenReasoningModel] = useState("deepseek/deepseek-r1");
  const [tokenTemp, setTokenTemp] = useState("0.4");
  const [tokenMaxTokens, setTokenMaxTokens] = useState("4096");
  const [tokenBudget, setTokenBudget] = useState("50");
  const [tokenSpent, setTokenSpent] = useState(0);
  const [tokenSystemPrompt, setTokenSystemPrompt] = useState("");
  const [tokenSaving, setTokenSaving] = useState(false);
  const [tokenSaved, setTokenSaved] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);

  const loadUser = useCallback(async () => {
    try {
      const res = await fetch("/api/user");
      if (res.ok) {
        const data = await res.json();
        setName(data.user.name ?? "");
        setEmail(data.user.email ?? "");
        setPlan(data.user.plan ?? "free");
      }
    } catch {
      // Fall back to session data
    }
  }, []);

  const loadTokenConfig = useCallback(async () => {
    try {
      const res = await fetch("/api/token/config");
      if (res.ok) {
        const data = await res.json();
        setIsAdmin(true);
        setTokenEnabled(data.config.enabled);
        setTokenChatModel(data.config.chatModel);
        setTokenResearchModel(data.config.researchModel);
        setTokenReasoningModel(data.config.reasoningModel);
        setTokenTemp(String(data.config.temperature));
        setTokenMaxTokens(String(data.config.maxTokensPerReply));
        setTokenBudget(String(data.config.monthlyBudgetUsd));
        setTokenSpent(data.config.totalSpentUsd);
        setTokenSystemPrompt(data.config.systemPrompt ?? "");
      }
    } catch {
      // Not admin or config not available
    }
  }, []);

  useEffect(() => {
    if (session?.user) {
      setName(session.user.name ?? "");
      setEmail(session.user.email ?? "");
      setPlan(
        ((session.user as Record<string, unknown>)?.plan as string) ?? "free",
      );
      loadUser();
      loadTokenConfig();
    }
  }, [session, loadUser, loadTokenConfig]);

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");

    try {
      const res = await fetch("/api/user", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim() }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to save");
        return;
      }

      await updateSession();
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch {
      setError("Failed to save changes");
    } finally {
      setSaving(false);
    }
  }

  const [upgrading, setUpgrading] = useState<string | null>(null);

  async function handleUpgrade(planKey: string) {
    setUpgrading(planKey);
    setError("");
    try {
      const res = await fetch("/api/stripe/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan: planKey }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setError(data.error || "Failed to start checkout");
      }
    } catch {
      setError("Failed to start checkout");
    } finally {
      setUpgrading(null);
    }
  }

  async function handleManageBilling() {
    setError("");
    try {
      const res = await fetch("/api/stripe/portal", { method: "POST" });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setError(data.error || "Failed to open billing portal");
      }
    } catch {
      setError("Failed to open billing portal");
    }
  }

  function handleSignOut() {
    signOut({ callbackUrl: "/" });
  }

  const planLabel = plan.charAt(0).toUpperCase() + plan.slice(1);

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-gray-100">Settings</h1>
        <p className="mt-1 text-sm text-gray-400">
          Manage your account and preferences
        </p>
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-lg border border-red-800/50 bg-red-900/20 px-4 py-3 text-sm text-red-400">
          <AlertTriangle size={16} />
          {error}
          <button
            onClick={() => setError("")}
            className="ml-auto text-red-400 hover:text-red-300"
          >
            Dismiss
          </button>
        </div>
      )}

      <div className="mx-auto max-w-2xl space-y-6">
        {/* Account info */}
        <Card title="Account" icon={<User size={20} />}>
          <form onSubmit={handleSave} className="space-y-4">
            <Input
              id="name"
              label="Name"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <Input
              id="email"
              label="Email"
              type="email"
              value={email}
              disabled
            />
            <p className="text-xs text-gray-500">
              Email cannot be changed. Contact support if needed.
            </p>
            <Button type="submit" size="md" disabled={saving}>
              {saved ? "Saved!" : saving ? "Saving..." : "Save Changes"}
            </Button>
          </form>
        </Card>

        {/* Plan */}
        <Card title="Plan" icon={<CreditCard size={20} />}>
          <div className="space-y-4">
            {(Object.entries(PLANS) as [string, typeof PLANS[keyof typeof PLANS]][]).map(
              ([key, planDef]) => {
                const isCurrent = plan === key;
                const canUpgrade =
                  !isCurrent &&
                  key !== "free" &&
                  key !== "enterprise";
                return (
                  <div
                    key={key}
                    className={`flex items-center justify-between rounded-lg border p-4 ${
                      isCurrent
                        ? "border-indigo-500/30 bg-indigo-500/5"
                        : "border-gray-800 bg-gray-800/50"
                    }`}
                  >
                    <div>
                      <p
                        className={`font-medium ${
                          key === "pro" ? "text-indigo-300" : "text-gray-100"
                        }`}
                      >
                        {planDef.name} Plan
                        {planDef.price > 0 && ` — $${planDef.price}/mo`}
                      </p>
                      <p className="text-sm text-gray-400">
                        {planDef.features.slice(0, 2).join(", ")}
                      </p>
                    </div>
                    {isCurrent ? (
                      <span className="rounded-full bg-indigo-500/20 px-3 py-1 text-xs font-medium text-indigo-300">
                        Current
                      </span>
                    ) : canUpgrade ? (
                      <Button
                        variant="primary"
                        size="sm"
                        disabled={upgrading === key}
                        onClick={() => handleUpgrade(key)}
                      >
                        {upgrading === key
                          ? "Redirecting..."
                          : "Upgrade"}
                      </Button>
                    ) : key === "enterprise" && !isCurrent ? (
                      <Button variant="secondary" size="sm">
                        Contact Sales
                      </Button>
                    ) : null}
                  </div>
                );
              },
            )}
            {plan !== "free" && (
              <div className="flex items-center justify-between">
                <p className="text-xs text-gray-500">
                  Current plan:{" "}
                  <span className="font-medium">{planLabel}</span>
                </p>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleManageBilling}
                >
                  Manage Billing
                </Button>
              </div>
            )}
          </div>
        </Card>

        {/* Spending baseline */}
        <Card title="Spending Baseline" icon={<CreditCard size={20} />}>
          <form onSubmit={handleSave} className="space-y-4">
            <Input
              id="baseline"
              label="Monthly AI spending without LLMHosts (USD)"
              type="number"
              step="1"
              min="0"
              value={baseline}
              onChange={(e) => setBaseline(e.target.value)}
              placeholder="200"
            />
            <p className="text-xs text-gray-500">
              Used for savings projections and comparison charts.
            </p>
            <Button type="submit" size="md">
              Update Baseline
            </Button>
          </form>
        </Card>

        {/* LLMHosts Instance */}
        <Card title="LLMHosts Instance" icon={<Server size={20} />}>
          <form onSubmit={handleSave} className="space-y-4">
            <Input
              id="instance-url"
              label="Instance URL"
              placeholder="http://localhost:11434"
              value={instanceUrl}
              onChange={(e) => setInstanceUrl(e.target.value)}
            />
            <p className="text-xs text-gray-500">
              URL of your running LLMHosts proxy. Used to pull live metrics.
            </p>
            <div className="flex items-center gap-3">
              <Button type="submit" size="md">
                Save URL
              </Button>
              <Button type="button" variant="secondary" size="md">
                Test Connection
              </Button>
            </div>
          </form>
        </Card>

        {/* Privacy & Routing */}
        <Card title="Privacy & Routing" icon={<Shield size={20} />}>
          <div className="space-y-4">
            <p className="text-sm text-gray-400">
              Control how your requests are routed based on PII detection.
              When PII is detected in your prompts, requests are automatically
              routed to local models to protect your data.
            </p>

            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-100">
                  Allow cloud routing for non-PII requests
                </p>
                <p className="text-xs text-gray-500">
                  When enabled, requests without PII can be sent to cloud backends
                </p>
              </div>
              <button
                type="button"
                role="switch"
                aria-checked={allowCloudRouting}
                onClick={() => setAllowCloudRouting(!allowCloudRouting)}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                  allowCloudRouting ? "bg-indigo-500" : "bg-gray-700"
                }`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                    allowCloudRouting ? "translate-x-6" : "translate-x-1"
                  }`}
                />
              </button>
            </div>

            <Select
              id="privacy-mode"
              label="Privacy Mode"
              value={privacyMode}
              onChange={(e) => setPrivacyMode(e.target.value)}
              options={[
                { value: "standard", label: "Standard -- PII auto-detected, non-PII routes to cloud" },
                { value: "strict", label: "Strict -- All requests route to local models" },
                { value: "paranoid", label: "Paranoid -- Local only, extended PII patterns" },
              ]}
            />

            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-100">
                  Redact PII from logs
                </p>
                <p className="text-xs text-gray-500">
                  When enabled, detected PII is redacted from routing decision logs
                </p>
              </div>
              <button
                type="button"
                role="switch"
                aria-checked={redactLogs}
                onClick={() => setRedactLogs(!redactLogs)}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                  redactLogs ? "bg-indigo-500" : "bg-gray-700"
                }`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                    redactLogs ? "translate-x-6" : "translate-x-1"
                  }`}
                />
              </button>
            </div>

            {/* Privacy mode indicator */}
            <div className={`rounded-lg border p-3 ${
              privacyMode === "paranoid"
                ? "border-red-800/50 bg-red-900/20"
                : privacyMode === "strict"
                  ? "border-yellow-800/50 bg-yellow-900/20"
                  : "border-green-800/50 bg-green-900/20"
            }`}>
              <div className="flex items-center gap-2">
                <Shield size={16} className={
                  privacyMode === "paranoid"
                    ? "text-red-400"
                    : privacyMode === "strict"
                      ? "text-yellow-400"
                      : "text-green-400"
                } />
                <p className={`text-sm font-medium ${
                  privacyMode === "paranoid"
                    ? "text-red-300"
                    : privacyMode === "strict"
                      ? "text-yellow-300"
                      : "text-green-300"
                }`}>
                  {privacyMode === "paranoid"
                    ? "Paranoid Mode: All requests forced to encrypted local routing"
                    : privacyMode === "strict"
                      ? "Strict Mode: All requests routed to local models only"
                      : allowCloudRouting
                        ? "Standard Mode: PII auto-detected, clean requests can use cloud"
                        : "Standard Mode: Cloud routing disabled by preference"}
                </p>
              </div>
            </div>

            <Button
              type="button"
              size="md"
              onClick={() => {
                setPrivacySaved(true);
                setTimeout(() => setPrivacySaved(false), 2000);
              }}
            >
              {privacySaved ? "Saved!" : "Save Privacy Settings"}
            </Button>
          </div>
        </Card>

        {/* Token Admin (admin only) */}
        {isAdmin && (
          <Card title="Token Assistant" icon={<Zap size={20} />}>
            <div className="space-y-4">
              <p className="text-sm text-gray-400">
                Configure Token, the AI fleet assistant. Token uses OpenRouter
                to help users manage models and deployments.
              </p>

              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-100">Enabled</p>
                  <p className="text-xs text-gray-500">
                    Allow users to chat with Token in the dashboard
                  </p>
                </div>
                <button
                  type="button"
                  role="switch"
                  aria-checked={tokenEnabled}
                  onClick={() => setTokenEnabled(!tokenEnabled)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    tokenEnabled ? "bg-indigo-500" : "bg-gray-700"
                  }`}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      tokenEnabled ? "translate-x-6" : "translate-x-1"
                    }`}
                  />
                </button>
              </div>

              <Input
                id="token-chat-model"
                label="Chat Model"
                value={tokenChatModel}
                onChange={(e) => setTokenChatModel(e.target.value)}
                placeholder="google/gemini-2.5-flash"
              />
              <Input
                id="token-research-model"
                label="Research Model"
                value={tokenResearchModel}
                onChange={(e) => setTokenResearchModel(e.target.value)}
                placeholder="anthropic/claude-sonnet-4.6"
              />
              <Input
                id="token-reasoning-model"
                label="Reasoning Model"
                value={tokenReasoningModel}
                onChange={(e) => setTokenReasoningModel(e.target.value)}
                placeholder="deepseek/deepseek-r1"
              />

              <div className="grid grid-cols-2 gap-4">
                <Input
                  id="token-temp"
                  label="Temperature"
                  type="number"
                  step="0.1"
                  min="0"
                  max="2"
                  value={tokenTemp}
                  onChange={(e) => setTokenTemp(e.target.value)}
                />
                <Input
                  id="token-max-tokens"
                  label="Max Tokens/Reply"
                  type="number"
                  step="256"
                  min="100"
                  max="32000"
                  value={tokenMaxTokens}
                  onChange={(e) => setTokenMaxTokens(e.target.value)}
                />
              </div>

              <Input
                id="token-budget"
                label="Monthly Budget (USD)"
                type="number"
                step="1"
                min="0"
                value={tokenBudget}
                onChange={(e) => setTokenBudget(e.target.value)}
              />

              <div className="rounded-lg border border-gray-700 bg-gray-800/50 p-3">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-gray-400">Spent this month</span>
                  <span className="text-sm font-medium text-gray-200">
                    ${tokenSpent.toFixed(4)} / ${Number(tokenBudget).toFixed(2)}
                  </span>
                </div>
                <div className="mt-2 h-2 overflow-hidden rounded-full bg-gray-700">
                  <div
                    className="h-full rounded-full bg-indigo-500 transition-all"
                    style={{
                      width: `${Math.min((tokenSpent / Math.max(Number(tokenBudget), 0.01)) * 100, 100)}%`,
                    }}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="token-system-prompt" className="mb-1 block text-sm font-medium text-gray-300">
                  Custom System Prompt (appended to Token&apos;s base prompt)
                </label>
                <textarea
                  id="token-system-prompt"
                  value={tokenSystemPrompt}
                  onChange={(e) => setTokenSystemPrompt(e.target.value)}
                  placeholder="Additional instructions for Token..."
                  rows={3}
                  className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                />
              </div>

              <Button
                type="button"
                size="md"
                disabled={tokenSaving}
                onClick={async () => {
                  setTokenSaving(true);
                  try {
                    const res = await fetch("/api/token/config", {
                      method: "PATCH",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({
                        enabled: tokenEnabled,
                        chatModel: tokenChatModel,
                        researchModel: tokenResearchModel,
                        reasoningModel: tokenReasoningModel,
                        temperature: parseFloat(tokenTemp),
                        maxTokensPerReply: parseInt(tokenMaxTokens, 10),
                        monthlyBudgetUsd: parseFloat(tokenBudget),
                        systemPrompt: tokenSystemPrompt,
                      }),
                    });
                    if (res.ok) {
                      setTokenSaved(true);
                      setTimeout(() => setTokenSaved(false), 2000);
                    } else {
                      const data = await res.json();
                      setError(data.error || "Failed to save Token config");
                    }
                  } catch {
                    setError("Failed to save Token config");
                  } finally {
                    setTokenSaving(false);
                  }
                }}
              >
                {tokenSaved ? "Saved!" : tokenSaving ? "Saving..." : "Save Token Config"}
              </Button>
            </div>
          </Card>
        )}

        {/* Legal */}
        <Card title="Legal" icon={<FileText size={20} />}>
          <div className="flex flex-wrap gap-4">
            <Link
              href="/legal/terms"
              className="text-sm text-indigo-400 transition-colors hover:text-indigo-300"
            >
              Terms of Service
            </Link>
            <Link
              href="/legal/privacy"
              className="text-sm text-indigo-400 transition-colors hover:text-indigo-300"
            >
              Privacy Policy
            </Link>
          </div>
        </Card>

        {/* Sign out */}
        <Card>
          <div className="flex items-center justify-between">
            <div>
              <p className="font-medium text-gray-100">Sign Out</p>
              <p className="text-sm text-gray-400">
                End your current session
              </p>
            </div>
            <Button variant="danger" size="md" onClick={handleSignOut}>
              <LogOut size={16} />
              Sign Out
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}
