import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';
import { User, Package, Heart, LogOut, Lock, AlertCircle, CheckCircle, MapPin, Home } from 'lucide-react';
import authService from '../../services/auth';

export default function ChangePasswordPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    current_password: '',
    new_password: '',
    confirm_password: ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    // Проверяем, авторизован ли пользователь
    if (!authService.isAuthenticated()) {
      router.push('/login?redirect=/account/change-password');
    }
  }, [router]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    // Проверяем совпадение паролей
    if (formData.new_password !== formData.confirm_password) {
      setError('Новый пароль и подтверждение не совпадают');
      setLoading(false);
      return;
    }

    try {
      // Вызываем метод изменения пароля
      await authService.changePassword(
        formData.current_password,
        formData.new_password
      );
      
      setSuccess(true);
    } catch (err) {
      console.error('Ошибка при изменении пароля:', err);
      setError('Не удалось изменить пароль. Проверьте правильность текущего пароля.');
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    authService.logout();
    router.push('/');
  };

  return (
    <div className="min-h-screen bg-gray-50 pt-20 pb-12">
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-3xl font-bold mb-8">Личный кабинет</h1>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          {/* Боковая панель навигации */}
          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex flex-col space-y-4">
              <Link href="/account" className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors">
                <User className="h-5 w-5" />
                <span>Профиль</span>
              </Link>
              <Link href="/account/orders" className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors">
                <Package className="h-5 w-5" />
                <span>Мои заказы</span>
              </Link>
              <Link href="/account/addresses" className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors">
                <MapPin className="h-5 w-5" />
                <span>Мои адреса</span>
              </Link>
              <Link href="/favorites" className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors">
                <Heart className="h-5 w-5" />
                <span>Избранное</span>
              </Link>
              <Link href="/" className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors">
                <Home className="h-5 w-5" />
                <span>На главную</span>
              </Link>
              <button 
                onClick={handleLogout}
                className="flex items-center space-x-2 text-gray-600 hover:text-indigo-600 transition-colors"
              >
                <LogOut className="h-5 w-5" />
                <span>Выйти</span>
              </button>
            </div>
          </div>

          {/* Основное содержимое */}
          <div className="md:col-span-3 bg-white rounded-lg shadow p-6">
            <div className="mb-6">
              <h2 className="text-xl font-semibold">Изменение пароля</h2>
              <p className="text-gray-600 mt-1">Обновите свой пароль для повышения безопасности аккаунта</p>
            </div>

            {error && (
              <div className="mb-6 bg-red-50 border-l-4 border-red-500 p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <AlertCircle className="h-5 w-5 text-red-500" />
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-red-700">{error}</p>
                  </div>
                </div>
              </div>
            )}

            {success ? (
              <div className="bg-green-50 border-l-4 border-green-500 p-4 mb-6">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <CheckCircle className="h-5 w-5 text-green-500" />
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-green-700">Пароль успешно изменен!</p>
                  </div>
                </div>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-6">
                <div>
                  <label htmlFor="current_password" className="block text-sm font-medium text-gray-700">
                    Текущий пароль
                  </label>
                  <div className="mt-1 relative rounded-md shadow-sm">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Lock className="h-5 w-5 text-gray-400" />
                    </div>
                    <input
                      id="current_password"
                      name="current_password"
                      type="password"
                      autoComplete="current-password"
                      required
                      value={formData.current_password}
                      onChange={handleChange}
                      className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="••••••••"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="new_password" className="block text-sm font-medium text-gray-700">
                    Новый пароль
                  </label>
                  <div className="mt-1 relative rounded-md shadow-sm">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Lock className="h-5 w-5 text-gray-400" />
                    </div>
                    <input
                      id="new_password"
                      name="new_password"
                      type="password"
                      autoComplete="new-password"
                      required
                      value={formData.new_password}
                      onChange={handleChange}
                      className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="••••••••"
                      minLength={8}
                    />
                  </div>
                  <p className="mt-1 text-xs text-gray-500">Минимум 8 символов</p>
                </div>

                <div>
                  <label htmlFor="confirm_password" className="block text-sm font-medium text-gray-700">
                    Подтверждение нового пароля
                  </label>
                  <div className="mt-1 relative rounded-md shadow-sm">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Lock className="h-5 w-5 text-gray-400" />
                    </div>
                    <input
                      id="confirm_password"
                      name="confirm_password"
                      type="password"
                      autoComplete="new-password"
                      required
                      value={formData.confirm_password}
                      onChange={handleChange}
                      className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      placeholder="••••••••"
                      minLength={8}
                    />
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <Link href="/account" className="text-sm font-medium text-indigo-600 hover:text-indigo-500">
                    Вернуться в профиль
                  </Link>
                  <button
                    type="submit"
                    disabled={loading}
                    className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? 'Сохранение...' : 'Изменить пароль'}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
} 