import {
  createTourAdmin,
  getSupportAgency,
  updateTour,
} from "@/pages/support/lib/api";
import type { GetSupportAgencyRes } from "@/pages/support/lib/types";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Loader2, XIcon } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { toast } from "sonner";

const SupportAgency = () => {
  const [query, setQuery] = useState("");
  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 { t } = useTranslation();
  const [selected, setSelected] = useState<GetSupportAgencyRes | null>(null);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["support_agency"],
    queryFn: () =>
      getSupportAgency({ page: 1, page_size: 10, search: "", status: "" }),
  });

  const { mutate: updateTours } = useMutation({
    mutationFn: ({
      id,
      body,
    }: {
      id: number;
      body: {
        status: "pending" | "approved" | "cancelled";
      };
    }) => updateTour({ body, id }),
    onSuccess: (res) => {
      queryClient.refetchQueries({ queryKey: ["support_agency"] });
      setOpenUser(true);
      setUser(res.data);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { mutate: createAdmin } = useMutation({
    mutationFn: (id: number) => createTourAdmin(id),
    onSuccess: (res) => {
      queryClient.refetchQueries({ queryKey: ["support_agency"] });
      setOpenUser(true);
      setUser(res.data);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  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>
    );
  }

  return (
    <div className="p-4 w-full mx-auto">
      <h2 className="text-2xl font-semibold mb-4">
        {t("Agentlik so'rovlari")}
      </h2>

      <div className="flex gap-3 mb-6">
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={t("Qidiruv (ism, email yoki telefon)...")}
          className="flex-1 p-2 border rounded-md focus:outline-none focus:ring"
        />
        <button
          onClick={() => setQuery("")}
          className="px-4 py-2 bg-gray-500 rounded-md hover:bg-gray-300 transition"
        >
          {t("Tozalash")}
        </button>
      </div>

      {data && data.data.data.results.length === 0 ? (
        <div className="text-center text-gray-500">{t("So'rov topilmadi")}</div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {data &&
            data.data.data.results.map((r) => (
              <div
                key={r.id}
                className="border rounded-lg p-4 shadow-sm hover:shadow-md transition bg-gray-800 text-white"
              >
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="text-lg font-medium">{r.name}</h3>
                    <p className="text-md">{r.addres}</p>
                  </div>
                  <div className="text-md">{formatPhone(r.phone)}</div>
                </div>

                <div className="mt-3 text-sm text-white">
                  <div>
                    <strong>{t("Email")}:</strong>{" "}
                    <Link to={`mailto:${r.email}`} className="text-white">
                      {r.email}
                    </Link>
                  </div>
                  {r.web_site && (
                    <div>
                      <strong>{t("Veb-sayt")}:</strong>{" "}
                      <a
                        href={r.web_site}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-white hover:underline"
                      >
                        {r.web_site.replace(/^https?:\/\//, "")}
                      </a>
                    </div>
                  )}
                </div>

                <div className="mt-4 flex gap-2">
                  <button
                    onClick={() => setSelected(r)}
                    className="px-3 py-1 rounded bg-blue-600 text-white text-sm hover:bg-blue-700 transition"
                  >
                    {t("Tafsilotlar")}
                  </button>
                  <Link
                    to={`mailto:${r.email}`}
                    className="px-3 py-1 rounded border text-sm transition"
                  >
                    {t("Javob yozish")}
                  </Link>
                </div>
              </div>
            ))}
        </div>
      )}

      {selected && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          onClick={() => setSelected(null)}
        >
          <div
            className="bg-gray-900 rounded-lg max-w-2xl w-full p-6 relative max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={() => setSelected(null)}
              className="absolute top-3 right-3 text-white cursor-pointer text-2xl"
            >
              <XIcon />
            </button>

            <h3 className="text-xl font-semibold mb-2">{selected.name}</h3>
            <p className="text-md text-white mb-4">{selected.addres}</p>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <div className="text-md text-white">{t("Email")}</div>
                <a
                  href={`mailto:${selected.email}`}
                  className="block text-white hover:underline"
                >
                  {selected.email}
                </a>
              </div>

              <div>
                <div className="text-md text-white">{t("Telefon raqam")}</div>
                <div>{formatPhone(selected.phone ?? "")}</div>
              </div>

              <div>
                <div className="text-xs text-white">{t("Veb-sayt")}</div>
                {selected.web_site ? (
                  <a
                    href={selected.web_site}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block text-white hover:underline"
                  >
                    {selected.web_site}
                  </a>
                ) : (
                  <div className="text-gray-400">—</div>
                )}
              </div>
            </div>

            <div className="mt-5">
              <div className="text-sm font-medium mb-2">{t("Hujjatlar")}</div>
              {selected.travel_agency_documents &&
              selected.travel_agency_documents.length > 0 ? (
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {selected.travel_agency_documents.map((doc, i) => {
                    const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(
                      doc.file,
                    );
                    const fileName = doc.file.split("/").pop();

                    return (
                      <a
                        key={i}
                        href={doc.file}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="group relative aspect-square border-2 border-gray-200 rounded-lg overflow-hidden hover:border-blue-500 transition"
                      >
                        {isImage ? (
                          <img
                            src={doc.file}
                            alt={`Hujjat ${i + 1}`}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex flex-col items-center justify-center bg-gray-800 text-gray-300">
                            {/* <img
                              src="/icons/document-placeholder.png"
                              alt="Document icon"
                              className="w-10 h-10 mb-2 opacity-70"
                            /> */}
                            <span className="text-xl text-center truncate px-2">
                              {fileName}
                            </span>
                          </div>
                        )}

                        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition flex items-end">
                          <div className="w-full bg-gradient-to-t from-black/70 to-transparent p-2">
                            <span className="text-white text-xs font-medium">
                              {t("Hujjat")} {i + 1}
                            </span>
                          </div>
                        </div>
                      </a>
                    );
                  })}
                </div>
              ) : (
                <div className="text-gray-500">{t("Hujjat topilmadi")}</div>
              )}
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => {
                  setSelected(null);
                  createAdmin(selected.id);
                  updateTours({
                    body: { status: "approved" },
                    id: selected.id,
                  });
                }}
                className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition"
              >
                {t("Qabul qilish")}
              </button>
              <button
                onClick={() => {
                  setSelected(null);
                  updateTours({
                    body: { status: "cancelled" },
                    id: selected.id,
                  });
                }}
                className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition"
              >
                {t("Rad etish")}
              </button>
            </div>
          </div>
        </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>
  );
};

export default SupportAgency;
