'use client';

import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  changeMyPassword,
  deleteMyAccount,
  forgotPassword,
  getPasswordStatus,
  leaveCurrentBusiness,
  type PasswordStatus,
} from '@/features/auth/api.client';
import { errorText } from '@/lib/api/errors';
import { DialogHead, SetDialog } from './settings-ui';

const DATE_FORMAT: Intl.DateTimeFormatOptions = {
  month: 'long',
  day: 'numeric',
  year: 'numeric',
};

/**
 * Password checklist matches Settings › Security PHP design (Untitled-2).
 * Stricter than signup’s 8-char floor; still accepted by POST /auth/password.
 */
function passwordRules(value: string) {
  return [
    { key: 'length', label: 'At least 12 characters long', ok: value.length >= 12 },
    { key: 'lower', label: 'One lowercase character', ok: /[a-z]/.test(value) },
    { key: 'upper', label: 'One uppercase character', ok: /[A-Z]/.test(value) },
    {
      key: 'special',
      label: 'One number, symbol, or whitespace character',
      ok: /[^A-Za-z]/.test(value),
    },
  ];
}

/**
 * Settings › Security › Password. The page shows Reset password and the last reset date.
 * "Forgot my password" opens a confirm dialog, then emails a reset link via POST /auth/forgot-password.
 */
