import { createFileRoute, Link, useRouter } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { supabase } from "@/integrations/supabase/client";
import { GlassCard, SectionLabel } from "@/components/GlassCard";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { toast } from "sonner";
import { useTheme, type Theme } from "@/lib/theme";
import { seedDemoData, clearAllData } from "@/lib/ai.functions";
import { exportUserData } from "@/lib/account.functions";
import { DeleteAccountDialog } from "@/components/legal/DeleteAccountDialog";
import {
  ArrowLeft, Bell, Brain, ChevronRight, Database, Download, LineChart, Lock, LogOut, Moon, Palette,
  Shield, Sparkles, Sun, Trash2, MonitorSmartphone, Sparkle,
  FileText, Scale, ShieldAlert, ShieldCheck, LifeBuoy, BarChart3, Megaphone, UserX,
} from "lucide-react";
import { useState } from "react";

export const Route = createFileRoute("/_authenticated/settings")({
  head: () => ({
    meta: [
      { title: "Settings — PRUDENTIA" },
      { name: "description", content: "Appearance, notifications, AI, privacy and data controls for PRUDENTIA." },
      { property: "og:title", content: "Settings — PRUDENTIA" },
      { property: "og:description", content: "Fine-tune your PRUDENTIA experience." },
    ],
  }),
  component: SettingsPage,
});

type Prefs = Record<string, any>;

const DEFAULT_PREFS: Prefs = {
  alerts_budget: true,
  alerts_goal: true,
  alerts_story: true,
  coach_depth: "balanced",
  coach_tone: "calm",
  coach_numbers: true,
  proactive_insights: true,
  privacy_ai_context: true,
  privacy_analytics: true,
  privacy_ads: true,
};

