"use client";

import {
  getDetailOrder,
  getOrderHistory,
  savedOrderHistory,
  updateDetailOrder,
} from "@/pages/finance/lib/api";
import type { OrderStatus } from "@/pages/finance/lib/type";
import { OrderHistoryTable } from "@/pages/finance/ui/OrderHistoryTable";
import formatPhone from "@/shared/lib/formatPhone";
import formatPrice from "@/shared/lib/formatPrice";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/ui/select";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  ArrowLeft,
  Calendar,
  CreditCard,
  DollarSign,
  Mail,
  MapPin,
  Phone,
  User,
  UsersIcon,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useParams } from "react-router-dom";
import { toast } from "sonner";

export default function FinanceDetailUser() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState<
    "bookings" | "details" | "history"
  >("bookings");
  const [historyPage, setHistoryPage] = useState(1);
  const params = useParams();

  const { data } = useQuery({
    queryKey: ["detail_order"],
    queryFn: () => getDetailOrder(Number(params.id)),
    select(data) {
      return data.data.data;
    },
  });

  const { mutate } = useMutation({
    mutationFn: ({
      id,
      body,
    }: {
      id: number;
      body: {
        order_status:
          | "pending_payment"
          | "pending_confirmation"
          | "cancelled"
          | "confirmed"
          | "completed";
      };
    }) => updateDetailOrder({ body, id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_order"] });
      queryClient.refetchQueries({ queryKey: ["list_order_user"] });
      toast.success(t("Status muvaffaqiyatli yangilandi"), {
        richColors: true,
        position: "top-center",
      });
    },
    onError: () => {
      toast.error(t("Statusni yangilashda xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { mutate: savedHistory } = useMutation({
    mutationFn: (body: {
      order: number;
      old_status:
        | "pending_payment"
        | "pending_confirmation"
        | "cancelled"
        | "confirmed"
        | "completed";
      new_status:
        | "pending_payment"
        | "pending_confirmation"
        | "cancelled"
        | "confirmed"
        | "completed";
    }) => savedOrderHistory(body),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_order"] });
      queryClient.refetchQueries({ queryKey: ["list_order_user"] });
      queryClient.refetchQueries({ queryKey: ["order_history"] });
      toast.success(t("Status muvaffaqiyatli yangilandi"), {
        richColors: true,
        position: "top-center",
      });
    },
    onError: () => {
      toast.error(t("Statusni yangilashda xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { data: history } = useQuery({
    queryKey: ["order_history", historyPage, params.id],
    queryFn: () =>
      getOrderHistory({
        page: historyPage,
        page_size: 10,
        order: Number(params.id),
      }),
  });

  const getStatusBadge = (status: OrderStatus["order_status"]) => {
    const base =
      "px-3 py-1 rounded-full text-sm font-medium inline-flex items-center gap-2";
    switch (status) {
      case "pending_confirmation":
        return (
          <span
            className={`${base} bg-yellow-900 text-yellow-400 border border-yellow-700`}
          >
            <div className="w-2 h-2 rounded-full bg-yellow-400"></div>
            {t("Paid")}
          </span>
        );
      case "pending_payment":
        return (
          <span
            className={`${base} bg-green-900 text-green-400 border border-green-700`}
          >
            <div className="w-2 h-2 rounded-full bg-green-400"></div>
            {t("Pending")}
          </span>
        );
      case "cancelled":
        return (
          <span
            className={`${base} bg-red-900 text-red-400 border border-red-700`}
          >
            <div className="w-2 h-2 rounded-full bg-red-400"></div>
            {t("Cancelled")}
          </span>
        );
      case "confirmed":
        return (
          <span
            className={`${base} bg-blue-900 text-blue-400 border border-blue-700`}
          >
            <div className="w-2 h-2 rounded-full bg-blue-400"></div>
            {t("Refunded")}
          </span>
        );
    }
  };

  return (
    <div className="min-h-screen w-full bg-gray-900 text-gray-100">
      <div className="w-[90%] mx-auto py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <Link
              to="/finance"
              className="bg-gray-800 p-2 rounded-lg hover:bg-gray-700 transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </Link>
            <div>
              <h1 className="text-3xl font-bold">
                {t("Foydalanuvchi moliyaviy tafsilotlari")}
              </h1>
              <p className="text-gray-400 mt-1">
                {data?.user.username} {t("uchun batafsil moliyaviy sharh")}
              </p>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="bg-gray-800 rounded-xl shadow">
          {/* Tabs */}
          <div className="flex border-b border-gray-700">
            <button
              className={`px-6 py-4 font-medium flex items-center gap-2 transition-colors ${
                activeTab === "bookings"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("bookings")}
            >
              <CreditCard className="w-4 h-4" />
              {t("Booking History")}
            </button>
            <button
              className={`px-6 py-4 font-medium flex items-center gap-2 transition-colors ${
                activeTab === "details"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("details")}
            >
              <User className="w-4 h-4" />
              {t("User Details")}
            </button>
            <button
              className={`px-6 py-4 font-medium flex items-center gap-2 transition-colors ${
                activeTab === "history"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("history")}
            >
              <Calendar className="w-4 h-4" />
              {t("Order History")}
            </button>
          </div>

          <div className="p-6">
            {activeTab === "bookings" && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold mb-4">
                  {t("Booking History")}
                </h2>
                <div className="bg-gray-700 p-6 rounded-lg hover:bg-gray-600 transition-colors">
                  <div className="flex justify-between items-start mb-4">
                    <div>
                      <h3 className="text-lg font-bold text-gray-100">
                        {data?.departure}
                      </h3>
                    </div>
                    <div className="flex items-center gap-3">
                      {data && getStatusBadge(data?.order_status)}
                      {data && (
                        <Select
                          onValueChange={(
                            value:
                              | "pending_payment"
                              | "pending_confirmation"
                              | "cancelled"
                              | "confirmed"
                              | "completed",
                          ) => {
                            mutate({
                              id: data.id,
                              body: { order_status: value },
                            });
                            savedHistory({
                              new_status: value,
                              old_status: data.order_status,
                              order: data.id,
                            });
                          }}
                          value={data.order_status}
                        >
                          <SelectTrigger className="w-[180px] bg-gray-800 border-gray-700 text-gray-200">
                            <SelectValue placeholder={t("Statusni tanlang")} />
                          </SelectTrigger>
                          <SelectContent className="bg-gray-800 text-gray-100 border-gray-700">
                            <SelectItem value="pending_payment">
                              {t("Pending")}
                            </SelectItem>
                            <SelectItem value="pending_confirmation">
                              {t("Paid")}
                            </SelectItem>
                            <SelectItem value="confirmed">
                              {t("Refunded")}
                            </SelectItem>
                            <SelectItem value="completed">
                              {t("Completed")}
                            </SelectItem>
                            <SelectItem value="cancelled">
                              {t("Cancelled")}
                            </SelectItem>
                          </SelectContent>
                        </Select>
                      )}
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                    <div className="flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Destination")}
                        </p>
                        <p className="text-gray-100">{data?.destination}</p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Travel Dates")}
                        </p>
                        <p className="text-gray-100">
                          {data?.departure_date} - {data?.arrival_time}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <User className="w-4 h-4 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Travelers")}
                        </p>
                        <p className="text-gray-100">
                          {data?.participant.length}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <DollarSign className="w-4 h-4 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-400">{t("Amount")}</p>
                        <p className="text-green-400 font-bold">
                          {data && formatPrice(data?.total_price, true)}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="flex justify-between items-center pt-4 border-t border-gray-600">
                    <div className="text-sm text-gray-400">
                      {t("Booked on")} {data?.departure_date}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {activeTab === "details" && (
              <div className="grid grid-cols-1 gap-8">
                {/* Personal Information */}
                <div>
                  <h3 className="text-lg font-bold mb-4">
                    {t("Personal Information")}
                  </h3>
                  <div className="space-y-4">
                    <div className="flex items-center gap-3 p-3 bg-gray-700 rounded-lg">
                      <User className="w-5 h-5 text-blue-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Full Name")}
                        </p>
                        <p className="text-gray-100">
                          {data?.user.first_name} {data?.user.last_name}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-3 p-3 bg-gray-700 rounded-lg">
                      <Phone className="w-5 h-5 text-green-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Phone Number")}
                        </p>
                        <p className="text-gray-100">
                          {data && formatPhone(data?.user.phone)}
                        </p>
                      </div>
                    </div>

                    {data?.user.email && (
                      <div className="flex items-center gap-3 p-3 bg-gray-700 rounded-lg">
                        <Mail className="w-5 h-5 text-yellow-400" />
                        <div>
                          <p className="text-sm text-gray-400">
                            {t("Email Address")}
                          </p>
                          <p className="text-gray-100">{data?.user.email}</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <UsersIcon className="w-5 h-5 text-purple-400" />
                    {t("Hamrohlar")}
                    <span className="ml-auto text-sm font-normal text-slate-500">
                      {data?.participant.length} ta
                    </span>
                  </h2>
                  <div className="space-y-4 max-h-[300px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-slate-700 hover:scrollbar-thumb-slate-600 scrollbar-track-transparent">
                    {data && data?.participant.length > 0 ? (
                      data?.participant.map((companion, index) => (
                        <div
                          key={index}
                          className="p-4 bg-slate-800/50 rounded-xl border border-slate-700/50"
                        >
                          <div className="flex items-start gap-4">
                            <div className="w-14 h-14 rounded-lg bg-gradient-to-br from-purple-600 to-pink-600 flex items-center justify-center flex-shrink-0 shadow-lg shadow-purple-500/20">
                              <User className="w-7 h-7 text-white" />
                            </div>
                            <div className="flex-1 space-y-3">
                              <div>
                                <h3 className="font-semibold text-slate-100 text-lg">
                                  {companion.first_name} {companion.last_name}
                                </h3>
                                <div className="flex items-center gap-2 mt-1">
                                  <span
                                    className={`px-2 py-1 text-xs rounded-full border ${
                                      companion.gender === "male"
                                        ? "bg-blue-500/20 text-blue-400 border-blue-500/30"
                                        : "bg-pink-500/20 text-pink-400 border-pink-500/30"
                                    }`}
                                  >
                                    {companion.gender === "male"
                                      ? t("Erkak")
                                      : t("Ayol")}
                                  </span>
                                </div>
                              </div>
                              <div className="grid grid-cols-2 gap-3 text-sm">
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Tug'ilgan sana")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {companion.birth_date}
                                  </p>
                                </div>
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Telefon raqami")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {formatPhone(companion.phone_number)}
                                  </p>
                                </div>
                              </div>
                              {companion.participant_pasport_image.length >
                                0 && (
                                <div>
                                  <p className="text-xs text-slate-500 mb-2">
                                    {t("Passport rasmlari")}:
                                  </p>
                                  <div className="flex gap-2">
                                    {companion.participant_pasport_image.map(
                                      (img) => (
                                        <a
                                          key={index}
                                          href={img.image}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className="w-20 h-20 rounded-lg bg-slate-700/50 flex items-center justify-center overflow-hidden border border-slate-600/50"
                                        >
                                          <img
                                            alt="passport image"
                                            src={img.image}
                                            className="w-full h-full"
                                          />
                                        </a>
                                      ),
                                    )}
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      ))
                    ) : (
                      <p className="text-sm text-slate-500 text-center py-4">
                        {t("Hozircha hamrohlar qo'shilmagan")}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            )}
            {activeTab === "history" && history?.data && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold mb-4">{t("Order History")}</h2>
                <OrderHistoryTable
                  t={t}
                  data={history.data.data}
                  onPageChange={setHistoryPage}
                />
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
