import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { BACKEND_URL, getFrontEnv, useGoogleAuth } from "@/hooks/useGoogleAuth";
import { useAuth } from "@/src/contexts/authContext";
import { ArrowLeft, Folder, Loader2 } from "lucide-react";
import { useEffect, useState } from "react";

interface SelectDocComponentProps {
  loja: string;
  onSelecionar: (doc: any) => void;
}

const SelectDocComponent = ({
  loja,
  onSelecionar,
}: SelectDocComponentProps) => {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [docSelecionado, setDocSelecionado] = useState<any | null>(null);
  const [path, setPath] = useState<{ id: string; name: string }[]>([]); // caminho atual
  const { valuesSession } = useAuth();
  const { session } = valuesSession();
  const { connected } = useGoogleAuth();
  // -------------------------------
  // FUNÇÕES GOOGLE DRIVE
  // -------------------------------
  const FOLDER_MIME = "application/vnd.google-apps.folder";
  const DOC_MIME = "application/vnd.google-apps.document";
  const SHORTCUT_MIME = "application/vnd.google-apps.shortcut";
  // Lista conteúdo de uma pasta (pastas + arquivos Google Docs)
  async function listFolderContents(folderId: string) {
    const sigla = session.sigla;
    const env = getFrontEnv();
    const params = new URLSearchParams({
      folderId,
      lojaId: loja,
      sigla,
      env: "prod",
    });

    const res = await fetch(
      `${BACKEND_URL}/auth/drive/list?${params.toString()}`,
      { credentials: "include" },
    );

    if (!res.ok) {
      throw new Error("Erro ao listar Drive");
    }

    const data = await res.json();
    return data.files;
  }

  // -------------------------------
  // CARREGAR RAIZ (root)
  // -------------------------------
  useEffect(() => {
    // if (!connected) return;

    const loadRoot = async () => {
      setLoading(true);
      try {
        const rootItems = await listFolderContents("root");
        setItems(rootItems);
        setPath([{ id: "root", name: "Meu Drive" }]);
      } catch (e) {
        console.error("Erro ao carregar Google Drive:", e);
      }
      setLoading(false);
    };

    loadRoot();
  }, []);

  // -------------------------------
  // ABRIR PASTA
  // -------------------------------
  async function abrirPasta(item: any) {
    if (item.effectiveMimeType !== FOLDER_MIME) return;

    setLoading(true);
    const conteudo = await listFolderContents(item.effectiveId);
    setItems(conteudo);
    setPath((prev) => [...prev, { id: item.effectiveId, name: item.name }]);
    setLoading(false);
  }

  // -------------------------------
  // VOLTAR UMA PASTA
  // -------------------------------
  async function voltar() {
    if (path.length <= 1) return; // já está na raiz

    const newPath = [...path];
    newPath.pop(); // remove a pasta atual

    const prevFolder = newPath[newPath.length - 1];

    setPath(newPath);
    setLoading(true);
    const conteudo = await listFolderContents(prevFolder.id);
    setItems(conteudo);
    setLoading(false);
  }

  // -------------------------------
  // RENDER
  // -------------------------------
  return (
    <div>
      <h2 className="text-xl font-semibold text-gray-800 mb-4">
        Navegar Drive → Selecionar Documento
      </h2>

      {/* Caminho atual (breadcrumb) */}
      <div className="flex items-center gap-2 text-sm text-gray-500 mb-4">
        {path.map((p, i) => (
          <span key={p.id}>
            {i > 0 && " / "}
            {p.name}
          </span>
        ))}
      </div>

      {/* Botão Voltar */}
      {path.length > 1 && (
        <Button
          variant="outline"
          className="mb-4 flex items-center gap-2"
          onClick={voltar}
        >
          <ArrowLeft size={16} /> Voltar
        </Button>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-10 text-gray-600">
          <Loader2 className="animate-spin mr-2" />
          Carregando...
        </div>
      ) : (
        <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-4 max-h-[60vh] overflow-y-auto">
          {items.map((item) => (
            <Card
              key={item.id}
              onClick={() => {
                if (item.effectiveMimeType === FOLDER_MIME) {
                  abrirPasta(item);
                } else {
                  setDocSelecionado(item);
                }
              }}
              className={`p-4 cursor-pointer border-2 transition-all ${
                docSelecionado?.id === item.id
                  ? "border-blue-500 bg-blue-50"
                  : "border-transparent hover:border-blue-200"
              }`}
            >
              <div className="flex items-center gap-3 mb-3">
                {item.effectiveMimeType === FOLDER_MIME ? (
                  <Folder className="text-gray-500" />
                ) : (
                  <img
                    src={
                      item.iconLink ||
                      "https://www.gstatic.com/images/branding/product/2x/docs_2020q4_48dp.png"
                    }
                    alt=""
                    className="w-6 h-6"
                  />
                )}
                <h3 className="font-medium text-gray-800 line-clamp-1">
                  {item.name}
                </h3>
              </div>

              {item.mimeType !== "application/vnd.google-apps.folder" && (
                <>
                  <p className="text-xs text-gray-500">
                    {item.owners?.[0]?.displayName || "Desconhecido"}
                  </p>
                  <p className="text-xs text-gray-400">
                    {new Date(item.modifiedTime).toLocaleString("pt-BR")}
                  </p>
                </>
              )}
            </Card>
          ))}
        </div>
      )}

      <div className="mt-6 flex justify-end gap-3">
        <Button
          disabled={!docSelecionado}
          onClick={() =>
            docSelecionado &&
            onSelecionar({ ...docSelecionado, id: docSelecionado.effectiveId })
          }
        >
          Confirmar
        </Button>
      </div>
    </div>
  );
};

export default SelectDocComponent;
