"use client";

import { useEffect, useState, useMemo } from 'react';
import Link from 'next/link';
import { useToast } from '@/contexts/ToastContext';
import { useConfirm } from '@/contexts/ConfirmContext';

interface Project {
  id: string;
  title: string;
  category: string;
  client: string | null;
  status: string;
  completionDate: string | null;
  description: string | null;
  coverImage: string | null;
  galleryImages: string[];
  featured: boolean;
  createdAt: string;
  updatedAt: string;
}

const STATUS_STYLES: Record<string, string> = {
  'Concluído': 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  'Em andamento': 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  'Rascunho': 'bg-gray-100 text-gray-600 dark:bg-white/10 dark:text-gray-300',
};

export default function ProjectsList() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState<string>('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [filterDateFrom, setFilterDateFrom] = useState<string>('');
  const [filterDateTo, setFilterDateTo] = useState<string>('');
  const { success, error } = useToast();
  const { confirm } = useConfirm();

  useEffect(() => {
    fetchProjects();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchProjects = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/projects');
      if (!response.ok) {
        throw new Error('Falha ao carregar projetos');
      }
      const data: Project[] = await response.json();
      setProjects(data);
    } catch (err) {
      console.error('Erro ao carregar projetos:', err);
      error('Não foi possível carregar os projetos.');
    } finally {
      setLoading(false);
    }
  };

  // Extrair categorias e status únicos
  const categories = useMemo(() => {
    const cats = new Set<string>();
    projects.forEach((p) => {
      if (p.category) cats.add(p.category);
    });
    return Array.from(cats).sort();
  }, [projects]);

  const statuses = useMemo(() => {
    const stats = new Set<string>();
    projects.forEach((p) => {
      if (p.status) stats.add(p.status);
    });
    return Array.from(stats);
  }, [projects]);

  // Filtrar projetos
  const filteredProjects = useMemo(() => {
    return projects.filter((project) => {
      // Filtro de pesquisa
      const matchesSearch = !searchTerm ||
        project.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        project.client?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        project.category?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        project.description?.toLowerCase().includes(searchTerm.toLowerCase());

      // Filtro de categoria
      const matchesCategory = !filterCategory || project.category === filterCategory;

      // Filtro de status
      const matchesStatus = !filterStatus || project.status === filterStatus;

      // Filtro de data (criação)
      let matchesDateFrom = true;
      let matchesDateTo = true;
      
      if (filterDateFrom) {
        const projectDate = new Date(project.createdAt);
        const fromDate = new Date(filterDateFrom);
        matchesDateFrom = projectDate >= fromDate;
      }
      
      if (filterDateTo) {
        const projectDate = new Date(project.createdAt);
        const toDate = new Date(filterDateTo);
        toDate.setHours(23, 59, 59, 999);
        matchesDateTo = projectDate <= toDate;
      }

      return matchesSearch && matchesCategory && matchesStatus && matchesDateFrom && matchesDateTo;
    });
  }, [projects, searchTerm, filterCategory, filterStatus, filterDateFrom, filterDateTo]);

  const clearFilters = () => {
    setSearchTerm('');
    setFilterCategory('');
    setFilterStatus('');
    setFilterDateFrom('');
    setFilterDateTo('');
  };

  const hasActiveFilters = searchTerm || filterCategory || filterStatus || filterDateFrom || filterDateTo;

  const handleDelete = async (id: string) => {
    const confirmed = await confirm({
      title: 'Excluir projeto',
      message: 'Tem certeza que deseja remover este projeto? Esta ação não pode ser desfeita.',
      confirmText: 'Excluir',
      cancelText: 'Cancelar',
      type: 'danger',
    });

    if (!confirmed) return;

    try {
      const response = await fetch(`/api/projects/${id}`, { method: 'DELETE' });
      const result = await response.json();

      if (!response.ok) {
        throw new Error(result?.error || 'Falha ao excluir projeto');
      }

      success('Projeto excluído com sucesso!');
      fetchProjects();
    } catch (err) {
      console.error('Erro ao excluir projeto:', err);
      error('Não foi possível excluir o projeto.');
    }
  };

  const renderStatus = (status: string) => {
    const style = STATUS_STYLES[status] || 'bg-gray-100 text-gray-600 dark:bg-white/10 dark:text-gray-300';
    return (
      <span className={`px-3 py-1 rounded-full text-xs font-bold ${style}`}>
        {status}
      </span>
    );
  };

  const formatDate = (value: string | null) => {
    if (!value) return '—';
    try {
      return new Intl.DateTimeFormat('pt-BR').format(new Date(value));
    } catch (err) {
      console.error('Erro ao formatar data:', err);
      return '—';
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold font-headline text-secondary dark:text-white mb-2">Projetos</h1>
          <p className="text-gray-500 dark:text-gray-400">Gerencie os projetos exibidos no portfólio.</p>
        </div>
        <Link
          href="/admin/projetos/novo"
          className="px-6 py-3 bg-primary text-white rounded-xl font-bold hover-primary transition-colors shadow-lg shadow-primary/20 flex items-center gap-2"
        >
          <i className="ri-add-line text-xl"></i>
          Novo Projeto
        </Link>
      </div>

      {/* Filters Section */}
      <div className="bg-white dark:bg-secondary rounded-xl border border-gray-200 dark:border-white/10 shadow-sm p-4 mb-6">
        <div className="flex flex-col lg:flex-row gap-4">
          {/* Search */}
          <div className="flex-1">
            <div className="relative">
              <input
                type="text"
                placeholder="Pesquisar projetos..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full px-4 py-2.5 pl-10 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 text-secondary dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
              />
              <i className="ri-search-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
              {searchTerm && (
                <button
                  onClick={() => setSearchTerm('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-white transition-colors"
                >
                  <i className="ri-close-line"></i>
                </button>
              )}
            </div>
          </div>

          {/* Category Filter */}
          <div className="w-full lg:w-48">
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 text-secondary dark:text-white focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all appearance-none cursor-pointer"
            >
              <option value="">Todas categorias</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>{cat}</option>
              ))}
            </select>
          </div>

          {/* Status Filter */}
          <div className="w-full lg:w-40">
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 text-secondary dark:text-white focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all appearance-none cursor-pointer"
            >
              <option value="">Todos status</option>
              {statuses.map((status) => (
                <option key={status} value={status}>{status}</option>
              ))}
            </select>
          </div>

          {/* Date From Filter */}
          <div className="w-full lg:w-40">
            <input
              type="date"
              value={filterDateFrom}
              onChange={(e) => setFilterDateFrom(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 text-secondary dark:text-white focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all cursor-pointer"
              title="Data inicial"
            />
          </div>

          {/* Date To Filter */}
          <div className="w-full lg:w-40">
            <input
              type="date"
              value={filterDateTo}
              onChange={(e) => setFilterDateTo(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/5 text-secondary dark:text-white focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all cursor-pointer"
              title="Data final"
            />
          </div>

          {/* Clear Filters */}
          {hasActiveFilters && (
            <button
              onClick={clearFilters}
              className="px-4 py-2.5 text-gray-500 hover:text-red-500 dark:text-gray-400 dark:hover:text-red-400 font-medium transition-colors flex items-center gap-1 whitespace-nowrap"
            >
              <i className="ri-filter-off-line"></i>
              Limpar
            </button>
          )}
        </div>

        {/* Results count */}
        {!loading && (
          <div className="mt-3 pt-3 border-t border-gray-100 dark:border-white/5 text-sm text-gray-500 dark:text-gray-400">
            {hasActiveFilters ? (
              <span>Exibindo {filteredProjects.length} de {projects.length} projetos</span>
            ) : (
              <span>{projects.length} projeto{projects.length !== 1 ? 's' : ''} cadastrado{projects.length !== 1 ? 's' : ''}</span>
            )}
          </div>
        )}
      </div>

      <div className="bg-white dark:bg-secondary rounded-xl border border-gray-200 dark:border-white/10 shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <i className="ri-loader-4-line animate-spin text-3xl text-primary"></i>
          </div>
        ) : filteredProjects.length === 0 ? (
          <div className="py-16 text-center text-gray-500 dark:text-gray-400 flex flex-col items-center gap-3">
            <i className="ri-briefcase-line text-4xl"></i>
            {hasActiveFilters ? (
              <>
                Nenhum projeto encontrado com os filtros aplicados.
                <button
                  onClick={clearFilters}
                  className="mt-2 px-4 py-2 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors"
                >
                  Limpar filtros
                </button>
              </>
            ) : (
              'Nenhum projeto cadastrado ainda.'
            )}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-gray-50 dark:bg-white/5 border-b border-gray-200 dark:border-white/10">
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Projeto</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Categoria</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Cliente</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Inserção</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Conclusão</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Status</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider text-right">Ações</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-white/5">
                {filteredProjects.map((project) => (
                  <tr key={project.id} className="hover:bg-gray-50 dark:hover:bg-white/5 transition-colors group">
                    <td className="p-4">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 rounded-lg bg-gray-200 dark:bg-white/10 overflow-hidden shrink-0 border border-gray-100 dark:border-white/10">
                          {project.coverImage ? (
                            <img src={project.coverImage} alt={project.title} className="w-full h-full object-cover" />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-gray-400">
                              <i className="ri-image-line"></i>
                            </div>
                          )}
                        </div>
                        <div>
                          <p className="font-bold text-secondary dark:text-white flex items-center gap-2">
                            {project.title}
                            {project.featured && (
                              <span className="text-[10px] uppercase tracking-wider bg-primary/10 text-primary px-2 py-0.5 rounded-full font-bold">Destaque</span>
                            )}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">{project.category}</td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">{project.client || '—'}</td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">
                      <div className="flex flex-col">
                        <span>{formatDate(project.createdAt)}</span>
                        <span className="text-xs text-gray-400 dark:text-gray-500">
                          {new Date(project.createdAt).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                    </td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">{formatDate(project.completionDate)}</td>
                    <td className="p-4">{renderStatus(project.status)}</td>
                    <td className="p-4 text-right">
                      <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => handleDelete(project.id)}
                          className="w-8 h-8 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center justify-center text-gray-500 hover:text-red-500 transition-colors cursor-pointer"
                          title="Excluir"
                        >
                          <i className="ri-delete-bin-line"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