function SettingsPage() {
  const { user } = Route.useRouteContext();
  const router = useRouter();
  const qc = useQueryClient();
  const { theme, setTheme } = useTheme();
  const seedFn = useServerFn(seedDemoData);
  const clearFn = useServerFn(clearAllData);
  const [seeding, setSeeding] = useState(false);
  const [clearing, setClearing] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const exportFn = useServerFn(exportUserData);

  const profileQ = useQuery({
    queryKey: ["profile", user.id],
    queryFn: async () => (await supabase.from("profiles").select("*").eq("id", user.id).single()).data,
  });
  const prefs: Prefs = { ...DEFAULT_PREFS, ...((profileQ.data as any)?.preferences ?? {}) };

  async function setPref(key: string, value: any) {
    const next = { ...prefs, [key]: value };
    qc.setQueryData(["profile", user.id], (old: any) => (old ? { ...old, preferences: next } : old));
    const { error } = await supabase.from("profiles").update({ preferences: next }).eq("id", user.id);
    if (error) {
      toast.error(error.message);
      qc.invalidateQueries({ queryKey: ["profile", user.id] });
    }
  }

  async function loadDemo() {
    setSeeding(true);
    try {
      const res = await seedFn();
      toast.success(`Loaded ${res.transactions} sample transactions`);
      qc.invalidateQueries();
    } catch (e: any) {
      toast.error(e.message ?? "Failed");
    } finally { setSeeding(false); }
  }
  async function clearAll() {
    if (!confirm("Delete all your transactions, budgets, goals, decisions, and chats? This cannot be undone.")) return;
    setClearing(true);
    try {
      await clearFn();
      toast.success("Cleared");
      qc.invalidateQueries();
    } catch (e: any) {
      toast.error(e.message ?? "Failed");
    } finally { setClearing(false); }
  }
  async function exportData() {
    setExporting(true);
    try {
      const payload = await exportFn();
      const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `prudentia-data-export-${new Date().toISOString().slice(0, 10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
      toast.success("Your data export has been downloaded");
    } catch (e: any) {
      toast.error(e?.message ?? "Export failed");
    } finally { setExporting(false); }
  }
  async function resetPassword() {
    if (!user.email) return;
    const { error } = await supabase.auth.resetPasswordForEmail(user.email, { redirectTo: `${window.location.origin}/auth` });
    if (error) return toast.error(error.message);
    toast.success("Password reset link sent");
  }
  async function signOut() {
    await supabase.auth.signOut();
    qc.clear();
    router.navigate({ to: "/auth" });
  }

  return (
    <div className="px-4 pt-8 pb-8 space-y-5">
      <header className="flex items-center gap-3 px-1">
        <Link to="/profile" className="size-9 rounded-full glass grid place-items-center" aria-label="Back">
          <ArrowLeft className="size-4" />
        </Link>
        <div>
          <p className="text-[11px] text-muted-foreground uppercase tracking-widest">Preferences</p>
          <h1 className="text-2xl font-semibold">Settings</h1>
        </div>
      </header>

      {/* Appearance */}
      <SectionLabel>Appearance</SectionLabel>
      <GlassCard>
        <div className="flex items-center gap-2 mb-3 text-muted-foreground">
          <Palette className="size-4" />
          <p className="text-sm font-medium text-foreground">Theme</p>
        </div>
        <div className="grid grid-cols-3 gap-2">
          <ThemeOption current={theme} value="dark" label="Dark" icon={Moon} onClick={setTheme} />
          <ThemeOption current={theme} value="light" label="Light" icon={Sun} onClick={setTheme} />
          <ThemeOption current={theme} value="system" label="System" icon={MonitorSmartphone} onClick={setTheme} />
        </div>
        <p className="text-[11px] text-muted-foreground mt-3">Your preference is saved on this device.</p>
      </GlassCard>

      {/* Alerts */}
      <SectionLabel>Alerts</SectionLabel>
      <GlassCard className="divide-y divide-white/5 p-0 overflow-hidden">
        <ToggleRow icon={Bell} label="Budget warnings" hint="Flag categories that pass their alert threshold" checked={prefs.alerts_budget} onChange={(v) => setPref("alerts_budget", v)} />
        <ToggleRow icon={Bell} label="Goal milestones" hint="Celebrate 25 / 50 / 75 / 100% progress" checked={prefs.alerts_goal} onChange={(v) => setPref("alerts_goal", v)} />
        <ToggleRow icon={Bell} label="Weekly money story" hint="Generate a narrative recap each week" checked={prefs.alerts_story} onChange={(v) => setPref("alerts_story", v)} />
      </GlassCard>

      {/* AI */}
      <SectionLabel>AI coaching</SectionLabel>
      <GlassCard className="space-y-4">
        <div className="flex items-center gap-2 text-muted-foreground">
          <Brain className="size-4" />
          <p className="text-sm font-medium text-foreground">How PRUDENTIA talks to you</p>
        </div>
        <PrefChoice
          label="Answer depth"
          value={prefs.coach_depth}
          options={[{ v: "brief", l: "Brief" }, { v: "balanced", l: "Balanced" }, { v: "detailed", l: "Detailed" }]}
          onChange={(v) => setPref("coach_depth", v)}
        />
        <PrefChoice
          label="Tone"
          value={prefs.coach_tone}
          options={[{ v: "calm", l: "Calm" }, { v: "encouraging", l: "Encouraging" }, { v: "direct", l: "Direct" }]}
          onChange={(v) => setPref("coach_tone", v)}
        />
        <div className="divide-y divide-white/5 -mx-5">
          <ToggleRow icon={Sparkles} label="Lead with numbers" hint="Back every answer with your real figures" checked={prefs.coach_numbers} onChange={(v) => setPref("coach_numbers", v)} />
          <ToggleRow icon={Sparkles} label="Proactive insights" hint="Let PRUDENTIA surface recommendations unprompted" checked={prefs.proactive_insights} onChange={(v) => setPref("proactive_insights", v)} />
        </div>
      </GlassCard>

      {/* Privacy & security */}
      <SectionLabel>Privacy & security</SectionLabel>
      <GlassCard className="divide-y divide-white/5 p-0 overflow-hidden">
        <ToggleRow icon={Shield} label="Share context with AI" hint="Off means PRUDENTIA answers generically, without your data" checked={prefs.privacy_ai_context} onChange={(v) => setPref("privacy_ai_context", v)} />
        <ToggleRow icon={BarChart3} label="Product analytics" hint="Anonymous usage and stability diagnostics" checked={prefs.privacy_analytics} onChange={(v) => setPref("privacy_analytics", v)} />
        <ToggleRow icon={Megaphone} label="Personalised advertising" hint="Ads are off today; this applies if they arrive on Free" checked={prefs.privacy_ads} onChange={(v) => setPref("privacy_ads", v)} />
        <button onClick={exportData} disabled={exporting} className="w-full text-left">
          <RowInner icon={Download} label="Export my data" hint={exporting ? "Preparing…" : "Download JSON"} />
        </button>
        <button onClick={resetPassword} className="w-full text-left">
          <RowInner icon={Lock} label="Reset password" hint="Email me a link" />
        </button>
      </GlassCard>

      {/* Data */}
      <SectionLabel>Data</SectionLabel>
      <GlassCard className="space-y-3">
        <div className="flex items-center gap-2 text-muted-foreground">
          <Database className="size-4" />
          <p className="text-sm font-medium text-foreground">Sample dataset</p>
        </div>
        <p className="text-[12px] text-muted-foreground leading-relaxed">Load ~90 days of realistic transactions, budgets and goals so you can explore charts and AI insights. Replaces existing rows.</p>
        <div className="grid grid-cols-2 gap-2">
          <Button onClick={loadDemo} disabled={seeding} className="rounded-full bg-gradient-to-br from-electric to-purple text-primary-foreground">
            <Sparkles className="size-4 mr-2" /> {seeding ? "Loading…" : "Load sample data"}
          </Button>
          <Button onClick={clearAll} disabled={clearing} variant="outline" className="rounded-full bg-white/5 border-white/10 text-destructive">
            <Trash2 className="size-4 mr-2" /> {clearing ? "Clearing…" : "Clear all data"}
          </Button>
        </div>
      </GlassCard>

      {/* Legal */}
      <SectionLabel>Legal</SectionLabel>
      <GlassCard className="divide-y divide-white/5 p-0 overflow-hidden">
        <Link to="/legal/privacy"><RowInner icon={ShieldCheck} label="Privacy Policy" hint="What we collect" /></Link>
        <Link to="/legal/terms"><RowInner icon={Scale} label="Terms of Service" hint="Your agreement" /></Link>
        <Link to="/legal/disclaimer"><RowInner icon={ShieldAlert} label="Financial Disclaimer" hint="Limits of AI guidance" /></Link>
        <Link to="/legal/licenses"><RowInner icon={FileText} label="Licenses" hint="Open source" /></Link>
      </GlassCard>

      {/* Help */}
      <SectionLabel>Help &amp; support</SectionLabel>
      <GlassCard className="divide-y divide-white/5 p-0 overflow-hidden">
        <Link to="/support"><RowInner icon={LifeBuoy} label="Help & Support" hint="FAQ & contact" /></Link>
        <Link to="/delete-account"><RowInner icon={Trash2} label="Account deletion help" hint="How it works" /></Link>
      </GlassCard>

      {/* Account */}
      <SectionLabel>Account</SectionLabel>
      <GlassCard className="space-y-3">
        <div className="flex items-center gap-2 text-muted-foreground">
          <UserX className="size-4" />
          <p className="text-sm font-medium text-foreground">Delete account</p>
        </div>
        <p className="text-[12px] text-muted-foreground leading-relaxed">
          Permanently erases your profile, transactions, budgets, goals, receipts, AI history and login. This cannot be undone —
          export your data first if you want a copy, and cancel any paid plan so it does not renew.
        </p>
        <Button onClick={() => setDeleteOpen(true)} variant="outline" className="w-full rounded-full bg-white/5 border-white/10 text-destructive">
          <Trash2 className="size-4 mr-2" /> Delete my account
        </Button>
      </GlassCard>
      <DeleteAccountDialog open={deleteOpen} onOpenChange={setDeleteOpen} />

      <SectionLabel>More</SectionLabel>
      <GlassCard className="divide-y divide-white/5 p-0 overflow-hidden">
        <Link to="/analytics"><RowInner icon={LineChart} label="Analytics" hint="Breakdowns & trends" /></Link>
        <Link to="/profile"><RowInner icon={Sparkle} label="Subscription" hint="Manage on Profile" /></Link>
        <Link to="/profile"><RowInner icon={Download} label="Export data" hint="Manage on Profile" /></Link>
      </GlassCard>

      <Button onClick={signOut} variant="outline" className="w-full rounded-full bg-white/5 border-white/10 text-destructive">
        <LogOut className="size-4 mr-2" /> Sign out
      </Button>

      <p className="text-center text-[10px] text-muted-foreground pt-2">Signed in as {user.email}</p>
    </div>
  );
}

function ThemeOption({ current, value, label, icon: Icon, onClick }: { current: Theme; value: Theme; label: string; icon: any; onClick: (v: Theme) => void }) {
  const active = current === value;
  return (
    <button
      onClick={() => onClick(value)}
      className={`rounded-2xl py-3 flex flex-col items-center gap-1.5 transition-all ${
        active ? "bg-gradient-to-br from-electric to-purple text-primary-foreground glow-electric" : "bg-white/5 border border-white/10 hover:bg-white/10"
      }`}
      aria-pressed={active}
    >
      <Icon className="size-4" />
      <span className="text-xs font-medium">{label}</span>
    </button>
  );
}

function RowInner({ icon: Icon, label, hint }: { icon: any; label: string; hint?: string }) {
  return (
    <div className="flex items-center justify-between px-4 py-3.5">
      <div className="flex items-center gap-3">
        <Icon className="size-4 text-muted-foreground" />
        <p className="text-sm font-medium">{label}</p>
      </div>
      <div className="flex items-center gap-2 text-muted-foreground">
        {hint && <span className="text-[11px]">{hint}</span>}
        <ChevronRight className="size-4" />
      </div>
    </div>
  );
}

function ToggleRow({ icon: Icon, label, hint, checked, onChange }: { icon: any; label: string; hint?: string; checked: boolean; onChange: (v: boolean) => void }) {
  return (
    <div className="flex items-center justify-between gap-3 px-5 py-3.5">
      <div className="flex items-start gap-3 min-w-0">
        <Icon className="size-4 text-muted-foreground mt-0.5 shrink-0" />
        <div className="min-w-0">
          <p className="text-sm font-medium">{label}</p>
          {hint && <p className="text-[11px] text-muted-foreground mt-0.5">{hint}</p>}
        </div>
      </div>
      <Switch checked={!!checked} onCheckedChange={onChange} aria-label={label} />
    </div>
  );
}

function PrefChoice({ label, value, options, onChange }: { label: string; value: string; options: { v: string; l: string }[]; onChange: (v: string) => void }) {
  return (
    <div>
      <p className="text-[11px] text-muted-foreground mb-1.5">{label}</p>
      <div className="grid grid-cols-3 gap-2">
        {options.map((o) => (
          <button
            key={o.v}
            onClick={() => onChange(o.v)}
            aria-pressed={value === o.v}
            className={`rounded-2xl py-2 text-xs font-medium transition-all ${
              value === o.v ? "bg-gradient-to-br from-electric to-purple text-primary-foreground" : "bg-white/5 border border-white/10 hover:bg-white/10"
            }`}
          >
            {o.l}
          </button>
        ))}
      </div>
    </div>
  );
}
