"use client";

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

interface Service {
  id: string;
  title: string;
  icon: string;
  shortDescription: string | null;
  fullDescription: string | null;
  active: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
}

export default function ServicesList() {
  const [services, setServices] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const { success, error } = useToast();
  const { confirm } = useConfirm();

  useEffect(() => {
    fetchServices();
  }, []);

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

  // Filtrar serviços
  const filteredServices = useMemo(() => {
    return services.filter((service) => {
      const matchesSearch = !searchTerm ||
        service.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        service.shortDescription?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        service.fullDescription?.toLowerCase().includes(searchTerm.toLowerCase());

      const matchesStatus = !filterStatus ||
        (filterStatus === 'active' && service.active) ||
        (filterStatus === 'inactive' && !service.active);

      return matchesSearch && matchesStatus;
    });
  }, [services, searchTerm, filterStatus]);

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

  const hasActiveFilters = searchTerm || filterStatus;

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

    if (!confirmed) return;

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

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

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

  const formatDate = (value: string | null) => {
    if (!value) return '—';
    try {
      return new Intl.DateTimeFormat('pt-BR').format(new Date(value));
    } catch (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">Serviços</h1>
          <p className="text-gray-500 dark:text-gray-400">Gerencie os serviços oferecidos pela empresa.</p>
        </div>
        <Link 
          href="/admin/servicos/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 Serviço
        </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 serviços..."
                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>

          {/* Status Filter */}
          <div className="w-full lg:w-48">
            <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 os status</option>
              <option value="active">Ativo</option>
              <option value="inactive">Inativo</option>
            </select>
          </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 {filteredServices.length} de {services.length} serviços</span>
            ) : (
              <span>{services.length} serviço{services.length !== 1 ? 's' : ''} cadastrado{services.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>
        ) : filteredServices.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-customer-service-2-line text-4xl"></i>
            {hasActiveFilters ? (
              <>
                Nenhum serviço 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 serviço 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">Serviço</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Descrição</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Ordem</th>
                  <th className="p-4 font-bold text-gray-600 dark:text-gray-300 text-sm uppercase tracking-wider">Criado em</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">
                {filteredServices.map((service) => (
                  <tr key={service.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-10 h-10 rounded-lg bg-primary/10 text-primary flex items-center justify-center text-xl shrink-0">
                          <i className={service.icon || 'ri-settings-3-line'}></i>
                        </div>
                        <span className="font-bold text-secondary dark:text-white">{service.title}</span>
                      </div>
                    </td>
                    <td className="p-4 text-gray-600 dark:text-gray-400 max-w-xs">
                      <span className="line-clamp-2">{service.shortDescription || '—'}</span>
                    </td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">
                      <span className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-gray-100 dark:bg-white/10 font-bold text-sm">
                        {service.order}
                      </span>
                    </td>
                    <td className="p-4 text-gray-600 dark:text-gray-400">
                      <div className="flex flex-col">
                        <span>{formatDate(service.createdAt)}</span>
                        <span className="text-xs text-gray-400 dark:text-gray-500">
                          {new Date(service.createdAt).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                    </td>
                    <td className="p-4">
                      <span className={`px-3 py-1 rounded-full text-xs font-bold ${
                        service.active 
                          ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' 
                          : 'bg-gray-100 text-gray-600 dark:bg-white/10 dark:text-gray-300'
                      }`}>
                        {service.active ? 'Ativo' : 'Inativo'}
                      </span>
                    </td>
                    <td className="p-4 text-right">
                      <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <Link
                          href={`/admin/servicos/${service.id}/editar`}
                          className="w-8 h-8 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/20 flex items-center justify-center text-gray-500 hover:text-blue-500 transition-colors"
                          title="Editar"
                        >
                          <i className="ri-pencil-line"></i>
                        </Link>
                        <button
                          onClick={() => handleDelete(service.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>
  );
}
