import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import PageLayout from "../components/PageLayout";
import { getUserInfo, getUserOrders } from "../api";
import OrderCard from "../components/OrderCard";

export default function Profile() {
  const [user, setUser] = useState(null);
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    Promise.all([getUserInfo(), getUserOrders()])
      .then(([userRes, ordersRes]) => {
        setUser(userRes.data);
        setOrders(ordersRes.data);
      })
      .catch(() => { })
      .finally(() => setLoading(false));
  }, []);

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    navigate("/");
  };

  const statusLabels = {
    new: "Новый",
    packed: "Собирают",
    delivered: "Доставлен",
    cancel: "Отменен",
  };

  if (loading) {
    return (
      <PageLayout>
        <p className="text-white p-6 md:p-16">Загрузка..</p>
      </PageLayout>
    );
  }

  const activeOrders = orders.filter(
    (o) => o.status === "new" || o.status === "packed",
  );

  const completedOrders = orders.filter(
    (o) => o.status === "delivered" || o.status === "cancel",
  );
  return (
    <PageLayout>
      <main className="px-6 md:px-16 grow w-full mb-10 text-white">
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-2xl md:text-4xl font-medium uppercase">
            Личный кабинет
          </h1>
          <button
            onClick={handleLogout}
            className="text-white/60 hover:text-red-400 transition-colors text-sm uppercase"
          >
            Выйти
          </button>
        </div>

        <section className="mb-10 bg-white/5 rounded-lg p-6 border border-white/10">
          <h2 className="text-white/80 space-y-2">
            {user && (
              <div className="text-white/80 space-y-2">
                <p>
                  Имя: {user.first_name || "не указано"}{" "}
                  {user.last_name || "не указано"}
                </p>
                <p>Телефон: {user.phone || "не указано"}</p>
                <p>Логин: {user.username}</p>
              </div>
            )}
          </h2>
        </section>
        <section className="mb-10">
          <h2 className="text-xl font-medium mb-4">Активные заказы</h2>
          {activeOrders.length === 0 ? (
            <p className="text-white/60">Нет активных заказов</p>
          ) : (
            <div className="flex flex-col gap-4">
              {activeOrders.map((order) => (
                <OrderCard
                  key={order.id}
                  order={order}
                  statusLabels={statusLabels}
                />
              ))}
            </div>
          )}
        </section>

        <section>
          <h2 className="text-xl font-medium mb-4 text-white/50">
            Завершённые
          </h2>
          {completedOrders.length === 0 ? (
            <p className="text-white/60">Нет завершённых заказов</p>
          ) : (
            <div className="flex flex-col gap-4">
              {completedOrders.map((order) => (
                <OrderCard
                  key={order.id}
                  order={order}
                  statusLabels={statusLabels}
                />
              ))}
            </div>
          )}
        </section>
      </main>
    </PageLayout>
  );
}
