"use client";

import { AlertCircle, Loader2, LogOut, Monitor, Trash2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { toast } from "sonner";

import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { useRouter } from "@/i18n/navigation";
import { authClient } from "@/lib/auth-client";

type Session = {
  id: string;
  token: string;
  expiresAt: Date | string;
  createdAt: Date | string;
  ipAddress?: string | null;
  userAgent?: string | null;
};

function parseUserAgent(
  ua: string | null | undefined,
  labels: {
    unknownDevice: string;
    unknownBrowser: string;
    unknownOs: string;
    deviceOn: (browser: string, os: string) => string;
  },
): string {
  if (!ua) return labels.unknownDevice;
  const browser = /Firefox/.test(ua)
    ? "Firefox"
    : /Edg\//.test(ua)
      ? "Edge"
      : /Chrome/.test(ua)
        ? "Chrome"
        : /Safari/.test(ua)
          ? "Safari"
          : labels.unknownBrowser;
  const os = /Mac OS X/.test(ua)
    ? "macOS"
    : /Windows/.test(ua)
      ? "Windows"
      : /Android/.test(ua)
        ? "Android"
        : /iPhone|iPad|iOS/.test(ua)
          ? "iOS"
          : /Linux/.test(ua)
            ? "Linux"
            : labels.unknownOs;
  return labels.deviceOn(browser, os);
}

export default function SettingsPage() {
  const router = useRouter();
  const t = useTranslations("Settings");
  const locale = useLocale();
  const dateLocale = locale === "fr" ? "fr-FR" : locale === "es" ? "es-ES" : "en-US";
  const dateFmt = new Intl.DateTimeFormat(dateLocale, { dateStyle: "short", timeStyle: "short" });

  // --- Password form ---
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [revokeOther, setRevokeOther] = useState(false);
  const [pwdLoading, setPwdLoading] = useState(false);
  const [pwdError, setPwdError] = useState<string | null>(null);

  async function handleChangePassword(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setPwdError(null);
    if (newPassword.length < 8) {
      setPwdError(t("password.errorTooShort"));
      return;
    }
    if (newPassword !== confirmPassword) {
      setPwdError(t("password.errorMismatch"));
      return;
    }
    setPwdLoading(true);
    const { error } = await authClient.changePassword({
      currentPassword,
      newPassword,
      revokeOtherSessions: revokeOther,
    });
    setPwdLoading(false);
    if (error) {
      const msg = error.message ?? t("password.errorFallback");
      setPwdError(msg);
      toast.error(msg);
      return;
    }
    toast.success(t("password.successToast"));
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    setRevokeOther(false);
    if (revokeOther) void loadSessions();
  }

  // --- Sessions ---
  const [sessions, setSessions] = useState<Session[] | null>(null);
  const [currentToken, setCurrentToken] = useState<string | null>(null);
  const [revokingId, setRevokingId] = useState<string | null>(null);

  async function loadSessions() {
    const [{ data: list }, { data: current }] = await Promise.all([
      authClient.listSessions(),
      authClient.getSession(),
    ]);
    setSessions((list as Session[] | null) ?? []);
    setCurrentToken(current?.session?.token ?? null);
  }

  useEffect(() => {
    void loadSessions();
  }, []);

  async function handleRevoke(session: Session) {
    setRevokingId(session.id);
    const { error } = await authClient.revokeSession({ token: session.token });
    setRevokingId(null);
    if (error) {
      toast.error(error.message ?? t("sessions.revokeError"));
      return;
    }
    toast.success(t("sessions.successToast"));
    if (session.token === currentToken) {
      router.push("/login");
      return;
    }
    void loadSessions();
  }

  // --- Delete account ---
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deletePassword, setDeletePassword] = useState("");
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);

  async function handleDelete() {
    setDeleteError(null);
    setDeleteLoading(true);
    const { error } = await authClient.deleteUser({ password: deletePassword });
    setDeleteLoading(false);
    if (error) {
      setDeleteError(error.message ?? t("danger.errorFallback"));
      return;
    }
    toast.success(t("danger.successToast"));
    setDeleteOpen(false);
    router.push("/login");
  }

  const uaLabels = {
    unknownDevice: t("sessions.unknownDevice"),
    unknownBrowser: t("sessions.unknownBrowser"),
    unknownOs: t("sessions.unknownOs"),
    deviceOn: (browser: string, os: string) => t("sessions.deviceOn", { browser, os }),
  };

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <h1 className="text-2xl font-semibold tracking-tight">{t("title")}</h1>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("password.title")}</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleChangePassword}>
            <FieldGroup>
              {pwdError ? (
                <Alert variant="destructive">
                  <AlertCircle />
                  <AlertDescription>{pwdError}</AlertDescription>
                </Alert>
              ) : null}
              <Field>
                <FieldLabel htmlFor="current-password">{t("password.currentLabel")}</FieldLabel>
                <Input
                  id="current-password"
                  type="password"
                  autoComplete="current-password"
                  required
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                />
              </Field>
              <Field>
                <FieldLabel htmlFor="new-password">{t("password.newLabel")}</FieldLabel>
                <Input
                  id="new-password"
                  type="password"
                  autoComplete="new-password"
                  required
                  minLength={8}
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                />
                <FieldDescription>{t("password.newHint")}</FieldDescription>
              </Field>
              <Field>
                <FieldLabel htmlFor="confirm-password">{t("password.confirmLabel")}</FieldLabel>
                <Input
                  id="confirm-password"
                  type="password"
                  autoComplete="new-password"
                  required
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                />
              </Field>
              <Field orientation="horizontal">
                <Checkbox
                  id="revoke-other"
                  checked={revokeOther}
                  onCheckedChange={(c) => setRevokeOther(c === true)}
                />
                <FieldLabel htmlFor="revoke-other" className="font-normal">
                  {t("password.revokeOthers")}
                </FieldLabel>
              </Field>
              <Field>
                <Button type="submit" disabled={pwdLoading} className="w-fit">
                  {pwdLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                  {t("password.submit")}
                </Button>
              </Field>
            </FieldGroup>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("sessions.title")}</CardTitle>
        </CardHeader>
        <CardContent>
          {sessions === null ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              {t("sessions.loading")}
            </div>
          ) : sessions.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("sessions.empty")}</p>
          ) : (
            <ul className="divide-y">
              {sessions.map((session) => {
                const isCurrent = session.token === currentToken;
                return (
                  <li
                    key={session.id}
                    className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0"
                  >
                    <div className="flex items-start gap-3">
                      <Monitor className="mt-0.5 h-4 w-4 text-muted-foreground" />
                      <div className="space-y-1 text-sm">
                        <div className="flex items-center gap-2 font-medium">
                          {parseUserAgent(session.userAgent, uaLabels)}
                          {isCurrent ? (
                            <Badge variant="secondary">{t("sessions.current")}</Badge>
                          ) : null}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {session.ipAddress ?? t("sessions.unknownIp")} · {t("sessions.createdOn")}{" "}
                          {dateFmt.format(new Date(session.createdAt))}
                        </div>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRevoke(session)}
                      disabled={revokingId === session.id}
                    >
                      {revokingId === session.id ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <LogOut className="h-4 w-4" />
                      )}
                      <span className="ml-2">{t("sessions.revoke")}</span>
                    </Button>
                  </li>
                );
              })}
            </ul>
          )}
        </CardContent>
      </Card>

      <Card className="border-destructive/50">
        <CardHeader>
          <CardTitle className="text-base text-destructive">{t("danger.title")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-muted-foreground">{t("danger.description")}</p>
          <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
            <AlertDialogTrigger asChild>
              <Button variant="destructive">
                <Trash2 className="mr-2 h-4 w-4" />
                {t("danger.deleteButton")}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t("danger.dialogTitle")}</AlertDialogTitle>
                <AlertDialogDescription>{t("danger.dialogDescription")}</AlertDialogDescription>
              </AlertDialogHeader>
              <div className="space-y-2">
                <FieldLabel htmlFor="delete-password">{t("danger.passwordLabel")}</FieldLabel>
                <Input
                  id="delete-password"
                  type="password"
                  autoComplete="current-password"
                  value={deletePassword}
                  onChange={(e) => setDeletePassword(e.target.value)}
                />
                {deleteError ? (
                  <Alert variant="destructive">
                    <AlertCircle />
                    <AlertDescription>{deleteError}</AlertDescription>
                  </Alert>
                ) : null}
              </div>
              <AlertDialogFooter>
                <AlertDialogCancel disabled={deleteLoading}>{t("danger.cancel")}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={(e) => {
                    e.preventDefault();
                    void handleDelete();
                  }}
                  disabled={deleteLoading || deletePassword.length === 0}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  {deleteLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                  {t("danger.confirmDelete")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </CardContent>
      </Card>
    </div>
  );
}
