import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader } from "@/components/pbps/page";
import { Field, FormError, Segmented, Select, TextInput, YesNo } from "@/components/pbps/form";
import { Dl, Tbl, useAct, View } from "@/components/pbps/blocks";
import { PasswordChecklist, passwordProblems } from "@/components/pbps/auth-layout";
import { Button } from "@/components/ui/button";
import { changePassword, confirmTotp, listSessions, revokeSession, setupTotp } from "@/api/auth";
import { getNotificationPrefs, saveNotificationPrefs } from "@/api/ops";
import type { NotificationPref } from "@/api/types-extra";
import { useAccess, useTheme } from "@/lib/access";
import { relativeTime } from "@/lib/format";

export const Route = createFileRoute("/p/$pid/me")({ component: Page });
function Page() {
  const { access, me } = useAccess();
  const { theme, setTheme } = useTheme();
  const prefs = useQuery({
    queryKey: ["prefs"],
    queryFn: getNotificationPrefs,
    refetchOnWindowFocus: false,
  });
  return (
    <>
      <PageHeader title="My profile" />
      <div className="max-w-3xl space-y-5">
        <Card title="Account">
          <Dl
            items={[
              ["Name", access?.userName],
              ["Email", access?.email],
              ["Role", access?.roleLabel],
              ...(access?.providerName
                ? [["Provider", access.providerName] as [string, string]]
                : []),
            ]}
          />
        </Card>
        <Card title="Theme">
          <Segmented
            value={theme}
            onChange={setTheme}
            options={[
              ["light", "Light"],
              ["dark", "Dark"],
              ["system", "Same as device"],
            ]}
          />
        </Card>
        <Password email={access?.email} />
        <TwoStep method={me?.user.twoFactorMethod ?? "none"} />
        <Sessions />
        <View q={prefs}>{(d) => <Prefs d={d} />}</View>
      </div>
    </>
  );
}
function Password({ email }: { email?: string | undefined }) {
  const [c, setC] = useState("");
  const [p, setP] = useState("");
  const [p2, setP2] = useState("");
  const bad = passwordProblems(p, email);
  const m = useAct((_: void) => changePassword(c, p), {
    success: "Password changed",
    onError: () => {},
    onDone: () => {
      setC("");
      setP("");
      setP2("");
    },
  });
  return (
    <Card title="Change password">
      <FormError error={m.error} />
      <form
        className="space-y-3"
        onSubmit={(e) => {
          e.preventDefault();
          if (!bad.length && p === p2) m.mutate();
        }}
      >
        <Field label="Current password" required>
          <TextInput type="password" autoComplete="current-password" value={c} onChange={setC} />
        </Field>
        <Field label="New password" required>
          <TextInput type="password" autoComplete="new-password" value={p} onChange={setP} />
        </Field>
        {p && <PasswordChecklist pw={p} {...(email ? { email } : {})} />}
        <Field
          label="Repeat new password"
          required
          error={p2 && p !== p2 ? "Passwords do not match." : undefined}
        >
          <TextInput type="password" autoComplete="new-password" value={p2} onChange={setP2} />
        </Field>
        <Button type="submit" disabled={!c || bad.length > 0 || p !== p2 || m.isPending}>
          Change password
        </Button>
      </form>
    </Card>
  );
}
function TwoStep({ method }: { method: "none" | "email" | "totp" }) {
  const { refresh } = useAccess();
  const [code, setCode] = useState("");
  const s = useAct((_: void) => setupTotp());
  const c = useAct((_: void) => confirmTotp(code), {
    success: "Authenticator app set up",
    onError: () => {},
    onDone: () => {
      s.reset();
      void refresh();
    },
  });
  return (
    <Card title="Two-step verification">
      <p className="mb-3">
        {method === "totp"
          ? "On, with an authenticator app."
          : method === "email"
            ? "On, with codes sent by email."
            : "Off."}
      </p>
      {s.data ? (
        <div className="space-y-3">
          <p>Add this key in your authenticator app, then enter the 6-digit code it shows.</p>
          <p className="break-all rounded bg-surface-2 p-3 font-mono">{s.data.secret}</p>
          <FormError error={c.error} />
          <Field label="Code" required>
            <TextInput
              className="w-32"
              inputMode="numeric"
              maxLength={6}
              autoComplete="one-time-code"
              value={code}
              onChange={setCode}
            />
          </Field>
          <Button disabled={!/^\d{6}$/.test(code) || c.isPending} onClick={() => c.mutate()}>
            Confirm
          </Button>
        </div>
      ) : (
        <Button variant="outline" disabled={s.isPending} onClick={() => s.mutate()}>
          {method === "totp" ? "Replace authenticator app" : "Set up authenticator app"}
        </Button>
      )}
    </Card>
  );
}
function Sessions() {
  const q = useQuery({ queryKey: ["sessions"], queryFn: listSessions });
  const m = useAct((id: string) => revokeSession(id), {
    success: "Session ended",
    refresh: ["sessions"],
  });
  return (
    <Card title="Signed-in devices" padded={false}>
      <View q={q}>
        {(d) => (
          <Tbl head={["Device", "IP address", "Last used", ""]}>
            {d.map((s) => (
              <tr key={s.id}>
                <td className="font-medium">{s.device}</td>
                <td className="font-mono text-[12px]">{s.ip}</td>
                <td>{relativeTime(s.lastUsed)}</td>
                <td className="text-right">
                  {s.current ? (
                    "This device"
                  ) : (
                    <Button
                      size="sm"
                      variant="ghost"
                      disabled={m.isPending}
                      onClick={() => m.mutate(s.id)}
                    >
                      Sign out
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </Tbl>
        )}
      </View>
    </Card>
  );
}
function Prefs({ d }: { d: NotificationPref[] }) {
  const [rows, setRows] = useState(d);
  const m = useAct((_: void) => saveNotificationPrefs(rows), {
    success: "Preferences saved",
    refresh: ["prefs"],
  });
  const patch = (t: string, p: Partial<NotificationPref>) =>
    setRows((s) => s.map((r) => (r.type === t ? { ...r, ...p } : r)));
  return (
    <Card title="Notifications" padded={false}>
      <Tbl head={["Type", "In the app", "Email"]}>
        {rows.map((r) => (
          <tr key={r.type}>
            <td className="font-medium">
              {r.label}
              {r.mandatory && (
                <p className="text-[12px] font-normal text-muted-foreground">
                  Required for your role
                </p>
              )}
            </td>
            <td>
              {r.mandatory ? (
                "Always on"
              ) : (
                <YesNo
                  name={r.type}
                  value={r.inApp}
                  onChange={(v) => patch(r.type, { inApp: v })}
                />
              )}
            </td>
            <td>
              <Select
                ariaLabel={`Email for ${r.label}`}
                value={r.email}
                onChange={(v) => v && patch(r.type, { email: v as NotificationPref["email"] })}
                options={[
                  ["immediate", "Immediately"],
                  ["daily_digest", "Daily digest"],
                  ...(r.mandatory ? [] : [["off", "Off"] as [string, string]]),
                ]}
              />
            </td>
          </tr>
        ))}
      </Tbl>
      <div className="flex justify-end border-t p-4">
        <Button disabled={m.isPending} onClick={() => m.mutate()}>
          Save preferences
        </Button>
      </div>
    </Card>
  );
}