export function SecurityPasswordBlock({ email }: { email: string }) {
  const toast = useToast();
  const [status, setStatus] = useState<PasswordStatus | null>(null);
  const [open, setOpen] = useState(false);
  const [forgotOpen, setForgotOpen] = useState(false);
  const [current, setCurrent] = useState('');
  const [next, setNext] = useState('');
  const [show, setShow] = useState(false);
  const [busy, setBusy] = useState(false);
  const [forgotBusy, setForgotBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      setStatus(await getPasswordStatus());
    } catch (err) {
      setError(errorText(err));
    }
  }, []);

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

  const rules = passwordRules(next);
  const ready = current.length > 0 && rules.every((r) => r.ok);

  const close = () => {
    setOpen(false);
    setForgotOpen(false);
    setCurrent('');
    setNext('');
    setShow(false);
    setError(null);
  };

  const closeForgot = () => {
    if (forgotBusy) return;
    setForgotOpen(false);
  };

  const submit = async () => {
    if (!ready || busy) return;
    setBusy(true);
    setError(null);
    try {
      await changeMyPassword(current, next);
      toast('Password updated. Other browsers were signed out.', 'success');
      close();
      await load();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  const sendReset = async () => {
    if (forgotBusy) return;
    setForgotBusy(true);
    try {
      await forgotPassword(email);
      toast('A password reset link was sent to your email.', 'success');
      close();
    } catch (err) {
      toast(errorText(err), 'danger');
      setForgotOpen(false);
    } finally {
      setForgotBusy(false);
    }
  };

  const lastReset = status?.lastResetAt ? new Date(status.lastResetAt) : null;

  return (
    <>
      <div className="set-security-block">
        <h3>Password</h3>
        {status && !status.hasPassword ? (
          <p className="set-security-meta">
            Your sign-in is managed by Google. Change your password in your Google account.
          </p>
        ) : (
          <>
            <button
              type="button"
              className="set-security-link"
              onClick={() => setOpen(true)}
              disabled={!status}
            >
              Reset password
            </button>
            {lastReset ? (
              <p className="set-security-meta">
                Last reset on {lastReset.toLocaleDateString('en-US', DATE_FORMAT)}
              </p>
            ) : null}
          </>
        )}
        {error && !open ? (
          <p className="set-security-meta" role="alert">
            {error}
          </p>
        ) : null}

        <SetDialog
          open={open}
          onClose={close}
          labelledBy="security-reset-title"
          className="set-security-dialog"
        >
          <form
            className="set-security-dialog-form"
            onSubmit={(e) => {
              e.preventDefault();
              void submit();
            }}
          >
            <DialogHead id="security-reset-title" title="Reset password" onClose={close} />
            <div className="set-security-dialog-body">
              <div className="field">
                <label className="field__label" htmlFor="security-current-password">
                  Confirm current password
                </label>
                <button
                  type="button"
                  className="set-security-link set-security-field-link"
                  onClick={() => setForgotOpen(true)}
                >
                  Forgot my password
                </button>
                <input
                  className="input"
                  id="security-current-password"
                  name="current_password"
                  type="password"
                  autoComplete="current-password"
                  required
                  value={current}
                  onChange={(e) => setCurrent(e.target.value)}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="security-new-password">
                  New password
                </label>
                <button
                  type="button"
                  className="set-security-link set-security-field-link"
                  onClick={() => setShow((s) => !s)}
                >
                  {show ? 'Hide password' : 'Show password'}
                </button>
                <input
                  className="input"
                  id="security-new-password"
                  name="new_password"
                  type={show ? 'text' : 'password'}
                  autoComplete="new-password"
                  required
                  value={next}
                  onChange={(e) => setNext(e.target.value)}
                />
              </div>
              <ul className="set-security-password-rules">
                {rules.map((r) => (
                  <li key={r.key} className={r.ok ? 'is-valid' : undefined}>
                    <span aria-hidden="true">✓</span>
                    {r.label}
                  </li>
                ))}
              </ul>
              {error ? (
                <p className="set-security-meta" role="alert">
                  {error}
                </p>
              ) : null}
            </div>
            <div className="set-security-dialog-foot">
              <button type="submit" className="btn-crm btn-crm--primary" disabled={!ready || busy}>
                Reset password
              </button>
              <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
                Cancel
              </button>
            </div>
          </form>
        </SetDialog>

        <SetDialog
          open={forgotOpen}
          onClose={closeForgot}
          labelledBy="security-forgot-title"
          className="set-security-dialog"
        >
          <DialogHead id="security-forgot-title" title="Forgot my password" onClose={closeForgot} />
          <div className="set-security-dialog-body">
            <p>A password reset process would be sent to the email address on your account.</p>
          </div>
          <div className="set-security-dialog-foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={forgotBusy}
              onClick={() => void sendReset()}
            >
              Continue
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={forgotBusy}
              onClick={closeForgot}
            >
              Cancel
            </button>
          </div>
        </SetDialog>
      </div>
      <SecurityDeprecationBlock hasPassword={Boolean(status?.hasPassword)} />
    </>
  );
}

/** Design: passwords not used for 90 days are removed. Shown for accounts that have a password. */
export function SecurityDeprecationBlock({ hasPassword }: { hasPassword: boolean }) {
  return (
    <div className="set-security-block">
      <h3>Deprecation</h3>
      <p className="set-security-description">
        If you don&apos;t use a password to log in for over 90 days, your password will be removed.
      </p>
      <table className="set-security-table set-security-table--small">
        <thead>
          <tr>
            <th>Status</th>
            <th>Deprecation Date</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <span className="set-security-status-dot" />
              {hasPassword ? 'Ineligible' : 'Not applicable'}
            </td>
            <td>None</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

/**
 * "Remove me from this account" and "Delete my user account". Both need the user to type their
 * own email. Leaving reloads into another account; deleting ends the session and goes to login.
 */
export function SecurityDangerZone({ email }: { email: string }) {
  const toast = useToast();
  const [mode, setMode] = useState<'leave' | 'delete' | null>(null);
  const [typed, setTyped] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const close = () => {
    setMode(null);
    setTyped('');
    setError(null);
  };

  const matches = typed.trim().toLowerCase() === email.trim().toLowerCase();

  const confirm = async () => {
    if (!mode || !matches || busy) return;
    setBusy(true);
    setError(null);
    try {
      if (mode === 'leave') {
        await leaveCurrentBusiness(typed.trim());
        toast('You were removed from this account. Opening another account.', 'success');
        window.location.assign('/');
        return;
      }
      await deleteMyAccount(typed.trim());
      window.location.assign('/login');
    } catch (err) {
      setError(errorText(err));
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const isDelete = mode === 'delete';

  return (
    <>
      <div className="set-security-danger-block">
        <h3>Remove from this account</h3>
        <p>
          This action will remove your user from this account. If you&apos;re part of other
          accounts, you&apos;ll still have access to them.
        </p>
        <button type="button" className="btn-crm btn-crm--danger" onClick={() => setMode('leave')}>
          Remove me from this account
        </button>
      </div>

      <div className="set-security-danger-block">
        <h3>Permanently Remove</h3>
        <button type="button" className="btn-crm btn-crm--danger" onClick={() => setMode('delete')}>
          Delete my user account
        </button>
      </div>

      <SetDialog
        open={mode !== null}
        onClose={close}
        labelledBy="security-danger-title"
        className="set-security-dialog"
      >
        <DialogHead
          id="security-danger-title"
          title={isDelete ? 'Permanently delete your account?' : 'Remove from this account?'}
          onClose={close}
        />
        <div className="set-security-dialog-body">
          <p>
            {isDelete
              ? 'You are about to permanently delete your account. This will also remove your user from CRM accounts you use and cannot be undone.'
              : "You are about to remove your user from this account. If you're part of other accounts, you'll still have access to them."}
          </p>
          <div className="field" data-security-confirm-email-field>
            <label className="field__label" htmlFor="security-confirm-email">
              Type your email address to confirm
            </label>
            <input
              className="input"
              id="security-confirm-email"
              name="confirm_email"
              type="email"
              value={typed}
              placeholder="name@company.com"
              autoComplete="off"
              onChange={(e) => setTyped(e.target.value)}
            />
          </div>
          {error ? (
            <p className="set-security-meta" role="alert">
              {error}
            </p>
          ) : null}
        </div>
        <div className="set-security-dialog-foot">
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            disabled={!matches || busy}
            onClick={() => void confirm()}
          >
            {isDelete ? 'Delete user' : 'Remove'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={close}
            disabled={busy}
          >
            Cancel
          </button>
        </div>
      </SetDialog>
    </>
  );
}
