import { useEffect, useState } from "react";
import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import {
  Loader2,
  Moon,
  Sun,
  Languages,
  LogOut,
  Trash2,
  
  Mail,
  Settings2,
  Save,
} from "lucide-react";
import { AppShell } from "@/components/AppShell";
import { AvatarUploader } from "@/components/AvatarUploader";
import { PageHeader } from "@/components/PageHeader";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useAuth } from "@/hooks/useAuth";
import { useSettings, useT } from "@/hooks/useSettings";
import { useBriefing } from "@/hooks/useBriefing";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export const Route = createFileRoute("/profile")({
  head: () => ({
    meta: [
      { title: "Profile & Settings — The Daily Ledger" },
      {
        name: "description",
        content:
          "Manage your account, preferences, theme and language for The Daily Ledger.",
      },
    ],
  }),
  component: ProfilePage,
});

function ProfilePage() {
  const { user, loading, signOut } = useAuth();
  const { theme, lang, toggleTheme } = useSettings();
  const t = useT();
  const navigate = useNavigate();
  const { hotel } = useBriefing({ skipBriefing: true });
  const [deleteOpen, setDeleteOpen] = useState(false);

  async function handleSignOut() {
    await signOut();
    navigate({ to: "/login" });
  }

  if (loading) {
    return (
      <div className="flex min-h-dvh items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <AppShell hotel={hotel ?? null} isLoading={false} onRefresh={() => {}}>
      <PageHeader
        eyebrow={lang === "zh" ? "个人资料" : "Profile"}
        title={lang === "zh" ? "账户与设置" : "Account & settings"}
        subtitle={
          lang === "zh"
            ? "管理您的账户、外观和语言偏好。"
            : "Manage your account, appearance, and language preferences."
        }
      />

      <div className="space-y-6">
        {/* Account card */}
        <section className="rounded-2xl border bg-card/60 p-5 shadow-[var(--shadow-elegant)] backdrop-blur-sm">
          <div className="mb-5">
            <div className="font-serif text-lg font-semibold text-foreground">
              {lang === "zh" ? "您的账户" : "Your account"}
            </div>
            <div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="h-3 w-3" />
              <span className="truncate">{user?.email ?? "—"}</span>
            </div>
          </div>

          <AvatarUploader
            userId={user?.id ?? null}
            email={user?.email ?? null}
            displayName=""
            lang={lang}
          />

          <div className="mt-5">
            <UsernameEditor userId={user?.id ?? null} lang={lang} />
          </div>

          <div className="mt-4 flex flex-wrap gap-2">
            <Button variant="outline" size="sm" onClick={handleSignOut} className="gap-2">
              <LogOut className="h-4 w-4" />
              {t("shell.signOut")}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setDeleteOpen(true)}
              className="gap-2 text-destructive hover:text-destructive"
            >
              <Trash2 className="h-4 w-4" />
              {t("shell.deleteAccount")}
            </Button>
          </div>
        </section>

        {/* Preferences card */}
        <section className="rounded-2xl border bg-card/60 p-5 shadow-[var(--shadow-elegant)] backdrop-blur-sm">
          <div className="mb-4 flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-soft text-brand">
              <Settings2 className="h-5 w-5" />
            </div>
            <div>
              <div className="font-serif text-lg font-semibold text-foreground">
                {lang === "zh" ? "偏好设置" : "Preferences"}
              </div>
              <div className="text-xs text-muted-foreground">
                {lang === "zh"
                  ? "外观和语言会在所有设备上同步。"
                  : "Appearance and language sync across your devices."}
              </div>
            </div>
          </div>

          <div className="grid gap-3 sm:grid-cols-2">
            <PreferenceRow
              title={lang === "zh" ? "主题" : "Theme"}
              value={
                theme === "dark"
                  ? lang === "zh"
                    ? "深色"
                    : "Dark"
                  : lang === "zh"
                    ? "浅色"
                    : "Light"
              }
              action={
                <Button variant="outline" size="sm" onClick={toggleTheme} className="gap-2">
                  {theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
                  {theme === "dark" ? t("shell.theme.light") : t("shell.theme.dark")}
                </Button>
              }
            />
          </div>
        </section>

        {hotel ? (
          <section className="rounded-2xl border bg-card/60 p-5 shadow-[var(--shadow-elegant)] backdrop-blur-sm">
            <div className="mb-3 font-serif text-lg font-semibold text-foreground">
              {lang === "zh" ? "当前酒店" : "Current property"}
            </div>
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="min-w-0">
                <div className="truncate font-medium">{hotel.hotel_name}</div>
                <div className="truncate text-xs text-muted-foreground">{hotel.location}</div>
              </div>
              <Button asChild variant="outline" size="sm">
                <Link to="/onboarding" search={{ hotelId: hotel.id } as never}>
                  {t("shell.editHotel")}
                </Link>
              </Button>
            </div>
          </section>
        ) : null}
      </div>

      <DeleteAccountDialog open={deleteOpen} onOpenChange={setDeleteOpen} />
    </AppShell>
  );
}

function PreferenceRow({
  title,
  value,
  action,
}: {
  title: string;
  value: string;
  action: React.ReactNode;
}) {
  return (
    <div className="flex items-center justify-between gap-3 rounded-xl border bg-background/60 px-4 py-3">
      <div className="min-w-0">
        <div className="text-[10px] uppercase tracking-wider text-muted-foreground">
          {title}
        </div>
        <div className="truncate text-sm font-medium text-foreground">{value}</div>
      </div>
      {action}
    </div>
  );
}

function DeleteAccountDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const t = useT();
  const navigate = useNavigate();
  const { signOut } = useAuth();
  const [confirm, setConfirm] = useState("");
  const [busy, setBusy] = useState(false);

  async function handleDelete() {
    setBusy(true);
    try {
      const { error } = await supabase.rpc("delete_my_account");
      if (error) throw error;
      toast.success("Account deleted");
      await signOut();
      navigate({ to: "/login" });
    } catch (err) {
      toast.error("Couldn't delete account", { description: (err as Error).message });
    } finally {
      setBusy(false);
      onOpenChange(false);
      setConfirm("");
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="text-destructive">{t("delete.title")}</DialogTitle>
          <DialogDescription>{t("delete.body")}</DialogDescription>
        </DialogHeader>
        <div className="grid gap-2">
          <label className="text-xs font-medium text-muted-foreground">
            {t("delete.confirm")}
          </label>
          <Input
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            placeholder="DELETE"
            autoComplete="off"
          />
        </div>
        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
            {t("delete.cancel")}
          </Button>
          <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={busy || confirm !== "DELETE"}
            className="gap-2"
          >
            {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
            {t("delete.cta")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function UsernameEditor({ userId, lang }: { userId: string | null; lang: "en" | "zh" }) {
  const [name, setName] = useState("");
  const [initial, setInitial] = useState("");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!userId) return;
    let cancelled = false;
    supabase
      .from("user_preferences")
      .select("display_name")
      .eq("user_id", userId)
      .maybeSingle()
      .then(({ data }) => {
        if (cancelled) return;
        const v = (data?.display_name as string | null) ?? "";
        setName(v);
        setInitial(v);
      });
    return () => {
      cancelled = true;
    };
  }, [userId]);

  const dirty = name.trim() !== initial.trim();

  async function handleSave() {
    if (!userId) return;
    setBusy(true);
    try {
      const { error } = await supabase
        .from("user_preferences")
        .upsert(
          { user_id: userId, display_name: name.trim() || null },
          { onConflict: "user_id" },
        );
      if (error) throw error;
      setInitial(name.trim());
      toast.success(lang === "zh" ? "已保存" : "Saved");
    } catch (err) {
      toast.error(lang === "zh" ? "保存失败" : "Couldn't save", {
        description: (err as Error).message,
      });
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="grid gap-2">
      <label className="text-[10px] uppercase tracking-wider text-muted-foreground">
        {lang === "zh" ? "用户名" : "Username"}
      </label>
      <div className="flex gap-2">
        <Input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder={lang === "zh" ? "输入您的姓名" : "Enter your name"}
          maxLength={80}
          className="flex-1"
        />
        <Button
          size="sm"
          onClick={handleSave}
          disabled={!dirty || busy || !userId}
          className="gap-2"
        >
          {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
          {lang === "zh" ? "保存" : "Save"}
        </Button>
      </div>
    </div>
  );
}
