"use client";

import {
  agencyUser,
  agencyUserDelete,
  agencyUserUpdate,
  getDetailAgency,
  updateAgencyStatus,
} from "@/pages/agencies/lib/api";
import { AgencyUsersSection } from "@/pages/agencies/ui/AgencyUsersSection";
import formatPhone from "@/shared/lib/formatPhone";
import formatPrice from "@/shared/lib/formatPrice";
import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/ui/select";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  ArrowLeft,
  ChevronRight,
  DollarSign,
  Loader2,
  Package,
  Pencil,
  Percent,
  TrendingUp,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";

export default function AgencyDetailPage() {
  const params = useParams();
  const router = useNavigate();
  const { t } = useTranslation();
  const [edit, setEdit] = useState<boolean>(false);
  const queryClient = useQueryClient();
  const [openUser, setOpenUser] = useState<boolean>(false);
  const [user, setUser] = useState<{
    status: boolean;
    data: {
      id: number;
      phone: string;
      role: string;
      travel_agency: string;
      password: string;
    };
  } | null>(null);

  const { data, isLoading, refetch, isError } = useQuery({
    queryKey: ["detail_agency"],
    queryFn: () => getDetailAgency({ id: Number(params.id) }),
  });

  const { data: agency, isLoading: isLoadingUsers } = useQuery({
    queryKey: ["agency_user", params.id],
    queryFn: () => {
      return agencyUser(Number(params.id));
    },
  });

  const statusMutation = useMutation({
    mutationFn: (newStatus: "pending" | "approved" | "cancelled") =>
      updateAgencyStatus({
        id: Number(params.id),
        body: { status: newStatus },
      }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["detail_agency"] });
      queryClient.refetchQueries({ queryKey: ["all_agency"] });
      toast.success(t("Status muvaffaqiyatli o'zgartirildi"));
    },
    onError: () => {
      toast.error(t("Statusni o'zgartirishda xatolik yuz berdi"));
    },
  });

  const updateUserMutation = useMutation({
    mutationFn: (updatedUser: number) => agencyUserUpdate(updatedUser),
    onSuccess: (res) => {
      queryClient.refetchQueries({ queryKey: ["agency_user", params.id] });
      toast.success(t("Foydalanuvchi muvaffaqiyatli yangilandi"));
      setOpenUser(true);
      setUser(res.data);
      setEdit(false);
    },
    onError: () => {
      toast.error(t("Foydalanuvchini yangilashda xatolik"));
    },
  });

  const deleteUserMutation = useMutation({
    mutationFn: (userId: number) => agencyUserDelete(userId),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["agency_user", params.id] });
      toast.success(t("Foydalanuvchi muvaffaqiyatli o'chirildi"));
    },
    onError: () => {
      toast.error(t("Foydalanuvchini o'chirishda xatolik"));
    },
  });

  const handleStatusChange = (
    newStatus: "pending" | "approved" | "cancelled",
  ) => {
    statusMutation.mutate(newStatus);
  };

  const handleEditUser = (user: number) => {
    updateUserMutation.mutate(user);
  };

  const handleDeleteUser = (userId: number) => {
    deleteUserMutation.mutate(userId);
  };

  if (isLoading) {
    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) {
    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()}
          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 getStatusBadge = (status: string) => {
    switch (status) {
      case "pending":
        return (
          <Badge className="bg-yellow-500/20 text-yellow-300 border border-yellow-500/40">
            {t("Kutilmoqda")}
          </Badge>
        );
      case "approved":
        return (
          <Badge className="bg-green-500/20 text-green-300 border border-green-500/40">
            {t("Faol")}
          </Badge>
        );
      case "cancelled":
        return (
          <Badge className="bg-red-500/20 text-red-300 border border-red-500/40">
            {t("Cancelled")}
          </Badge>
        );
      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gray-900 w-full">
      <div className="container mx-auto px-4 py-8 max-w-full">
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              size="icon"
              onClick={() => router(-1)}
              className="rounded-full border-gray-700 bg-gray-800 hover:bg-gray-700"
            >
              <ArrowLeft className="w-5 h-5 text-gray-300" />
            </Button>
            <div>
              <div className="flex gap-2">
                <h1 className="text-4xl font-bold text-white">
                  {data?.data.data.name}
                </h1>
                <p className="text-md text-muted-foreground">
                  {data?.data.data.custom_id}
                </p>
              </div>
              <p className="text-gray-400 mt-1">
                {t("Egasi")}: {data?.data.data.owner_user}
              </p>
            </div>
          </div>

          {/* Status Select */}
          <div className="flex items-center gap-3">
            {data && getStatusBadge(data?.data.data.status)}
            <Select
              value={data?.data.data.status}
              onValueChange={handleStatusChange}
              disabled={statusMutation.isPending}
            >
              <SelectTrigger className="w-[180px] border-gray-700 bg-gray-800 text-white hover:bg-gray-700 focus:ring-blue-500">
                <SelectValue placeholder={t("Status tanlang")} />
              </SelectTrigger>
              <SelectContent className="bg-gray-800 border-gray-700">
                <SelectItem
                  value="pending"
                  className="text-yellow-300 focus:bg-gray-700 focus:text-yellow-300"
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-yellow-500" />
                    {t("Kutilmoqda")}
                  </div>
                </SelectItem>
                <SelectItem
                  value="approved"
                  className="text-green-300 focus:bg-gray-700 focus:text-green-300"
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-green-500" />
                    {t("Faol")}
                  </div>
                </SelectItem>
                <SelectItem
                  value="cancelled"
                  className="text-red-300 focus:bg-gray-700 focus:text-red-300"
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500" />
                    {t("Cancelled")}
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <Card className="border border-gray-700 shadow-lg hover:shadow-xl transition-shadow bg-gray-800">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-400">
                {t("Jami turlar")}
              </CardTitle>
              <Package className="w-5 h-5 text-blue-400" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-white">
                {data?.data.data.tour_count}
              </div>
              <p className="text-xs text-gray-400 mt-1">
                {t("Qo'shilgan turlar soni")}
              </p>
            </CardContent>
          </Card>

          {/* Sold Tours */}
          <Card className="border border-gray-700 shadow-lg hover:shadow-xl transition-shadow bg-gray-800">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-400">
                {t("Sotilgan turlar soni")}
              </CardTitle>
              <TrendingUp className="w-5 h-5 text-green-400" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-white">
                {data?.data.data.ticket_sold_count}
              </div>
              <p className="text-xs text-gray-400 mt-1">
                {t("Jami sotilgan turlar")}
              </p>
            </CardContent>
          </Card>

          {/* Profit Percent */}
          <Card className="border border-gray-700 shadow-lg hover:shadow-xl transition-shadow bg-gray-800">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-400">
                {t("Ulush foizi")}
              </CardTitle>
              <Percent className="w-5 h-5 text-purple-400" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-white">
                {data?.data.data.share_percentage}%
              </div>
              <p className="text-xs text-gray-400 mt-1">
                {t("Har bir sotuvdan")}
              </p>
            </CardContent>
          </Card>

          {/* Total Profit */}
          <Card className="border border-gray-700 shadow-lg hover:shadow-xl transition-shadow bg-gray-800">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-gray-400">
                {t("Umumiy daromad")}
              </CardTitle>
              <DollarSign className="w-5 h-5 text-yellow-400" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-white">
                {data && data.data.data.total_income !== 0
                  ? formatPrice(data?.data.data.total_income, true)
                  : 0}
              </div>
              <p className="text-xs text-gray-400 mt-1">{t("so'm daromad")}</p>
            </CardContent>
          </Card>
        </div>

        <Card className="border border-gray-700 shadow-lg bg-gray-800 mb-8">
          <CardHeader>
            <CardTitle className="text-2xl text-white flex items-center justify-between">
              <p>{t("Umumiy ma'lumot")}</p>
              <Button
                onClick={() => router(`/agency/${params.id}/edit`)}
                className="bg-gradient-to-r cursor-pointer from-blue-600 to-indigo-700 hover:from-blue-700 hover:to-indigo-800 text-white shadow-lg shadow-blue-500/20"
              >
                <Pencil />
                {t("Tahrirlash")}
              </Button>
            </CardTitle>
            <p className="text-gray-400">
              {t("Agentlik haqida batafsil ma'lumot")}
            </p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {/* Address */}
              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("Manzil")}</p>
                <p className="text-base font-medium text-white">
                  {data?.data.data.addres || t("Ma'lumot yo'q")}
                </p>
              </div>

              {/* Email */}
              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("Email")}</p>
                <p className="text-base font-medium text-white break-all">
                  {data?.data.data.email || t("Ma'lumot yo'q")}
                </p>
              </div>

              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("Telefon raqami")}</p>
                <p className="text-base font-medium text-white">
                  {data
                    ? formatPhone(data?.data.data.phone)
                    : t("Ma'lumot yo'q")}
                </p>
              </div>

              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("Veb-sayt")}</p>
                {data?.data.data.web_site ? (
                  <a
                    href={data.data.data.web_site}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-base font-medium text-blue-400 hover:text-blue-300 hover:underline break-all"
                  >
                    {data.data.data.web_site}
                  </a>
                ) : (
                  <p className="text-base font-medium text-white">
                    {t("Ma'lumot yo'q")}
                  </p>
                )}
              </div>

              {/* Custom ID */}
              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("ID raqami")}</p>
                <p className="text-base font-medium text-white">
                  {data?.data.data.custom_id}
                </p>
              </div>

              {/* Share Percentage */}
              <div className="space-y-2">
                <p className="text-sm text-gray-400">{t("Komissiya")}</p>
                <p className="text-base font-medium text-white">
                  {data?.data.data.share_percentage}%
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        {agency?.data.data && (
          <div className="mb-8">
            <AgencyUsersSection
              edit={edit}
              setEdit={setEdit}
              users={
                Array.isArray(agency?.data.data)
                  ? agency?.data.data
                  : [agency?.data.data]
              }
              onEdit={handleEditUser}
              onDelete={handleDeleteUser}
              isLoading={isLoadingUsers}
            />
          </div>
        )}

        <Card className="border border-gray-700 shadow-lg bg-gray-800">
          <CardHeader>
            <CardTitle className="text-2xl text-white">
              {t("Qo'shilgan turlar")}
            </CardTitle>
            <p className="text-gray-400">
              {t("Firma tomonidan qo'shilgan barcha turlar ro'yxati")}
            </p>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {data?.data.data.tickets.map((tour) => (
                <Link key={tour.id} to={`/tours/${tour.id}`} className="block">
                  <div className="p-5 border border-gray-700 rounded-xl hover:bg-gray-700 transition-all cursor-pointer group bg-gray-800">
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <h3 className="text-lg font-semibold text-white group-hover:text-blue-400 transition-colors">
                            {tour.title}
                          </h3>
                        </div>
                        <p className="text-sm text-gray-400 mb-3">
                          {tour.destination}
                        </p>
                        <div className="flex items-center gap-6 text-sm">
                          <div className="flex items-center gap-2">
                            <Package className="w-4 h-4 text-gray-400" />
                            <span className="text-gray-400">
                              {t("Sotilgan")}:
                            </span>
                            <span className="font-semibold text-white">
                              {tour.total_income}
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            <DollarSign className="w-4 h-4 text-gray-400" />
                            <span className="text-gray-400">
                              {t("Daromad")}:
                            </span>
                            <span className="font-semibold text-yellow-400">
                              {tour.total_income === 0
                                ? 0
                                : formatPrice(tour.total_income, true)}
                            </span>
                          </div>
                        </div>
                      </div>
                      <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-blue-400 transition-colors" />
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
      <Dialog open={openUser} onOpenChange={() => {}}>
        <DialogContent className="bg-gray-900 text-white sm:max-w-sm rounded-2xl">
          <DialogHeader>
            <DialogTitle className="text-lg font-semibold">
              {t("Yangi foydalanuvchi ma'lumotlari")}
            </DialogTitle>
            <DialogDescription className="text-gray-400 text-sm">
              {t("Agentlik uchun tizimga kirish ma'lumotlari")}
            </DialogDescription>
          </DialogHeader>

          {user && (
            <div className="space-y-4 mt-4">
              <div>
                <p className="text-gray-400 text-sm mb-1">
                  {t("Telefon raqam (login)")}
                </p>
                <p className="text-lg font-medium">
                  {formatPhone(user.data.phone)}
                </p>
              </div>

              <div>
                <p className="text-gray-400 text-sm mb-1">{t("Parol")}</p>
                <p className="text-lg font-semibold text-green-400">
                  {user.data.password}
                </p>
              </div>
            </div>
          )}

          <DialogFooter className="mt-6">
            <Button
              onClick={() => setOpenUser(false)}
              className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white px-5 py-2 rounded-md hover:opacity-90"
            >
              {t("Yopish")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
