/**
 * Reset password — uses uid + token from email link query string
 */

import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '../../components/common/Button';
import { Input } from '../../components/common/Input';
import { Card } from '../../components/common/Card';
import { handleApiError } from '../../services/api';
import { authService } from '../../services/auth';

export const ResetPassword: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const uid = searchParams.get('uid') ?? '';
  const token = searchParams.get('token') ?? '';

  const [form, setForm] = useState({ new_password: '', new_password_confirm: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [linkError, setLinkError] = useState('');

  useEffect(() => {
    if (!uid || !token) {
      setLinkError('This reset link is invalid or incomplete. Request a new link from the login page.');
    }
  }, [uid, token]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
    setError('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!uid || !token) return;
    setLoading(true);
    setError('');
    try {
      await authService.confirmPasswordReset({
        uid,
        token,
        new_password: form.new_password,
        new_password_confirm: form.new_password_confirm,
      });
      setSuccess(true);
      setTimeout(() => navigate('/login', { replace: true }), 2000);
    } catch (err) {
      setError(handleApiError(err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="page-bg" style={{ display: 'grid', placeItems: 'center', padding: '2rem 1.5rem' }}>
      <div style={{ width: '100%', maxWidth: 420 }}>
        <Card padding="none">
          <div style={{ padding: '2rem' }}>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <h1
                style={{
                  margin: 0,
                  fontSize: 32,
                  fontWeight: 900,
                  background: 'linear-gradient(90deg, var(--color-brand-dark), var(--color-brand))',
                  WebkitBackgroundClip: 'text',
                  backgroundClip: 'text',
                  color: 'transparent',
                }}
              >
                Set new password
              </h1>
              <p style={{ margin: '12px 0 0', color: 'var(--text-muted)', fontSize: 14 }}>
                Choose a strong password for your account.
              </p>
            </div>

            {linkError && (
              <div
                style={{
                  marginBottom: 16,
                  padding: 16,
                  background: '#fef2f2',
                  border: '1px solid #fecaca',
                  borderRadius: 12,
                }}
              >
                <p style={{ margin: 0, color: '#b91c1c', fontSize: 14 }}>{linkError}</p>
                <p style={{ margin: '12px 0 0', fontSize: 14 }}>
                  <Link to="/forgot-password" style={{ color: 'var(--color-brand)', fontWeight: 700 }}>
                    Request a new link
                  </Link>
                </p>
              </div>
            )}

            {success && (
              <div
                style={{
                  padding: 16,
                  background: 'rgba(34,197,94,0.10)',
                  border: '2px solid rgba(34,197,94,0.35)',
                  borderRadius: 12,
                  marginBottom: 16,
                }}
              >
                <p style={{ margin: 0, color: '#86efac', fontSize: 14 }}>
                  Password updated. Redirecting to login…
                </p>
              </div>
            )}

            {!linkError && !success && (
              <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 16 }}>
                {error && (
                  <div
                    style={{
                      padding: 16,
                      background: '#fef2f2',
                      border: '1px solid #fecaca',
                      borderRadius: 12,
                    }}
                  >
                    <p style={{ margin: 0, color: '#b91c1c', fontSize: 14 }}>{error}</p>
                  </div>
                )}
                <Input
                  label="New password"
                  type="password"
                  name="new_password"
                  value={form.new_password}
                  onChange={handleChange}
                  placeholder="New password"
                  required
                  autoComplete="new-password"
                />
                <Input
                  label="Confirm new password"
                  type="password"
                  name="new_password_confirm"
                  value={form.new_password_confirm}
                  onChange={handleChange}
                  placeholder="Confirm new password"
                  required
                  autoComplete="new-password"
                />
                <Button type="submit" variant="primary" fullWidth loading={loading} disabled={!uid || !token}>
                  {loading ? 'Saving…' : 'Update password'}
                </Button>
              </form>
            )}

            <div
              style={{
                borderTop: '1px solid rgba(15,23,42,0.08)',
                marginTop: 24,
                paddingTop: 20,
                textAlign: 'center',
              }}
            >
              <Link
                to="/login"
                style={{ color: 'var(--color-brand)', fontWeight: 800, textDecoration: 'none', fontSize: 14 }}
              >
                Back to login
              </Link>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};
