'use client';

import { CheckCircle2, LogOut, MailWarning, Monitor, Smartphone, Tablet, type LucideIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

import { CountdownRing } from '@/components/auth/resend-button';
import { FormField } from '@/components/forms/form-field';
import { PasswordInput } from '@/components/forms/password-input';
import { PasswordStrength } from '@/components/forms/password-strength';
import { PageTitle } from '@/components/layout/page-header';
import { SectionCard } from '@/components/settings/section-card';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { DateText } from '@/components/ui/money-text';
import { ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { formatRelative } from '@/lib/shipments';

interface SessionRow {
  id: string;
  device: string;
  ip?: string;
  lastUsedAt?: string;
  current: boolean;
}

/** Best-effort parse of a user agent string for display only. */
const describeDevice = (device: string): { icon: LucideIcon; browser: string; os: string } => {
  const ua = device;
  const icon = /iPad|Tablet/i.test(ua) ? Tablet : /iPhone|Android.*Mobile|Mobile/i.test(ua) ? Smartphone : Monitor;
  const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : '';
  const os = /Windows/.test(ua) ? 'Windows' : /Mac OS X|Macintosh/.test(ua) && !/iPhone|iPad/.test(ua) ? 'macOS' : /iPhone|iPad|iOS/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Linux/.test(ua) ? 'Linux' : '';
  return { icon, browser, os };
};

export default function SecuritySettingsPage() {
  const { user, refreshMe } = useAuth();
  const [currentPassword, setCurrentPassword] = useState('');
  const [nextPassword, setNextPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [passwordPending, setPasswordPending] = useState(false);
  const [sessions, setSessions] = useState<SessionRow[] | null>(null);
  const [error, setError] = useState<ApiError | null>(null);
  const [revokeTarget, setRevokeTarget] = useState<SessionRow | null>(null);
  const [signOutAllOpen, setSignOutAllOpen] = useState(false);
  const [cooldown, setCooldown] = useState(0);

  const loadSessions = () => {
    void api<SessionRow[]>('/sessions')
      .then(setSessions)
      .catch((reason: unknown) => setError(reason instanceof ApiError ? reason : null));
  };

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

  const cooling = cooldown > 0;
  useEffect(() => {
    if (!cooling) return undefined;
    const timer = window.setInterval(() => setCooldown((current) => Math.max(0, current - 1)), 1000);
    return () => window.clearInterval(timer);
  }, [cooling]);

  if (error !== null) return <ErrorState message={error.message} requestId={error.requestId} />;

  const others = (sessions ?? []).filter((session) => !session.current).length;

  return (
    <div className="grid gap-6">
      <PageTitle title="Security" breadcrumb="Settings" />
      <SectionCard title="Password" description="Use at least 10 characters with a letter and a number.">
        <form
          className="grid gap-4 sm:max-w-md"
          onSubmit={(event) => {
            event.preventDefault();
            if (nextPassword !== confirm) {
              toast.error('New password and confirmation do not match.');
              return;
            }
            setPasswordPending(true);
            void api('/auth/change-password', { method: 'POST', json: { currentPassword, newPassword: nextPassword } })
              .then(() => {
                setCurrentPassword('');
                setNextPassword('');
                setConfirm('');
                toast.success('Password changed. Other devices were signed out.');
                loadSessions();
              })
              .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not change password.'))
              .finally(() => setPasswordPending(false));
          }}
        >
          <FormField id="current-password" label="Current password">
            <PasswordInput id="current-password" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} autoComplete="current-password" />
          </FormField>
          <div className="grid gap-3">
            <FormField id="new-password" label="New password">
              <PasswordInput id="new-password" value={nextPassword} onChange={(event) => setNextPassword(event.target.value)} autoComplete="new-password" />
            </FormField>
            <PasswordStrength password={nextPassword} />
          </div>
          <FormField id="confirm-password" label="Confirm new password">
            <PasswordInput id="confirm-password" value={confirm} onChange={(event) => setConfirm(event.target.value)} autoComplete="new-password" />
          </FormField>
          <div className="flex flex-wrap items-center gap-3">
            <Button type="submit" loading={passwordPending}>
              Change password
            </Button>
            <p className="text-caption text-muted-foreground">Other devices will be signed out.</p>
          </div>
        </form>
      </SectionCard>

      <SectionCard title="Active sessions" description="Devices signed in to your account.">
        {sessions === null ? (
          <div className="grid gap-3">
            {[0, 1].map((index) => (
              <Skeleton key={index} className="h-14 w-full" />
            ))}
          </div>
        ) : (
          <>
            <ul className="-mx-2 grid gap-1">
              {sessions.map((session) => {
                const device = describeDevice(session.device);
                const Icon = device.icon;
                const title = [device.browser, device.os].filter(Boolean).join(' on ') || session.device;
                const lastUsed = session.lastUsedAt === undefined ? null : typeof session.lastUsedAt === 'string' ? session.lastUsedAt : new Date(session.lastUsedAt).toISOString();
                return (
                  <li key={session.id} className="flex items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-surface-muted/60">
                    <span className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-surface-muted text-muted-foreground">
                      <Icon className="h-5 w-5" aria-hidden="true" />
                    </span>
                    <div className="min-w-0 flex-1">
                      <p className="flex flex-wrap items-center gap-2 text-small font-semibold">
                        <span className="truncate" title={session.device}>
                          {title}
                        </span>
                        {session.current ? <span className="rounded-pill bg-primary-soft px-2 py-0.5 text-[11px] font-semibold text-primary">Current device</span> : null}
                      </p>
                      <p className="truncate text-caption text-muted-foreground">
                        {session.ip ?? 'Unknown IP'}
                        {lastUsed === null ? '' : ` · Active ${formatRelative(lastUsed)}`}
                      </p>
                    </div>
                    {session.current ? null : (
                      <Button type="button" size="sm" variant="ghost" onClick={() => setRevokeTarget(session)}>
                        Revoke
                      </Button>
                    )}
                  </li>
                );
              })}
            </ul>
            <div className="mt-4 border-t border-border pt-4">
              <Button
                type="button"
                variant="secondary"
                className="border-danger/40 text-danger hover:bg-danger-soft"
                disabled={others === 0}
                onClick={() => setSignOutAllOpen(true)}
              >
                <LogOut className="h-4 w-4" aria-hidden="true" />
                Sign out of all other devices
              </Button>
            </div>
          </>
        )}
      </SectionCard>

      <SectionCard title="Email verification" description="A verified email is required to buy labels.">
        {user?.emailVerifiedAt === undefined ? (
          <div className="flex flex-wrap items-center gap-3">
            <span className="inline-flex items-center gap-1.5 rounded-pill bg-warning-soft px-2.5 py-1 text-caption font-semibold text-warning">
              <MailWarning className="h-3.5 w-3.5" aria-hidden="true" />
              Not verified
            </span>
            <p className="min-w-0 flex-1 text-small text-muted-foreground">Check your inbox for the verification link.</p>
            <Button
              type="button"
              variant="secondary"
              size="sm"
              disabled={cooling}
              onClick={() => {
                void api('/auth/resend-verification', { method: 'POST' })
                  .then(() => {
                    toast.success('Verification email sent.');
                    setCooldown(60);
                  })
                  .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not resend verification.'));
              }}
            >
              {cooling ? (
                <>
                  <CountdownRing remaining={cooldown} className="h-4 w-4" />
                  <span className="tabular-nums">Resend in {cooldown}s</span>
                </>
              ) : (
                'Resend verification email'
              )}
            </Button>
            <Button type="button" variant="ghost" size="sm" onClick={() => void refreshMe()}>
              Refresh status
            </Button>
          </div>
        ) : (
          <div className="flex flex-wrap items-center gap-3">
            <span className="inline-flex items-center gap-1.5 rounded-pill bg-success-soft px-2.5 py-1 text-caption font-semibold text-success">
              <CheckCircle2 className="h-3.5 w-3.5" aria-hidden="true" />
              Verified
            </span>
            <p className="text-small text-muted-foreground">
              Verified on <DateText value={user.emailVerifiedAt} />
            </p>
          </div>
        )}
      </SectionCard>

      <ConfirmDialog
        open={revokeTarget !== null}
        title="Revoke this session?"
        message="That device will be signed out the next time it makes a request."
        confirmLabel="Revoke session"
        cancelLabel="Keep session"
        onClose={() => setRevokeTarget(null)}
        onConfirm={() => {
          if (revokeTarget === null) return;
          const target = revokeTarget;
          setRevokeTarget(null);
          void api(`/sessions/${target.id}`, { method: 'DELETE' })
            .then(() => {
              toast.success('Session revoked.');
              loadSessions();
            })
            .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not revoke session.'));
        }}
      />
      <ConfirmDialog
        open={signOutAllOpen}
        title="Sign out of all other devices?"
        message="Every other session is signed out. This device stays signed in."
        confirmLabel="Sign out others"
        cancelLabel="Cancel"
        onClose={() => setSignOutAllOpen(false)}
        onConfirm={() => {
          setSignOutAllOpen(false);
          void api('/auth/logout-all', { method: 'POST' })
            .then(() => toast.success('Other devices were signed out.'))
            .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not sign out other devices.'))
            .finally(loadSessions);
        }}
      />
    </div>
  );
}
