"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Settings,
  Cpu,
  RefreshCw,
  CheckCircle,
  XCircle,
  Play,
  Users,
  Trash2,
  ShieldCheck,
  ShieldOff,
  FileText,
  Brain,
  BarChart3,
} from "lucide-react";
import { settingsAPI, adminAPI, type AdminUser } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";

const LLM_PROVIDERS = [
  { value: "openai", label: "OpenAI (GPT-4o)", hint: "Requires OPENAI_API_KEY in .env" },
  { value: "anthropic", label: "Anthropic (Claude)", hint: "Requires ANTHROPIC_API_KEY in .env" },
  { value: "gemini", label: "Google Gemini", hint: "Requires GEMINI_API_KEY in .env" },
  { value: "ollama", label: "Ollama (Local)", hint: "Requires Ollama running on host" },
];

export default function SettingsPage() {
  const qc = useQueryClient();
  const currentUser = useAuthStore((s) => s.user);

  const { data: settings, isLoading: settingsLoading } = useQuery({
    queryKey: ["settings"],
    queryFn: () => settingsAPI.get(),
  });

  const { data: stats } = useQuery({
    queryKey: ["admin-stats"],
    queryFn: () => adminAPI.getStats(),
    enabled: !!currentUser?.is_admin,
    refetchInterval: 30_000,
  });

  const { data: users, isLoading: usersLoading } = useQuery({
    queryKey: ["admin-users"],
    queryFn: () => adminAPI.listUsers(),
    enabled: !!currentUser?.is_admin,
  });

  const updateSetting = useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) => settingsAPI.update(key, value),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings"] }),
  });

  const deleteUser = useMutation({
    mutationFn: (id: number) => adminAPI.deleteUser(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
  });

  const toggleAdmin = useMutation({
    mutationFn: (id: number) => adminAPI.toggleAdmin(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
  });

  const [testResult, setTestResult] = useState<{
    status: string;
    detail?: string;
    summary_preview?: string;
    provider?: string;
  } | null>(null);
  const [testing, setTesting] = useState(false);
  const [taskIds, setTaskIds] = useState<Record<string, string>>({});
  const [confirmDelete, setConfirmDelete] = useState<number | null>(null);

  const testLLM = async () => {
    setTesting(true);
    setTestResult(null);
    try {
      const result = await settingsAPI.testLLM();
      setTestResult(result);
    } catch (e: unknown) {
      setTestResult({ status: "error", detail: e instanceof Error ? e.message : String(e) });
    } finally {
      setTesting(false);
    }
  };

  const trigger = async (name: string, fn: () => Promise<{ task_id: string }>) => {
    const result = await fn();
    setTaskIds((prev) => ({ ...prev, [name]: result.task_id }));
  };

  if (settingsLoading) return <div className="text-center py-20 text-muted-foreground">Loading...</div>;

  if (!currentUser?.is_admin) {
    return <div className="text-center py-20 text-muted-foreground">Admin access required.</div>;
  }

  const pct = stats && stats.total_bills > 0
    ? Math.round((stats.briefs_generated / stats.total_bills) * 100)
    : 0;

  return (
    <div className="space-y-8 max-w-2xl">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <Settings className="w-5 h-5" /> Admin
        </h1>
        <p className="text-muted-foreground text-sm mt-1">Manage users, LLM provider, and system settings</p>
      </div>

      {/* Analysis Status */}
      <section className="bg-card border border-border rounded-lg p-6 space-y-4">
        <h2 className="font-semibold flex items-center gap-2">
          <BarChart3 className="w-4 h-4" /> Analysis Status
          <span className="text-xs text-muted-foreground font-normal ml-auto">refreshes every 30s</span>
        </h2>
        {stats ? (
          <>
            <div className="grid grid-cols-3 gap-4">
              <div className="bg-muted/50 rounded-lg p-3 text-center">
                <FileText className="w-4 h-4 mx-auto mb-1 text-muted-foreground" />
                <div className="text-xl font-bold">{stats.total_bills.toLocaleString()}</div>
                <div className="text-xs text-muted-foreground">Total Bills</div>
              </div>
              <div className="bg-muted/50 rounded-lg p-3 text-center">
                <FileText className="w-4 h-4 mx-auto mb-1 text-blue-500" />
                <div className="text-xl font-bold">{stats.docs_fetched.toLocaleString()}</div>
                <div className="text-xs text-muted-foreground">Docs Fetched</div>
              </div>
              <div className="bg-muted/50 rounded-lg p-3 text-center">
                <Brain className="w-4 h-4 mx-auto mb-1 text-green-500" />
                <div className="text-xl font-bold">{stats.briefs_generated.toLocaleString()}</div>
                <div className="text-xs text-muted-foreground">Briefs Generated</div>
              </div>
            </div>

            {/* Progress bar */}
            <div className="space-y-1">
              <div className="flex justify-between text-xs text-muted-foreground">
                <span>{stats.full_briefs} full · {stats.amendment_briefs} amendments</span>
                <span>{pct}% analyzed · {stats.remaining.toLocaleString()} remaining</span>
              </div>
              <div className="h-2 bg-muted rounded-full overflow-hidden">
                <div
                  className="h-full bg-green-500 rounded-full transition-all duration-500"
                  style={{ width: `${pct}%` }}
                />
              </div>
            </div>
          </>
        ) : (
          <p className="text-sm text-muted-foreground">Loading stats...</p>
        )}
      </section>

      {/* User Management */}
      <section className="bg-card border border-border rounded-lg p-6 space-y-4">
        <h2 className="font-semibold flex items-center gap-2">
          <Users className="w-4 h-4" /> Users
        </h2>
        {usersLoading ? (
          <p className="text-sm text-muted-foreground">Loading users...</p>
        ) : (
          <div className="divide-y divide-border">
            {(users ?? []).map((u: AdminUser) => (
              <div key={u.id} className="flex items-center justify-between py-3 gap-4">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium truncate">{u.email}</span>
                    {u.is_admin && (
                      <span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded font-medium">
                        admin
                      </span>
                    )}
                    {u.id === currentUser.id && (
                      <span className="text-xs text-muted-foreground">(you)</span>
                    )}
                  </div>
                  <div className="text-xs text-muted-foreground mt-0.5">
                    {u.follow_count} follow{u.follow_count !== 1 ? "s" : ""} ·{" "}
                    joined {new Date(u.created_at).toLocaleDateString()}
                  </div>
                </div>
                {u.id !== currentUser.id && (
                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={() => toggleAdmin.mutate(u.id)}
                      disabled={toggleAdmin.isPending}
                      title={u.is_admin ? "Remove admin" : "Make admin"}
                      className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
                    >
                      {u.is_admin ? <ShieldOff className="w-4 h-4" /> : <ShieldCheck className="w-4 h-4" />}
                    </button>
                    {confirmDelete === u.id ? (
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => { deleteUser.mutate(u.id); setConfirmDelete(null); }}
                          className="text-xs px-2 py-1 bg-destructive text-destructive-foreground rounded hover:bg-destructive/90"
                        >
                          Confirm
                        </button>
                        <button
                          onClick={() => setConfirmDelete(null)}
                          className="text-xs px-2 py-1 bg-muted rounded hover:bg-accent"
                        >
                          Cancel
                        </button>
                      </div>
                    ) : (
                      <button
                        onClick={() => setConfirmDelete(u.id)}
                        title="Delete user"
                        className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-accent transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </section>

      {/* LLM Provider */}
      <section className="bg-card border border-border rounded-lg p-6 space-y-4">
        <h2 className="font-semibold flex items-center gap-2">
          <Cpu className="w-4 h-4" /> LLM Provider
        </h2>
        <p className="text-xs text-muted-foreground">
          Current: <strong>{settings?.llm_provider}</strong> / <strong>{settings?.llm_model}</strong>
        </p>
        <div className="space-y-2">
          {LLM_PROVIDERS.map(({ value, label, hint }) => (
            <label key={value} className="flex items-start gap-3 cursor-pointer">
              <input
                type="radio"
                name="provider"
                value={value}
                checked={settings?.llm_provider === value}
                onChange={() => updateSetting.mutate({ key: "llm_provider", value })}
                className="mt-0.5"
              />
              <div>
                <div className="text-sm font-medium">{label}</div>
                <div className="text-xs text-muted-foreground">{hint}</div>
              </div>
            </label>
          ))}
        </div>
        <div className="flex items-center gap-3 pt-2 border-t border-border">
          <button
            onClick={testLLM}
            disabled={testing}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 transition-colors"
          >
            <Play className="w-3.5 h-3.5" />
            {testing ? "Testing..." : "Test Connection"}
          </button>
          {testResult && (
            <div className="flex items-center gap-2 text-sm">
              {testResult.status === "ok" ? (
                <>
                  <CheckCircle className="w-4 h-4 text-green-500" />
                  <span className="text-green-600 dark:text-green-400">
                    {testResult.provider} — {testResult.summary_preview?.slice(0, 60)}...
                  </span>
                </>
              ) : (
                <>
                  <XCircle className="w-4 h-4 text-red-500" />
                  <span className="text-red-600 dark:text-red-400">{testResult.detail}</span>
                </>
              )}
            </div>
          )}
        </div>
      </section>

      {/* Data Sources */}
      <section className="bg-card border border-border rounded-lg p-6 space-y-4">
        <h2 className="font-semibold flex items-center gap-2">
          <RefreshCw className="w-4 h-4" /> Data Sources
        </h2>
        <div className="space-y-3 text-sm">
          <div className="flex items-center justify-between">
            <div>
              <div className="font-medium">Congress.gov Poll Interval</div>
              <div className="text-xs text-muted-foreground">How often to check for new bills</div>
            </div>
            <select
              value={settings?.congress_poll_interval_minutes}
              onChange={(e) => updateSetting.mutate({ key: "congress_poll_interval_minutes", value: e.target.value })}
              className="px-3 py-1.5 text-sm bg-background border border-border rounded-md"
            >
              <option value="15">Every 15 min</option>
              <option value="30">Every 30 min</option>
              <option value="60">Every hour</option>
              <option value="360">Every 6 hours</option>
            </select>
          </div>
          <div className="flex items-center justify-between py-2 border-t border-border">
            <div>
              <div className="font-medium">NewsAPI.org</div>
              <div className="text-xs text-muted-foreground">100 requests/day free tier</div>
            </div>
            <span className={`text-xs font-medium ${settings?.newsapi_enabled ? "text-green-500" : "text-muted-foreground"}`}>
              {settings?.newsapi_enabled ? "Configured" : "Not configured"}
            </span>
          </div>
          <div className="flex items-center justify-between py-2 border-t border-border">
            <div>
              <div className="font-medium">Google Trends</div>
              <div className="text-xs text-muted-foreground">Zeitgeist scoring via pytrends</div>
            </div>
            <span className={`text-xs font-medium ${settings?.pytrends_enabled ? "text-green-500" : "text-muted-foreground"}`}>
              {settings?.pytrends_enabled ? "Enabled" : "Disabled"}
            </span>
          </div>
        </div>
      </section>

      {/* Manual Controls */}
      <section className="bg-card border border-border rounded-lg p-6 space-y-4">
        <h2 className="font-semibold">Manual Controls</h2>
        <div className="flex flex-wrap gap-3">
          <button
            onClick={() => trigger("poll", adminAPI.triggerPoll)}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" /> Trigger Poll
          </button>
          <button
            onClick={() => trigger("members", adminAPI.triggerMemberSync)}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" /> Sync Members
          </button>
          <button
            onClick={() => trigger("trends", adminAPI.triggerTrendScores)}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" /> Calculate Trends
          </button>
        </div>
        {Object.entries(taskIds).map(([name, id]) => (
          <p key={name} className="text-xs text-muted-foreground">{name}: task {id} queued</p>
        ))}
      </section>
    </div>
  );
}
