import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { Sun, Moon, Monitor, Bell, Globe, Sparkles, Trash2, Save } from "lucide-react";
import { PageHeader } from "@/components/common/PageBits";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { usePrefsStore } from "@/store";
import { toast } from "sonner";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/_app/settings")({
  head: () => ({ meta: [{ title: "Settings — Study Unique" }] }),
  component: SettingsPage,
});

function SettingsPage() {
  const theme = usePrefsStore((s) => s.theme);
  const setTheme = usePrefsStore((s) => s.setTheme);
  const density = usePrefsStore((s) => s.density);
  const setDensity = usePrefsStore((s) => s.setDensity);

  const [notifPush, setNotifPush] = useState(true);
  const [notifEmail, setNotifEmail] = useState(true);
  const [notifStreak, setNotifStreak] = useState(true);

  useEffect(() => {
    if (typeof document !== "undefined") {
      document.documentElement.classList.toggle("dark", theme === "dark");
    }
  }, [theme]);

  return (
    <div className="mx-auto w-full max-w-4xl space-y-6 p-4 md:p-6">
      <PageHeader title="Settings" description="Personalize Study Unique to your workflow." />

      <Tabs defaultValue="appearance">
        <TabsList>
          <TabsTrigger value="appearance">Appearance</TabsTrigger>
          <TabsTrigger value="notifications">Notifications</TabsTrigger>
          <TabsTrigger value="account">Account</TabsTrigger>
          <TabsTrigger value="ai">AI</TabsTrigger>
        </TabsList>

        <TabsContent value="appearance" className="mt-4 space-y-4">
          <Card title="Theme" description="Dark mode is on by default. Choose what suits you.">
            <div className="grid grid-cols-3 gap-3">
              {([
                ["light", "Light", Sun],
                ["dark", "Dark", Moon],
              ] as const).map(([v, label, Icon]) => (
                <button
                  key={v}
                  onClick={() => setTheme(v)}
                  className={cn(
                    "flex flex-col items-center gap-2 rounded-xl border-2 p-4 transition-colors",
                    theme === v ? "border-primary bg-primary/5" : "border-border hover:border-primary/40",
                  )}
                >
                  <Icon className="h-5 w-5" />
                  <span className="text-sm font-medium">{label}</span>
                </button>
              ))}
              <button
                disabled
                className="flex cursor-not-allowed flex-col items-center gap-2 rounded-xl border-2 border-border p-4 opacity-50"
              >
                <Monitor className="h-5 w-5" />
                <span className="text-sm font-medium">System</span>
              </button>
            </div>
          </Card>

          <Card title="Density" description="Choose how compact the interface feels.">
            <Select value={density} onValueChange={(v) => setDensity(v as "comfortable" | "compact")}>
              <SelectTrigger className="w-[220px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="comfortable">Comfortable</SelectItem>
                <SelectItem value="compact">Compact</SelectItem>
              </SelectContent>
            </Select>
          </Card>
        </TabsContent>

        <TabsContent value="notifications" className="mt-4 space-y-4">
          <Card title="Channels" description="Pick how we should reach you.">
            <Row icon={Bell} label="Push notifications" hint="Browser and mobile push.">
              <Switch checked={notifPush} onCheckedChange={setNotifPush} />
            </Row>
            <Separator />
            <Row icon={Bell} label="Email digests" hint="Weekly recap & study insights.">
              <Switch checked={notifEmail} onCheckedChange={setNotifEmail} />
            </Row>
            <Separator />
            <Row icon={Sparkles} label="Streak reminders" hint="Don't break the streak!">
              <Switch checked={notifStreak} onCheckedChange={setNotifStreak} />
            </Row>
          </Card>
        </TabsContent>

        <TabsContent value="account" className="mt-4 space-y-4">
          <Card title="Account info">
            <div className="grid gap-3 md:grid-cols-2">
              <div className="space-y-1.5">
                <Label className="text-xs">Display name</Label>
                <Input defaultValue="Alex Morgan" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Email</Label>
                <Input type="email" defaultValue="alex@studyunique.app" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Language</Label>
                <Select defaultValue="en">
                  <SelectTrigger>
                    <Globe className="mr-1.5 h-3.5 w-3.5" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="en">English</SelectItem>
                    <SelectItem value="es">Español</SelectItem>
                    <SelectItem value="fr">Français</SelectItem>
                    <SelectItem value="ja">日本語</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Timezone</Label>
                <Select defaultValue="utc">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="utc">UTC</SelectItem>
                    <SelectItem value="pst">Pacific (PST)</SelectItem>
                    <SelectItem value="cet">Central Europe (CET)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <Button onClick={() => toast.success("Saved")} className="mt-4 gradient-brand text-primary-foreground">
              <Save className="mr-1.5 h-4 w-4" /> Save
            </Button>
          </Card>

          <Card title="Danger zone" description="Permanent actions. Please be careful.">
            <Button
              variant="outline"
              className="border-destructive/30 text-destructive hover:bg-destructive/10"
              onClick={() => toast.warning("Account would be deleted in production")}
            >
              <Trash2 className="mr-1.5 h-4 w-4" /> Delete account
            </Button>
          </Card>
        </TabsContent>

        <TabsContent value="ai" className="mt-4 space-y-4">
          <Card title="AI model" description="Choose the default model for chat and generation.">
            <Select defaultValue="balanced">
              <SelectTrigger className="w-[260px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="fast">Fast — instant replies</SelectItem>
                <SelectItem value="balanced">Balanced — recommended</SelectItem>
                <SelectItem value="deep">Deep — best quality</SelectItem>
              </SelectContent>
            </Select>
          </Card>
          <Card title="Response style">
            <Row icon={Sparkles} label="Concise answers" hint="Prefer short, focused replies.">
              <Switch defaultChecked />
            </Row>
            <Separator />
            <Row icon={Sparkles} label="Show sources" hint="Always cite the document a fact came from.">
              <Switch defaultChecked />
            </Row>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function Card({
  title,
  description,
  children,
}: {
  title: string;
  description?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-border bg-card p-5">
      <div>
        <p className="text-sm font-semibold">{title}</p>
        {description && <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>}
      </div>
      <div className="mt-4 space-y-2">{children}</div>
    </div>
  );
}

function Row({
  icon: Icon,
  label,
  hint,
  children,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center justify-between gap-3 py-1.5">
      <div className="flex items-start gap-3">
        <div className="mt-0.5 flex h-8 w-8 items-center justify-center rounded-md bg-muted">
          <Icon className="h-4 w-4 text-muted-foreground" />
        </div>
        <div>
          <p className="text-sm font-medium">{label}</p>
          {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
        </div>
      </div>
      {children}
    </div>
  );
}
