import React, { useEffect, useState } from 'react';
import { 
  FolderOpen, 
  FileText, 
  ArrowLeft, 
  Home, 
  Loader2,
  Search,
  RefreshCw,
  Folder,
  Download,
  ChevronRight
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { useGerenciarPastas } from '../hooks/useGerenciarPastas';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

/**
 * View de gerenciamento de pastas do Nextcloud
 * Permite navegação hierárquica e exportação de arquivos
 */
const GerenciarPastasView = () => {
  const {
    loading,
    currentPath,
    navigationHistory,
    folders,
    files,
    error,
    enterFolder,
    goBack,
    navigateToPath,
    exportFolderFiles,
    loadInitialFolder
  } = useGerenciarPastas();

  const [searchTerm, setSearchTerm] = useState('');
  const [isDarkMode] = useState(true); // Pode vir do contexto de tema

  // Carrega a pasta inicial ao montar
  useEffect(() => {
    // Aguarda um pequeno delay para garantir que o componente está totalmente montado
    const timer = setTimeout(() => {
      console.log('🔄 [GerenciarPastasView] Carregando pasta inicial...');
      loadInitialFolder();
    }, 100);
    
    return () => clearTimeout(timer);
  }, []); // Executa apenas uma vez ao montar

  // Filtra pastas e arquivos baseado no termo de busca
  const filteredFolders = React.useMemo(() => {
    if (!searchTerm) return folders;
    return folders.filter(folder => 
      folder.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      folder.caminho?.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [folders, searchTerm]);

  const filteredFiles = React.useMemo(() => {
    if (!searchTerm) return files;
    return files.filter(file => 
      file.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      file.caminho?.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [files, searchTerm]);

  // Combina pastas e arquivos em uma única lista ordenada (pastas primeiro)
  const combinedItems = React.useMemo(() => {
    const foldersList = filteredFolders.map(folder => ({
      ...folder,
      tipo: 'pasta',
      nome: folder.nome || folder.caminho?.split('/').pop() || 'Pasta'
    }));
    
    const filesList = filteredFiles.map(file => ({
      ...file,
      tipo: 'arquivo',
      nome: file.nome || file.caminho?.split('/').pop() || 'Arquivo'
    }));

    return [...foldersList, ...filesList];
  }, [filteredFolders, filteredFiles]);

  // Gera breadcrumb a partir do caminho atual
  const breadcrumbPaths = React.useMemo(() => {
    const parts = currentPath.split('/').filter(Boolean);
    const paths = [];
    let current = '';
    
    parts.forEach((part, index) => {
      current += (index === 0 ? '' : '/') + part;
      paths.push({
        label: part,
        path: '/' + current
      });
    });

    return paths;
  }, [currentPath]);


  return (
    <div className="h-full flex flex-col">
      {/* Header com breadcrumb e ações */}
      <div className={cn(
        "border-b px-6 py-4 mb-6",
        isDarkMode ? "border-zinc-800" : "border-slate-200"
      )}>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className={cn(
              "p-2 rounded-lg",
              isDarkMode ? "bg-emerald-500/10 text-emerald-400" : "bg-emerald-100 text-emerald-600"
            )}>
              <FolderOpen size={20} />
            </div>
            <div>
              <h1 className={cn(
                "text-xl font-bold",
                isDarkMode ? "text-slate-100" : "text-slate-900"
              )}>
                Gerenciar Pastas
              </h1>
              <p className={cn(
                "text-sm mt-1",
                isDarkMode ? "text-slate-400" : "text-slate-500"
              )}>
                Navegue pelas pastas e exporte arquivos
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={loadInitialFolder}
              disabled={loading}
              className={cn(
                isDarkMode 
                  ? "border-zinc-700 hover:bg-zinc-800" 
                  : "border-slate-300 hover:bg-slate-100"
              )}
            >
              <RefreshCw size={16} className={cn("mr-2", loading && "animate-spin")} />
              Atualizar
            </Button>
          </div>
        </div>

        {/* Breadcrumb */}
        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => navigateToPath('/Espelhos de Notas Fiscais')}
            className={cn(
              "flex items-center gap-1 px-2 py-1 rounded text-sm transition-colors",
              isDarkMode
                ? "text-slate-400 hover:text-emerald-400 hover:bg-zinc-800"
                : "text-slate-500 hover:text-emerald-600 hover:bg-slate-100"
            )}
          >
            <Home size={14} />
            <span>Raiz</span>
          </button>

          {breadcrumbPaths.map((item, index) => (
            <React.Fragment key={item.path}>
              <span className={cn(
                "text-sm",
                isDarkMode ? "text-slate-600" : "text-slate-400"
              )}>
                /
              </span>
              <button
                onClick={() => navigateToPath(item.path)}
                className={cn(
                  "px-2 py-1 rounded text-sm transition-colors truncate max-w-[200px]",
                  isDarkMode
                    ? "text-slate-400 hover:text-emerald-400 hover:bg-zinc-800"
                    : "text-slate-500 hover:text-emerald-600 hover:bg-slate-100"
                )}
                title={item.label}
              >
                {item.label}
              </button>
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Barra de busca com botão de download */}
      <div className="mb-6 px-6">
        <div className="flex items-center gap-3">
          <div className="relative max-w-md flex-1">
            <Search 
              size={18} 
              className={cn(
                "absolute left-3 top-1/2 -translate-y-1/2",
                isDarkMode ? "text-slate-400" : "text-slate-500"
              )} 
            />
            <Input
              type="text"
              placeholder="Buscar pastas ou arquivos..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className={cn(
                "pl-10",
                isDarkMode 
                  ? "bg-zinc-900/50 border-zinc-800 text-slate-100" 
                  : "bg-white border-slate-200 text-slate-900"
              )}
            />
          </div>
          {/* Ícone de download - só aparece quando há arquivos */}
          {files.length > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => exportFolderFiles()}
              disabled={loading}
              className={cn(
                isDarkMode
                  ? "border-emerald-500/30 hover:bg-emerald-500/10 text-emerald-400"
                  : "border-emerald-500 hover:bg-emerald-50 text-emerald-600"
              )}
              title="Baixar arquivos da pasta"
            >
              <Download size={18} className={cn("mr-2", loading && "animate-spin")} />
              Baixar Arquivos
            </Button>
          )}
        </div>
      </div>

      {/* Botão voltar */}
      {navigationHistory.length > 1 && (
        <div className="mb-4 px-6">
          <Button
            variant="ghost"
            size="sm"
            onClick={goBack}
            disabled={loading}
            className={cn(
              isDarkMode
                ? "text-slate-400 hover:text-emerald-400 hover:bg-zinc-800"
                : "text-slate-600 hover:text-emerald-600 hover:bg-slate-100"
            )}
          >
            <ArrowLeft size={16} className="mr-2" />
            Voltar
          </Button>
        </div>
      )}

      {/* Conteúdo principal */}
      <div className="flex-1 overflow-y-auto custom-scrollbar px-6 pb-6">
        {loading && (
          <div className="flex items-center justify-center py-20">
            <Loader2 size={32} className="animate-spin text-emerald-500" />
          </div>
        )}

        {error && !loading && (
          <div className={cn(
            "p-4 rounded-lg border mb-6",
            isDarkMode
              ? "bg-red-500/10 border-red-500/20 text-red-400"
              : "bg-red-50 border-red-200 text-red-600"
          )}>
            <p className="text-sm">{error}</p>
          </div>
        )}

        {!loading && !error && (
          <AnimatePresence mode="wait">
            {combinedItems.length > 0 ? (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.2 }}
                className={cn(
                  "rounded-lg border overflow-hidden",
                  isDarkMode 
                    ? "bg-zinc-900/50 border-zinc-800" 
                    : "bg-white border-slate-200"
                )}
              >
                <div className="overflow-x-auto">
                  <Table>
                  <TableHeader>
                    <TableRow className={cn(
                      isDarkMode 
                        ? "bg-zinc-800/50 hover:bg-zinc-800/50 border-zinc-800" 
                        : "bg-slate-50 hover:bg-slate-50 border-slate-200"
                    )}>
                      <TableHead className={cn(
                        "w-[50px]",
                        isDarkMode ? "text-slate-300" : "text-slate-700"
                      )}>
                        Tipo
                      </TableHead>
                      <TableHead className={cn(
                        isDarkMode ? "text-slate-300" : "text-slate-700"
                      )}>
                        Nome
                      </TableHead>
                      <TableHead className={cn(
                        "hidden md:table-cell",
                        isDarkMode ? "text-slate-300" : "text-slate-700"
                      )}>
                        Caminho
                      </TableHead>
                      <TableHead className={cn(
                        "w-[100px] text-right",
                        isDarkMode ? "text-slate-300" : "text-slate-700"
                      )}>
                        Ações
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {combinedItems.map((item, index) => {
                      const isFolder = item.tipo === 'pasta';
                      const fileName = item.nome || item.caminho?.split('/').pop() || 'Item';
                      const fileExtension = !isFolder ? fileName.split('.').pop()?.toUpperCase() : null;

                      return (
                        <TableRow
                          key={item.caminho || item.nome || index}
                          className={cn(
                            "cursor-pointer transition-colors",
                            isDarkMode
                              ? "hover:bg-zinc-800/50 border-zinc-800"
                              : "hover:bg-slate-50 border-slate-200"
                          )}
                          onClick={() => {
                            if (isFolder) {
                              enterFolder(item);
                            }
                            // Arquivos não fazem nada ao clicar - download é feito pelo botão único
                          }}
                        >
                          <TableCell className="py-3">
                            <div className={cn(
                              "flex items-center justify-center w-10 h-10 rounded-lg",
                              isFolder
                                ? isDarkMode
                                  ? "bg-emerald-500/10 text-emerald-400"
                                  : "bg-emerald-100 text-emerald-600"
                                : isDarkMode
                                  ? "bg-blue-500/10 text-blue-400"
                                  : "bg-blue-100 text-blue-600"
                            )}>
                              {isFolder ? (
                                <Folder size={20} className="stroke-[1.5]" />
                              ) : (
                                <FileText size={20} className="stroke-[1.5]" />
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="py-3">
                            <div className="flex items-center gap-2">
                              <span className={cn(
                                "font-medium",
                                isDarkMode ? "text-slate-100" : "text-slate-900"
                              )}>
                                {fileName}
                              </span>
                              {isFolder && (
                                <ChevronRight 
                                  size={16} 
                                  className={cn(
                                    isDarkMode ? "text-slate-500" : "text-slate-400"
                                  )} 
                                />
                              )}
                            </div>
                            {!isFolder && fileExtension && (
                              <span className={cn(
                                "text-xs mt-1 block",
                                isDarkMode ? "text-slate-400" : "text-slate-500"
                              )}>
                                {fileExtension}
                              </span>
                            )}
                          </TableCell>
                          <TableCell className={cn(
                            "py-3 hidden md:table-cell",
                            isDarkMode ? "text-slate-400" : "text-slate-500"
                          )}>
                            <span className="text-xs truncate block max-w-md" title={item.caminho || ''}>
                              {item.caminho || '-'}
                            </span>
                          </TableCell>
                          <TableCell className="py-3 text-right">
                            <div className="flex items-center justify-end gap-2">
                              {isFolder && (
                                <span className={cn(
                                  "text-xs px-2 py-1 rounded",
                                  isDarkMode
                                    ? "bg-emerald-500/10 text-emerald-400"
                                    : "bg-emerald-100 text-emerald-600"
                                )}>
                                  Pasta
                                </span>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
                </div>
              </motion.div>
            ) : (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex flex-col items-center justify-center py-20"
              >
                <div className={cn(
                  "p-6 rounded-full mb-4",
                  isDarkMode ? "bg-zinc-800" : "bg-slate-100"
                )}>
                  <FolderOpen 
                    size={48} 
                    className={cn(
                      isDarkMode ? "text-slate-600" : "text-slate-400"
                    )} 
                  />
                </div>
                <h3 className={cn(
                  "text-lg font-semibold mb-2",
                  isDarkMode ? "text-slate-300" : "text-slate-700"
                )}>
                  {searchTerm ? 'Nenhum resultado encontrado' : 'Pasta vazia'}
                </h3>
                <p className={cn(
                  "text-sm text-center max-w-md",
                  isDarkMode ? "text-slate-500" : "text-slate-500"
                )}>
                  {searchTerm 
                    ? 'Tente ajustar os termos de busca'
                    : 'Esta pasta não contém pastas ou arquivos'}
                </p>
              </motion.div>
            )}
          </AnimatePresence>
        )}
      </div>
    </div>
  );
};

export default GerenciarPastasView;
