'use client';

import { useState, type FormEvent, type ChangeEvent } from 'react';
import { login } from '@/lib/auth';

/** Format raw digits into +7 (XXX) XXX-XX-XX mask. Max 11 digits (7 + 10). */
function formatPhone(value: string): string {
  const digits = value.replace(/\D/g, '').slice(0, 11);

  if (digits.length === 0) return '';
  if (digits.length <= 1) return `+${digits}`;
  if (digits.length <= 4) return `+${digits[0]} (${digits.slice(1)}`;
  if (digits.length <= 7)
    return `+${digits[0]} (${digits.slice(1, 4)}) ${digits.slice(4)}`;
  if (digits.length <= 9)
    return `+${digits[0]} (${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7)}`;
  return `+${digits[0]} (${digits.slice(1, 4)}) ${digits.slice(4, 7)}-${digits.slice(7, 9)}-${digits.slice(9, 11)}`;
}

/** Strip mask, return raw digits prefixed with +. */
function stripPhone(masked: string): string {
  const digits = masked.replace(/\D/g, '');
  return digits ? `+${digits}` : '';
}

export default function LoginPage() {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handlePhoneChange = (e: ChangeEvent<HTMLInputElement>) => {
    setPhone(formatPhone(e.target.value));
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');

    const rawPhone = stripPhone(phone);

    if (!rawPhone || rawPhone.length < 12 || !password.trim()) {
      setError('Заполните все поля');
      return;
    }

    setLoading(true);

    try {
      await login(rawPhone, password);
      window.location.href = '/dashboard';
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Ошибка авторизации',
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="w-full max-w-sm">
        <div className="mb-8 text-center">
          <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary">
            <span className="text-2xl font-bold text-primary-foreground">MF</span>
          </div>
          <h1 className="text-2xl font-bold text-text">
            My<span className="text-primary">Fit</span>CRM
          </h1>
          <p className="mt-1 text-sm text-muted">
            Панель суперадминистратора
          </p>
        </div>

        <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
          <h2 className="mb-6 text-lg font-semibold text-text">Вход</h2>

          <form onSubmit={(e) => void handleSubmit(e)} className="space-y-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-text">
                Телефон
              </label>
              <input
                type="tel"
                placeholder="+7 (999) 000-00-00"
                value={phone}
                onChange={handlePhoneChange}
                maxLength={18}
                autoComplete="tel"
                className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-text placeholder:text-muted outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
              />
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-text">
                Пароль
              </label>
              <input
                type="password"
                placeholder="Введите пароль"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete="current-password"
                className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-text placeholder:text-muted outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
              />
            </div>

            {error && (
              <div className="rounded-lg bg-error/10 p-3 text-sm text-error">
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:brightness-90 disabled:opacity-50"
            >
              {loading ? 'Вход...' : 'Войти'}
            </button>
          </form>
        </div>

        <p className="mt-6 text-center text-xs text-muted">
          MyFitCRM &copy; 2026. Все права защищены.
        </p>
      </div>
    </div>
  );
}
