"use client";

import {
  getAllAmenities,
  hotelBadge,
  hotelFeature,
  hotelFeatureType,
  hotelTarif,
  hotelTransport,
  hotelType,
} from "@/pages/tours/lib/api";
import Amenities from "@/pages/tours/ui/Amenities";
import BadgeTable from "@/pages/tours/ui/BadgeTable";
import FeaturesTable from "@/pages/tours/ui/FeaturesTable";
import FeaturesTableType from "@/pages/tours/ui/FeaturesTableType";
import MealTable from "@/pages/tours/ui/MealTable";
import TarifTable from "@/pages/tours/ui/TarifTable";
import TransportTable from "@/pages/tours/ui/TransportTable";
import { Button } from "@/shared/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/ui/tabs";

import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, Loader2 } from "lucide-react";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } from "react-router-dom";

const ToursSetting: React.FC = () => {
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState("badge");
  const [featureId, setFeatureId] = useState<number | null>(null);
  const navigate = useNavigate();

  const page = parseInt(searchParams.get("page") || "1", 10);
  const pageSize = parseInt(searchParams.get("pageSize") || "10", 10);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["all_badge", page, pageSize],
    queryFn: () => hotelBadge({ page, page_size: pageSize }),
    select: (res) => res.data.data,
  });

  const pageTarif = parseInt(searchParams.get("pageTarif") || "1", 10);
  const pageSizeTarif = parseInt(searchParams.get("pageTarifSize") || "10", 10);

  const {
    data: tarifData,
    isLoading: tarifLoad,
    isError: tarifError,
    refetch: tarifRef,
  } = useQuery({
    queryKey: ["all_tarif", pageTarif, pageSizeTarif],
    queryFn: () => hotelTarif({ page: pageTarif, page_size: pageSizeTarif }),
    select: (res) => res.data.data,
  });

  const pageTransport = parseInt(searchParams.get("pageTransport") || "1", 10);
  const pageSizeTransport = parseInt(
    searchParams.get("pageTransportSize") || "10",
    10,
  );

  const {
    data: transportData,
    isLoading: transportLoad,
    isError: transportError,
    refetch: transportRef,
  } = useQuery({
    queryKey: ["all_transport", pageTransport, pageSizeTransport],
    queryFn: () =>
      hotelTransport({ page: pageTransport, page_size: pageSizeTransport }),
    select: (res) => res.data.data,
  });

  const pageType = parseInt(searchParams.get("pageType") || "1", 10);
  const pageSizeType = parseInt(searchParams.get("pageTypeSize") || "10", 10);

  const {
    data: typeData,
    isLoading: typeLoad,
    isError: typeError,
    refetch: typeRef,
  } = useQuery({
    queryKey: ["all_type", pageType, pageSizeType],
    queryFn: () => hotelType({ page: pageType, page_size: pageSizeType }),
    select: (res) => res.data.data,
  });

  const pageFeature = parseInt(searchParams.get("pageFeature") || "1", 10);
  const pageSizeFeature = parseInt(
    searchParams.get("pageSizeFeature") || "10",
    10,
  );

  const {
    data: featureData,
    isLoading: featureLoad,
    isError: featureError,
    refetch: featureRef,
  } = useQuery({
    queryKey: ["all_feature", pageFeature, pageSizeFeature],
    queryFn: () =>
      hotelFeature({ page: pageFeature, page_size: pageSizeFeature }),
    select: (res) => res.data.data,
  });

  const {
    data: featureTypeData,
    isLoading: featureTypeLoad,
    isError: featureTypeError,
    refetch: featureTypeRef,
  } = useQuery({
    queryKey: ["all_feature_type", pageFeature, pageSizeFeature, featureId],
    queryFn: () =>
      hotelFeatureType({
        page: pageFeature,
        page_size: pageSizeFeature,
        feature_type: featureId!,
      }),
    select: (res) => res.data.data,
    enabled: !!featureId,
  });

  const pageAmenities = parseInt(searchParams.get("pageAmenities") || "1", 10);
  const pageSizeAmenities = parseInt(
    searchParams.get("pageSizeAmenities") || "10",
    10,
  );

  const {
    data: amenitiesData,
    isLoading: amenitiesLoad,
    isError: amenitiesError,
    refetch: amenitiesRef,
  } = useQuery({
    queryKey: ["all_amenities", page, pageSize],
    queryFn: () => getAllAmenities({ page, page_size: pageSize }),
    select: (res) => res.data.data,
  });

  if (
    isLoading ||
    tarifLoad ||
    transportLoad ||
    typeLoad ||
    featureLoad ||
    featureTypeLoad ||
    amenitiesLoad
  ) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 text-white gap-4 w-full">
        <Loader2 className="w-10 h-10 animate-spin text-cyan-400" />
        <p className="text-slate-400">{t("Ma'lumotlar yuklanmoqda...")}</p>
      </div>
    );
  }

  if (
    isError ||
    tarifError ||
    transportError ||
    typeError ||
    featureError ||
    featureTypeError ||
    amenitiesError
  ) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 w-full text-center text-white gap-4">
        <AlertTriangle className="w-10 h-10 text-red-500" />
        <p className="text-lg">
          {t("Ma'lumotlarni yuklashda xatolik yuz berdi.")}
        </p>
        <Button
          onClick={() => {
            refetch();
            tarifRef();
            transportRef();
            typeRef();
            featureRef();
            featureTypeRef();
            amenitiesRef();
          }}
          className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-lg px-5 py-2 hover:opacity-90"
        >
          {t("Qayta urinish")}
        </Button>
      </div>
    );
  }

  const handleTabChange = (value: string) => {
    setActiveTab(value);
    navigate({
      pathname: window.location.pathname,
      search: "",
    });
  };

  return (
    <div className="min-h-screen bg-gray-900 p-6 w-full text-white">
      <div className="max-w-[90%] mx-auto space-y-6">
        <Tabs
          value={activeTab}
          onValueChange={handleTabChange}
          className="w-full"
        >
          <TabsList className="w-full">
            <TabsTrigger value="badge">{t("Belgilar (Badge)")}</TabsTrigger>
            <TabsTrigger value="tarif">{t("Tariflar")}</TabsTrigger>
            <TabsTrigger value="transport">{t("Transport")}</TabsTrigger>
            <TabsTrigger value="meal">{t("Qulayliklar")}</TabsTrigger>
            <TabsTrigger value="hotel_type">{t("Otel turlari")}</TabsTrigger>
            <TabsTrigger value="hotel_features">
              {t("Otel sharoitlari")}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="badge" className="space-y-4">
            <BadgeTable data={data} page={page} pageSize={pageSize} />
          </TabsContent>
          <TabsContent value="tarif" className="space-y-4">
            <TarifTable
              data={tarifData}
              page={pageTarif}
              pageSize={pageSizeTarif}
            />
          </TabsContent>
          <TabsContent value="transport" className="space-y-4">
            <TransportTable
              data={transportData}
              page={pageTransport}
              pageSize={pageSizeTransport}
            />
          </TabsContent>
          <TabsContent value="meal" className="space-y-4">
            <Amenities
              data={amenitiesData}
              page={pageAmenities}
              pageSize={pageSizeAmenities}
            />
          </TabsContent>
          <TabsContent value="hotel_type" className="space-y-4">
            <MealTable
              data={typeData}
              page={pageTransport}
              pageSize={pageSizeTransport}
            />
          </TabsContent>
          <TabsContent value="hotel_features" className="space-y-4">
            <FeaturesTable
              data={featureData}
              page={pageFeature}
              pageSize={pageSizeFeature}
              setActiveTab={setActiveTab}
              setFeatureId={setFeatureId}
            />
          </TabsContent>
          <TabsContent value="feature_type" className="space-y-4">
            <FeaturesTableType
              data={featureTypeData}
              page={pageFeature}
              featureId={featureId}
              pageSize={pageSizeFeature}
            />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default ToursSetting;
