"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import ProfileSidebar from "@/app/profile/components/ProfileSidebar";
import { User, Clock, MoveHorizontal, Users } from "lucide-react";
import useApiClient from "@/hooks/useApiClient";
import useAuthStore from "@/stores/useAuthStore";
import { ReservationDto } from "@/api/types";
import { formatWidth } from "@/lib/utils";

export default function ReservationsPage() {
    const [activeTab, setActiveTab] = useState<
        "new" | "active" | "confirmed" | "archive"
    >("new");
    const [reservationsData, setReservationsData] = useState<ReservationDto[]>(
        []
    );
    const apiClient = useApiClient();
    const { getUserId } = useAuthStore();
    const userId = getUserId();

    useEffect(() => {
        if (userId) {
            apiClient
                .get<ReservationDto[]>(`/reservations/user/${userId}`)
                .then((response) => {
                    setReservationsData(response.data);
                })
                .catch((error) => {
                    console.error("Ошибка при загрузке бронирований:", error);
                });
        }
    }, [userId]);

    // @TODO: Залупа с годом, надо скачать dayjs
    const formatUtcDate = (timestamp: number): string => {
        const date = new Date(timestamp);
        const day = String(date.getUTCDate()).padStart(2, "0");
        const month = String(date.getUTCMonth() + 1).padStart(2, "0");
        const year = date.getUTCFullYear();
        const hours = String(date.getUTCHours()).padStart(2, "0");
        const minutes = String(date.getUTCMinutes()).padStart(2, "0");
        return `${day}.${month}.${year} - ${hours}:${minutes}`;
    };

    return (
        <main className="bg-[#f4f4f4]">
            <div className="container max-w-6xl mx-auto px-4 py-6">
                {/* Breadcrumbs */}
                <div className="hidden lg:flex mb-4 text-sm text-[#999999] items-center gap-[16px]">
                    <Link href="/">
                        <span className="cursor-pointer hover:text-[#333333] transition-colors">
                            Аренда яхты
                        </span>
                    </Link>
                    <span>&gt;</span>
                    <Link href="/profile">
                        <span className="cursor-pointer hover:text-[#333333] transition-colors">
                            Личный кабинет
                        </span>
                    </Link>
                    <span>&gt;</span>
                    <span className="text-[#333333]">Мои брони</span>
                </div>

                <div className="flex gap-6">
                    {/* Sidebar */}
                    <ProfileSidebar />

                    {/* Main Content */}
                    <div className="flex-1 bg-white rounded-[16px] p-8">
                        {/* Tabs */}
                        <div className="flex gap-2 mb-6">
                            <button
                                onClick={() => setActiveTab("new")}
                                className={`px-4 py-2 text-sm font-medium rounded-full border transition-colors ${
                                    activeTab === "new"
                                        ? "border-[#333333] bg-white text-[#333333] font-bold"
                                        : "border-transparent text-[#999999] hover:text-[#333333]"
                                }`}
                            >
                                Новые брони ({reservationsData.length})
                            </button>
                            <button
                                onClick={() => setActiveTab("active")}
                                className={`px-4 py-2 text-sm font-medium rounded-full border transition-colors ${
                                    activeTab === "active"
                                        ? "border-[#333333] bg-white text-[#333333] font-bold"
                                        : "border-transparent text-[#999999] hover:text-[#333333]"
                                }`}
                            >
                                Активные
                            </button>
                            <button
                                onClick={() => setActiveTab("confirmed")}
                                className={`px-4 py-2 text-sm font-medium rounded-full border transition-colors ${
                                    activeTab === "confirmed"
                                        ? "border-[#333333] bg-white text-[#333333] font-bold"
                                        : "border-transparent text-[#999999] hover:text-[#333333]"
                                }`}
                            >
                                Подтвержденные
                            </button>
                            <button
                                onClick={() => setActiveTab("archive")}
                                className={`px-4 py-2 text-sm font-medium rounded-full border transition-colors ${
                                    activeTab === "archive"
                                        ? "border-[#333333] bg-white text-[#333333] font-bold"
                                        : "border-transparent text-[#999999] hover:text-[#333333]"
                                }`}
                            >
                                Архив
                            </button>
                        </div>

                        {/* Reservations List */}
                        <div className="space-y-8">
                            {reservationsData.length === 0 ? (
                                <div className="text-center py-12 text-[#999999]">
                                    Нет бронирований в этой категории
                                </div>
                            ) : (
                                reservationsData.map((reservation, index) => (
                                    <div
                                        key={reservation.id}
                                        className={`overflow-hidden bg-white ${
                                            index !==
                                            reservationsData.length - 1
                                                ? "pb-8 border-b border-gray-200"
                                                : ""
                                        }`}
                                    >
                                        <div>
                                            <div className="flex flex-col lg:flex-row">
                                                {/* Image Section */}
                                                <div className="relative rounded-[12px] overflow-hidden w-90 h-90 flex-shrink-0">
                                                    <Image
                                                        src={
                                                            reservation.yacht
                                                                .mainImageUrl
                                                        }
                                                        alt={
                                                            reservation.yacht
                                                                .name
                                                        }
                                                        fill
                                                        className="object-cover"
                                                    />
                                                    {/* Owner Info Overlay */}
                                                    <div className="absolute top-2 left-2">
                                                        <div className="bg-white p-2 rounded-[8px] flex items-center gap-2">
                                                            <User
                                                                size={20}
                                                                className="text-[#999999]"
                                                            />
                                                            <div className="flex flex-col">
                                                                <span className="text-xs text-[#999999]">
                                                                    Владелец
                                                                </span>
                                                                <span className="text-sm text-[#333333] font-bold">
                                                                    {
                                                                        reservation
                                                                            .yacht
                                                                            .owner
                                                                            .firstName
                                                                    }
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    {/* Yacht Details Overlay */}
                                                    <div className="absolute bottom-2 left-2 flex gap-2">
                                                        <div className="bg-black/50 text-white px-3 py-1.5 rounded-lg flex items-center gap-3 text-sm">
                                                            <div className="flex items-center gap-1">
                                                                <MoveHorizontal
                                                                    size={16}
                                                                    className="text-white"
                                                                />
                                                                <span>
                                                                    {formatWidth(
                                                                        reservation
                                                                            .yacht
                                                                            .length
                                                                    )}
                                                                </span>
                                                            </div>
                                                        </div>

                                                        <div className="bg-black/50 text-white px-3 py-1.5 rounded-lg flex items-center gap-3 text-sm">
                                                            <div className="flex items-center gap-1">
                                                                <Users
                                                                    size={16}
                                                                    className="text-white"
                                                                />
                                                                <span>
                                                                    {
                                                                        reservation
                                                                            .yacht
                                                                            .maxCapacity
                                                                    }
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Details Section */}
                                                <div className="flex-1 px-6">
                                                    <div className="space-y-3">
                                                        <div className="flex items-start justify-between">
                                                            <div className="space-y-3 w-full">
                                                                <div className="text-[#333333] w-full flex justify-between">
                                                                    <div>
                                                                        Выход:
                                                                    </div>
                                                                    <div>
                                                                        {formatUtcDate(
                                                                            reservation.startUtc
                                                                        )}
                                                                    </div>
                                                                </div>
                                                                <div className="text-[#333333] w-full flex justify-between">
                                                                    <div>
                                                                        Заход:
                                                                    </div>
                                                                    <div>
                                                                        {formatUtcDate(
                                                                            reservation.endUtc
                                                                        )}
                                                                    </div>
                                                                </div>
                                                                <div className="text-[#333333] w-full flex justify-between">
                                                                    <div>
                                                                        Гости:
                                                                    </div>
                                                                    <div>
                                                                        {/* @TODO: Добавить количество гостей */}
                                                                        {/* {
                                                                            reservation.guests
                                                                        } */}
                                                                        -
                                                                    </div>
                                                                </div>
                                                                <div className="text-[#333333] w-full flex justify-between">
                                                                    <div>
                                                                        Тип
                                                                        оплаты:
                                                                    </div>
                                                                    <div>
                                                                        {/* @TODO: Добавить тип оплаты */}
                                                                        {/* {
                                                                            reservation.paymentType
                                                                        } */}
                                                                        -
                                                                    </div>
                                                                </div>
                                                                <div className="flex items-center gap-2 text-sm text-[#333333]">
                                                                    <Clock
                                                                        size={
                                                                            16
                                                                        }
                                                                        className="text-[#999999]"
                                                                    />
                                                                    <span>
                                                                        По
                                                                        местному
                                                                        времени
                                                                        яхты
                                                                    </span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div className="pt-3 border-t border-[#DFDFDF]">
                                                            <div className="flex items-center justify-between">
                                                                <span className="text-base font-bold text-[#333333]">
                                                                    {/* @TODO: Добавить итоговую стоимость */}
                                                                    {/* Итого:{" "}
                                                                    {formatPrice(
                                                                        reservation.totalPrice
                                                                    )}{" "}
                                                                    {reservation.paymentStatus ===
                                                                        "pending" && (
                                                                        <span className="text-base font-bold text-red-500">
                                                                            (в
                                                                            ожидании
                                                                            оплаты)
                                                                        </span>
                                                                    )} */}
                                                                    Итого: 78000{" "}
                                                                    <span className="text-base font-bold text-red-500">
                                                                        (в
                                                                        ожидании
                                                                        оплаты)
                                                                    </span>
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </main>
    );
}
