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

export default function AccountPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');

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

    // Загружаем данные пользователя
    const fetchUserData = async () => {
      try {
        const userData = await userService.getCurrentUser();
        setUser(userData);
      } catch (err) {
        console.error('Ошибка при загрузке данных пользователя:', err);
        setError('Не удалось загрузить данные пользователя');
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, [router]);

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 pt-20 pb-12">
        <div className="container mx-auto px-4 py-8">
          <div className="flex justify-center">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
          </div>
        </div>
      </div>
    );
  }

  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>
        
        {error && (
          <div className="mb-6 bg-red-50 border-l-4 border-red-500 p-4">
            <div className="flex">
              <div className="ml-3">
                <p className="text-sm text-red-700">{error}</p>
              </div>
            </div>
          </div>
        )}

        <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-indigo-600 font-medium">
                <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="flex justify-between items-center mb-6">
              <h2 className="text-xl font-semibold">Личные данные</h2>
              <Link href="/account/edit" className="flex items-center text-sm text-indigo-600 hover:text-indigo-800">
                <Edit className="h-4 w-4 mr-1" />
                Редактировать
              </Link>
            </div>

            {user && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <div className="mb-4">
                    <p className="text-sm text-gray-500 mb-1">Имя</p>
                    <p className="font-medium">{user.first_name}</p>
                  </div>
                  <div className="mb-4">
                    <p className="text-sm text-gray-500 mb-1">Фамилия</p>
                    <p className="font-medium">{user.last_name}</p>
                  </div>
                </div>
                <div>
                  <div className="mb-4">
                    <p className="text-sm text-gray-500 mb-1">Email</p>
                    <p className="font-medium">{user.email}</p>
                  </div>
                  <div className="mb-4">
                    <p className="text-sm text-gray-500 mb-1">Телефон</p>
                    <p className="font-medium">{user.phone || 'Не указан'}</p>
                  </div>
                </div>
              </div>
            )}

            <div className="mt-8 border-t pt-6">
              <h3 className="text-lg font-semibold mb-4">Безопасность</h3>
              <Link href="/account/change-password" className="inline-flex items-center px-4 py-2 border border-indigo-600 text-sm font-medium rounded-md text-indigo-600 bg-white hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Изменить пароль
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 