"use client";

import { getDetailAgencyOrder } from "@/pages/finance/lib/api";
import { PayDialog } from "@/pages/finance/ui/PayDialog";
import { PaymentHistory } from "@/pages/finance/ui/PaymentHistory";
import formatDate from "@/shared/lib/formatDate";
import formatPhone from "@/shared/lib/formatPhone";
import formatPrice from "@/shared/lib/formatPrice";
import { Button } from "@/shared/ui/button";
import { Card, CardHeader } from "@/shared/ui/card";
import { useQuery } from "@tanstack/react-query";
import {
  ArrowLeft,
  Banknote,
  DollarSign,
  Eye,
  Mail,
  MapPin,
  Phone,
  Plane,
  Star,
  TrendingUp,
  Users,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useParams } from "react-router-dom";

export default function FinanceDetailTour() {
  const [openPayDialog, setOpenPayDialog] = useState(false);
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<
    "overview" | "bookings" | "reviews" | "payment"
  >("overview");
  const params = useParams();

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

  const renderStars = (rating: number) => {
    return (
      <div className="flex items-center gap-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <Star
            key={star}
            className={`w-4 h-4 ${
              star <= rating
                ? "text-yellow-400 fill-yellow-400"
                : "text-gray-600"
            }`}
          />
        ))}
      </div>
    );
  };

  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">{data?.name}</h1>
            </div>
          </div>
          <div className="flex justify-end mt-8">
            <Button
              onClick={() => setOpenPayDialog(true)}
              className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg"
            >
              {t("Qolgan summani to‘lash")}
            </Button>
          </div>
          {data && (
            <PayDialog
              open={openPayDialog}
              onClose={() => setOpenPayDialog(false)}
              agencyId={data?.id}
            />
          )}
        </div>

        {/* Tour Summary Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div className="bg-gray-800 p-6 rounded-xl shadow">
            <div className="flex items-center justify-between">
              <p className="text-gray-400 font-medium">
                {t("To'langan summa")}
              </p>
              <DollarSign className="text-green-400 w-6 h-6" />
            </div>
            <p className="text-2xl font-bold text-green-400 mt-3">
              {data && formatPrice(data?.paid, true)}
            </p>
          </div>

          <div className="bg-gray-800 p-6 rounded-xl shadow">
            <div className="flex items-center justify-between">
              <p className="text-gray-400 font-medium">
                {t("Kutilayotgan summa")}
              </p>
              <TrendingUp className="text-yellow-400 w-6 h-6" />
            </div>
            <p className="text-2xl font-bold text-yellow-400 mt-3">
              {data && formatPrice(data.pending, true)}
            </p>
          </div>

          <div className="bg-gray-800 p-6 rounded-xl shadow">
            <div className="flex items-center justify-between">
              <p className="text-gray-400 font-medium">{t("Total Bookings")}</p>
              <Users className="text-blue-400 w-6 h-6" />
            </div>
            <p className="text-2xl font-bold text-blue-400 mt-3">
              {data?.ticket_sold_count}
            </p>
          </div>

          <div className="bg-gray-800 p-6 rounded-xl shadow">
            <div className="flex items-center justify-between">
              <p className="text-gray-400 font-medium">{t("Average Rating")}</p>
              <Star className="text-yellow-400 w-6 h-6" />
            </div>
            <p className="text-2xl font-bold text-yellow-400 mt-3">
              {data?.rating}/5
            </p>
          </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 === "overview"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("overview")}
            >
              <Eye className="w-4 h-4" />
              {t("Umumiy ma'lumot")}
            </button>
            <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")}
            >
              <Users className="w-4 h-4" />
              {t("Bookings")} ({data?.total_booking_count})
            </button>
            <button
              className={`px-6 py-4 font-medium flex items-center gap-2 transition-colors ${
                activeTab === "reviews"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("reviews")}
            >
              <Star className="w-4 h-4" />
              {t("Reviews")}
            </button>
            <button
              className={`px-6 py-4 font-medium flex items-center gap-2 transition-colors ${
                activeTab === "payment"
                  ? "text-blue-400 border-b-2 border-blue-400"
                  : "text-gray-400 hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("payment")}
            >
              <Banknote className="w-4 h-4" />
              {t("To'lovlar tarixi")}
            </button>
          </div>
          <div className="p-6">
            {activeTab === "overview" && (
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Tour Information */}
                <div className="lg:col-span-2">
                  <h3 className="text-lg font-bold mb-4">
                    {t("Umumiy ma'lumot")}
                  </h3>
                  <div className="space-y-4">
                    <div className="flex items-center gap-3 p-3 bg-gray-700 rounded-lg">
                      <Plane className="w-5 h-5 text-blue-400" />
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Agentlik nomi")}
                        </p>
                        <p className="text-gray-100 font-medium">
                          {data?.name}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-3 p-3 bg-gray-700 rounded-lg">
                      <MapPin className="w-5 h-5 text-green-400" />
                      <div>
                        <p className="text-sm text-gray-400">{t("Manzili")}</p>
                        <p className="text-gray-100">{data?.addres}</p>
                      </div>
                    </div>

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

                    <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("E-mail")}</p>
                        <p className="text-gray-100">{data?.email}</p>
                      </div>
                    </div>

                    <div className="p-3 bg-gray-700 rounded-lg">
                      <p className="text-sm text-gray-400 mb-2">
                        {t("Id raqami va ulushi")}
                      </p>
                      <div className="flex gap-10">
                        <p className="text-gray-100">
                          {t("Id")}: {data?.custom_id}
                        </p>
                        <p className="text-gray-100">
                          {t("Ulushi")}: {data?.share_percentage}%
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                {data && (
                  <div className="grid gap-4">
                    <Card className="bg-gray-800 text-white border-gray-700">
                      <CardHeader>
                        {t("Qo'shilgan turlar")}
                        <p className="text-2xl font-bold text-purple-400">
                          {data.ticket_count}
                        </p>
                      </CardHeader>
                    </Card>

                    <Card className="bg-gray-800 text-white border-gray-700">
                      <CardHeader>
                        {t("Umumiy daromad")}
                        <p className="text-2xl font-bold text-blue-400">
                          {formatPrice(data.total_income, true)}
                        </p>
                      </CardHeader>
                    </Card>

                    {/* Platforma daromadi */}
                    <Card className="bg-gray-800 text-white border-gray-700">
                      <CardHeader>
                        {t("Platformaga daromadi")}
                        <p className="text-2xl font-bold text-purple-400">
                          {formatPrice(data.platform_income, true)}
                        </p>
                      </CardHeader>
                    </Card>

                    <Card className="bg-gray-800 text-white border-gray-700">
                      <CardHeader>
                        {t("Agentlik daromadi")}
                        <p className="text-2xl font-bold text-cyan-400">
                          {formatPrice(data.paid + data.pending, true)}
                        </p>
                      </CardHeader>
                    </Card>
                  </div>
                )}
              </div>
            )}

            {activeTab === "bookings" && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold mb-4">
                  {t("Recent Bookings")}
                </h2>
                {data?.orders.map((purchase) => (
                  <div
                    key={purchase.id}
                    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">
                          {purchase.user.first_name} {purchase.user.last_name}
                        </h3>
                        <p className="text-gray-400 text-sm">
                          {formatPhone(purchase.user.contact)}
                        </p>
                      </div>
                      {/* {getStatusBadge(purchase.)} */}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Travel Date")}
                        </p>
                        <p className="text-gray-100 font-medium">
                          {purchase.departure_date}
                        </p>
                      </div>

                      <div>
                        <p className="text-sm text-gray-400">
                          {t("Booking Date")}
                        </p>
                        <p className="text-gray-100">
                          {formatDate.format(purchase.created_at, "DD-MM-YYYY")}
                        </p>
                      </div>

                      <div>
                        <p className="text-sm text-gray-400">{t("Amount")}</p>
                        <p className="text-green-400 font-bold">
                          {formatPrice(purchase.total_price, true)}
                        </p>
                      </div>
                    </div>

                    <div className="flex justify-end items-center pt-4 border-t border-gray-600">
                      <Link
                        to={`/bookings/${purchase.id}`}
                        className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        {t("Batafsil")}
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {activeTab === "reviews" && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold mb-4">Customer Reviews</h2>
                {data?.comments.map((purchase) => (
                  <div
                    key={purchase.created}
                    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">
                          {purchase.user.first_name} {purchase.user.last_name}
                        </h3>
                        <p className="text-gray-400 text-sm">
                          {formatDate.format(purchase.created, "DD-MM-YYYY")}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        {renderStars(purchase.rating)}
                        <span className="text-gray-300">{purchase.rating}</span>
                      </div>
                    </div>

                    <p className="text-gray-100 mb-4">{purchase.text}</p>
                  </div>
                ))}
              </div>
            )}

            {activeTab === "payment" && <PaymentHistory />}
          </div>
        </div>
      </div>
    </div>
  );
}
