// @ts-nocheck
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, Folder } from 'lucide-react'
import Button from '@/components/common/Button'
import Input from '@/components/common/Input'
import Modal from '@/components/common/Modal'
import { supabase } from '@/lib/supabase'
import { toast } from '@/lib/toast'

interface Pasta {
  id: string
  tipo_documento: string
  caminho_local: string
  categoria_id?: string
  habilitado: boolean
  frequencia_atualizacao: string
  formatos_aceitos: string[]
}

export default function PastasTab() {
  const queryClient = useQueryClient()
  const [modalOpen, setModalOpen] = useState(false)
  const [editingPasta, setEditingPasta] = useState<Pasta | null>(null)
  const [formData, setFormData] = useState({
    tipo_documento: '',
    categoria_id: '',
    caminho_local: '',
    habilitado: true,
    frequencia_atualizacao: 'manual',
    formatos_aceitos: ['pdf', 'jpg', 'png'],
  })
  
  const [caminhoTipo, setCaminhoTipo] = useState<'local' | 'nuvem'>('local')
  
  const { data: pastas } = useQuery({
    queryKey: ['pastas'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('configuracoes_pastas')
        .select('*, categoria:categorias(nome, cor)')
        .order('created_at', { ascending: false })
      
      if (error) throw error
      return data as Pasta[]
    },
  })
  
  const { data: categorias } = useQuery({
    queryKey: ['categorias'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('categorias')
        .select('*')
        .eq('ativo', true)
        .order('nome', { ascending: true })
      
      if (error) throw error
      return data
    },
  })

  
  const createMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const { error } = await supabase
        .from('configuracoes_pastas')
        .insert([data as any])
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['pastas'] })
      toast.success('Pasta configurada com sucesso')
      setModalOpen(false)
      resetForm()
    },
  })
  
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: typeof formData }) => {
      const { error } = await supabase
        .from('configuracoes_pastas')
        .update(data as any)
        .eq('id', id)
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['pastas'] })
      toast.success('Pasta atualizada')
      setModalOpen(false)
      setEditingPasta(null)
      resetForm()
    },
  })
  
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('configuracoes_pastas')
        .delete()
        .eq('id', id)
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['pastas'] })
      toast.success('Pasta removida')
    },
  })
  
  const resetForm = () => {
    setFormData({
      tipo_documento: '',
      categoria_id: '',
      caminho_local: '',
      habilitado: true,
      frequencia_atualizacao: 'manual',
      formatos_aceitos: ['pdf', 'jpg', 'png'],
    })
    setCaminhoTipo('local')
  }
  
  const handleSelectFolder = async () => {
    try {
      // @ts-ignore - API do navegador para seleção de pasta
      const dirHandle = await window.showDirectoryPicker()
      setFormData(prev => ({ ...prev, caminho_local: dirHandle.name }))
      toast.success('Pasta selecionada')
    } catch (error) {
      // Usuário cancelou ou navegador não suporta
      toast.info('Use o campo de texto para inserir o caminho manualmente')
    }
  }

  
  const handleEdit = (pasta: Pasta) => {
    setEditingPasta(pasta)
    setFormData({
      tipo_documento: pasta.tipo_documento,
      categoria_id: pasta.categoria_id || '',
      caminho_local: pasta.caminho_local,
      habilitado: pasta.habilitado,
      frequencia_atualizacao: pasta.frequencia_atualizacao,
      formatos_aceitos: pasta.formatos_aceitos,
    })
    setCaminhoTipo('local')
    setModalOpen(true)
  }
  
  const handleSave = () => {
    if (editingPasta) {
      updateMutation.mutate({ id: editingPasta.id, data: formData })
    } else {
      createMutation.mutate(formData)
    }
  }
  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Mapeamento de Pastas</h2>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Configure as pastas onde seus documentos estão armazenados
          </p>
        </div>
        <Button onClick={() => {
          resetForm()
          setEditingPasta(null)
          setModalOpen(true)
        }}>
          <Plus size={20} className="mr-2" />
          Novo Mapeamento
        </Button>
      </div>
      
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Tipo de Documento
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Categoria
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Caminho
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Frequência
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Status
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                Ações
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
            {pastas && pastas.length > 0 ? (
              pastas.map((pasta) => (
                <tr key={pasta.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <Folder size={18} className="text-gray-400 dark:text-gray-500" />
                      <span className="font-medium text-gray-900 dark:text-gray-100">{pasta.tipo_documento}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    {(pasta as any).categoria ? (
                      <span 
                        className="px-2 py-1 text-xs rounded-full"
                        style={{ 
                          backgroundColor: `${(pasta as any).categoria.cor}20`,
                          color: (pasta as any).categoria.cor 
                        }}
                      >
                        {(pasta as any).categoria.nome}
                      </span>
                    ) : (
                      <span className="text-sm text-gray-400 dark:text-gray-500">-</span>
                    )}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600 dark:text-gray-400">
                    {pasta.caminho_local}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600 dark:text-gray-400">
                    {pasta.frequencia_atualizacao}
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      pasta.habilitado 
                        ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200' 
                        : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300'
                    }`}>
                      {pasta.habilitado ? 'Ativo' : 'Inativo'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleEdit(pasta)}
                        className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300"
                      >
                        <Edit size={18} />
                      </button>
                      <button
                        onClick={() => deleteMutation.mutate(pasta.id)}
                        className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={6} className="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                  Nenhum mapeamento configurado
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      
      <Modal
        isOpen={modalOpen}
        onClose={() => {
          setModalOpen(false)
          setEditingPasta(null)
          resetForm()
        }}
        title={editingPasta ? 'Editar Mapeamento' : 'Novo Mapeamento'}
      >
        <div className="space-y-4">
          <Input
            label="Tipo de Documento"
            value={formData.tipo_documento}
            onChange={(e) => setFormData(prev => ({ ...prev, tipo_documento: e.target.value }))}
            placeholder="Ex: Certificados de Soldagem"
            required
          />
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Categoria
            </label>
            <select
              value={formData.categoria_id}
              onChange={(e) => setFormData(prev => ({ ...prev, categoria_id: e.target.value }))}
              className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
            >
              <option value="">Selecione uma categoria...</option>
              {categorias?.map((cat: any) => (
                <option key={cat.id} value={cat.id}>
                  {cat.nome}
                </option>
              ))}
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Tipo de Armazenamento
            </label>
            <div className="flex gap-4 mb-2">
              <label className="flex items-center gap-2">
                <input
                  type="radio"
                  checked={caminhoTipo === 'local'}
                  onChange={() => setCaminhoTipo('local')}
                  className="text-primary focus:ring-primary"
                />
                <span className="text-sm text-gray-900 dark:text-gray-100">Local</span>
              </label>
              <label className="flex items-center gap-2">
                <input
                  type="radio"
                  checked={caminhoTipo === 'nuvem'}
                  onChange={() => setCaminhoTipo('nuvem')}
                  className="text-primary focus:ring-primary"
                />
                <span className="text-sm text-gray-900 dark:text-gray-100">Nuvem</span>
              </label>
            </div>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Caminho {caminhoTipo === 'local' ? 'Local' : 'da Nuvem'} *
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={formData.caminho_local}
                onChange={(e) => setFormData(prev => ({ ...prev, caminho_local: e.target.value }))}
                placeholder={caminhoTipo === 'local' ? 'C:\\Documentos\\Certificados' : 'https://drive.google.com/...'}
                className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100 flex-1"
                required
              />
              {caminhoTipo === 'local' && (
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleSelectFolder}
                  className="flex-shrink-0"
                >
                  <Folder size={16} className="mr-2" />
                  Buscar
                </Button>
              )}
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {caminhoTipo === 'local' 
                ? 'Clique em "Buscar" para selecionar uma pasta ou digite o caminho manualmente'
                : 'Cole o link da pasta na nuvem (Google Drive, OneDrive, etc)'}
            </p>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Frequência de Atualização
            </label>
            <select
              value={formData.frequencia_atualizacao}
              onChange={(e) => setFormData(prev => ({ ...prev, frequencia_atualizacao: e.target.value }))}
              className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
            >
              <option value="manual">Manual</option>
              <option value="ao_criar">Ao Criar Databook</option>
              <option value="diario">Diário</option>
              <option value="semanal">Semanal</option>
            </select>
          </div>
          
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={formData.habilitado}
              onChange={(e) => setFormData(prev => ({ ...prev, habilitado: e.target.checked }))}
              className="text-primary focus:ring-primary"
            />
            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Habilitado</span>
          </label>
          
          <div className="flex justify-end gap-3 pt-4">
            <Button
              variant="outline"
              onClick={() => {
                setModalOpen(false)
                setEditingPasta(null)
                resetForm()
              }}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleSave}
              isLoading={createMutation.isPending || updateMutation.isPending}
            >
              {editingPasta ? 'Atualizar' : 'Criar'}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}


