"use client";

import * as React from "react";
import { useActionState, useTransition } from "react";
import { toast } from "sonner";
import { Lock, ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { StatusBadge } from "@/components/shared/status-badge";
import { formatDateTime } from "@/lib/format";
import { accountTexts } from "@/lib/i18n/account";
import { changePasswordAction, setTwoFactorAction } from "@/lib/actions/account";
import type { AccountActionState } from "@/lib/validation/account";
import { FormFooter, SectionCard, TextField } from "./section-card";

export function SecurityCard({
  twoFactorEnabled,
  status,
  lastAuthAt,
  createdAt,
}: {
  twoFactorEnabled: boolean;
  status: string;
  lastAuthAt: string | null;
  createdAt: string;
}) {
  const [state, formAction, pending] = useActionState<AccountActionState, FormData>(
    changePasswordAction,
    null,
  );

  const [currentPassword, setCurrentPassword] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [twoFactor, setTwoFactor] = React.useState(twoFactorEnabled);
  const [twoFactorPending, startTransition] = useTransition();

  React.useEffect(() => {
    if (!state) return;
    if (state.ok) {
      toast.success(accountTexts.passwordChanged);
      setCurrentPassword("");
      setPassword("");
      setConfirmPassword("");
    } else {
      toast.error(state.error);
    }
  }, [state]);

  const failure = state && state.ok === false ? state : null;
  const errors = failure?.fieldErrors ?? {};

  function toggleTwoFactor(next: boolean) {
    const previous = twoFactor;
    setTwoFactor(next);
    startTransition(async () => {
      const result = await setTwoFactorAction(next);
      if (result?.ok) {
        toast.success(next ? accountTexts.twoFactorOn : accountTexts.twoFactorOff);
      } else {
        setTwoFactor(previous);
        toast.error(result && !result.ok ? result.error : accountTexts.errGeneric);
      }
    });
  }

  return (
    <SectionCard
      icon={Lock}
      title={accountTexts.securityTitle}
      description={accountTexts.securityHint}
    >
      <dl className="mb-5 grid gap-3 rounded-xl border bg-muted/30 p-4 text-sm sm:grid-cols-3">
        <div className="space-y-1">
          <dt className="text-xs text-muted-foreground">{accountTexts.accountStatus}</dt>
          <dd>
            <StatusBadge status={status} />
          </dd>
        </div>
        <div className="space-y-1">
          <dt className="text-xs text-muted-foreground">{accountTexts.lastSignIn}</dt>
          <dd className="font-mono text-xs">{formatDateTime(lastAuthAt)}</dd>
        </div>
        <div className="space-y-1">
          <dt className="text-xs text-muted-foreground">{accountTexts.memberSince}</dt>
          <dd className="font-mono text-xs">{formatDateTime(createdAt)}</dd>
        </div>
      </dl>

      <form action={formAction}>
        <fieldset disabled={pending} className="grid gap-4 sm:grid-cols-2">
          <TextField
            id="currentPassword"
            label={accountTexts.currentPasswordLabel}
            type="password"
            autoComplete="current-password"
            value={currentPassword}
            onChange={setCurrentPassword}
            error={errors.currentPassword}
            className="sm:col-span-2"
          />
          <TextField
            id="password"
            label={accountTexts.newPasswordLabel}
            type="password"
            autoComplete="new-password"
            value={password}
            onChange={setPassword}
            error={errors.password}
          />
          <TextField
            id="confirmPassword"
            label={accountTexts.confirmPasswordLabel}
            type="password"
            autoComplete="new-password"
            value={confirmPassword}
            onChange={setConfirmPassword}
            error={errors.confirmPassword}
          />
        </fieldset>

        <FormFooter
          message={
            state?.ok
              ? accountTexts.passwordChanged
              : failure && !Object.keys(errors).length
                ? failure.error
                : null
          }
          tone={failure ? "error" : "success"}
        >
          <Button type="submit" disabled={pending}>
            {pending ? "Saving…" : accountTexts.changePassword}
          </Button>
        </FormFooter>
      </form>

      <div className="mt-5 flex items-start gap-3 rounded-xl border p-4">
        <span className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg bg-cyan-500/10 text-cyan-600 dark:text-cyan-400">
          <ShieldCheck className="size-4" />
        </span>
        <div className="min-w-0 flex-1 space-y-1">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm font-medium">{accountTexts.twoFactorTitle}</p>
            <Switch
              checked={twoFactor}
              onCheckedChange={toggleTwoFactor}
              disabled={twoFactorPending}
              aria-label={accountTexts.twoFactorTitle}
            />
          </div>
          <p className="text-xs leading-relaxed text-muted-foreground">
            {accountTexts.twoFactorHint}
          </p>
        </div>
      </div>
    </SectionCard>
  );
}

export default SecurityCard;
