"use client";

import Link from "next/link";
import {
  Moon,
  Languages,
  BellRing,
  Megaphone,
  KeyRound,
  Info,
  FileText,
  ShieldQuestion,
  Lock,
  Mail,
  ChevronRight,
} from "lucide-react";
import { useState } from "react";
import { TopBar } from "@/components/ui/TopBar";
import { GlassCard } from "@/components/ui/GlassCard";
import { ThemeToggle } from "@/components/ui/ThemeToggle";
import { Switch } from "@/components/ui/Switch";
import { useTranslation } from "@/lib/i18n/LanguageProvider";
import { useAuth } from "@/lib/auth/auth-provider";
import { apiPost } from "@/lib/api/client";
import { useSettings } from "@/lib/data/settings-provider";
import { Language } from "@/lib/i18n/translations";
import { cn } from "@/lib/cn";

export default function SettingsPage() {
  const { language, setLanguage, t } = useTranslation();
  const { user } = useAuth();
  const { settings } = useSettings();
  const [orderUpdates, setOrderUpdates] = useState(true);
  const [promotions, setPromotions] = useState(false);

  function handleLanguageChange(lang: Language) {
    setLanguage(lang);
    // Settings is a protected route — user is always present here —
    // but guard anyway rather than assume.
    if (user) {
      apiPost("/api/auth/preferences", { languagePreference: lang }).catch(() => {
        // Non-critical — the local language change already applied either way.
      });
    }
  }

  const SUPPORT_LINKS = [
    { label: t("settings.aboutSharedNet"), icon: Info, href: "/about" },
    { label: t("settings.helpCenter"), icon: ShieldQuestion, href: "/help" },
    { label: t("settings.termsOfService"), icon: FileText, href: "/terms" },
    { label: t("settings.privacyPolicy"), icon: Lock, href: "/privacy" },
    { label: t("settings.contactUs"), icon: Mail, href: "/contact" },
  ];

  return (
    <div className="flex flex-1 flex-col">
      <TopBar title={t("settings.title")} />

      <div className="flex flex-1 flex-col gap-6 px-4 pb-8 pt-2">
        <section>
          <p className="mb-3 text-sm font-medium text-muted">{t("settings.appearance")}</p>
          <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
            <div className="flex items-center gap-3 px-3 py-3.5">
              <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                <Moon size={16} strokeWidth={2} className="text-muted" />
              </span>
              <span className="flex-1 text-sm font-medium">{t("settings.darkMode")}</span>
              <ThemeToggle />
            </div>

            <div className="flex items-center gap-3 px-3 py-3.5">
              <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                <Languages size={16} strokeWidth={2} className="text-muted" />
              </span>
              <span className="flex-1 text-sm font-medium">{t("settings.language")}</span>
              <div className="flex rounded-full bg-black/5 p-1 dark:bg-white/5">
                {(["en", "ur"] as Language[]).map((l) => (
                  <button
                    key={l}
                    onClick={() => handleLanguageChange(l)}
                    className={cn(
                      "rounded-full px-3 py-1 text-xs font-semibold transition-colors",
                      language === l
                        ? "bg-gold text-ink"
                        : "text-muted"
                    )}
                  >
                    {l === "en" ? "English" : "اردو"}
                  </button>
                ))}
              </div>
            </div>
          </GlassCard>
        </section>

        <section>
          <p className="mb-3 text-sm font-medium text-muted">{t("settings.account")}</p>
          <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
            <Link
              href="/change-password"
              className="flex items-center gap-3 px-3 py-3.5 first:rounded-t-3xl last:rounded-b-3xl active:bg-black/5 dark:active:bg-white/5"
            >
              <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                <KeyRound size={16} strokeWidth={2} className="text-muted" />
              </span>
              <span className="flex-1 text-sm font-medium">{t("settings.changePassword")}</span>
              <ChevronRight size={16} className="text-muted" />
            </Link>
          </GlassCard>
        </section>

        <section>
          <p className="mb-3 text-sm font-medium text-muted">{t("settings.notifications")}</p>
          <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
            <div className="flex items-center gap-3 px-3 py-3.5">
              <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                <BellRing size={16} strokeWidth={2} className="text-muted" />
              </span>
              <div className="flex-1">
                <p className="text-sm font-medium">{t("settings.orderUpdates")}</p>
                <p className="text-xs text-muted">{t("settings.orderUpdatesDesc")}</p>
              </div>
              <Switch checked={orderUpdates} onChange={setOrderUpdates} label="Order updates" />
            </div>
            <div className="flex items-center gap-3 px-3 py-3.5">
              <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                <Megaphone size={16} strokeWidth={2} className="text-muted" />
              </span>
              <div className="flex-1">
                <p className="text-sm font-medium">{t("settings.promotions")}</p>
                <p className="text-xs text-muted">{t("settings.promotionsDesc")}</p>
              </div>
              <Switch checked={promotions} onChange={setPromotions} label="Promotions" />
            </div>
          </GlassCard>
        </section>

        <section>
          <p className="mb-3 text-sm font-medium text-muted">{t("settings.support")}</p>
          <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
            {SUPPORT_LINKS.map(({ label, icon: Icon, href }) => (
              <Link
                key={label}
                href={href}
                className="flex items-center gap-3 px-3 py-3.5 active:bg-black/5 dark:active:bg-white/5"
              >
                <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
                  <Icon size={16} strokeWidth={2} className="text-muted" />
                </span>
                <span className="flex-1 text-sm font-medium">{label}</span>
                <ChevronRight size={16} className="text-muted" />
              </Link>
            ))}
          </GlassCard>
        </section>

        <p className="pb-2 text-center text-xs text-muted">{settings.businessName} &middot; v{settings.appVersion}</p>
      </div>
    </div>
  );
}
