"use client";

import { Fragment, useEffect, useState } from 'react';
import { Menu, Transition } from '@headlessui/react';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import { useToast } from '@/components/layout/ToastContext';
import {
    SparklesIcon,
    TrashIcon,
    PencilIcon,
    EllipsisVerticalIcon,
    MagnifyingGlassIcon,
    PlusIcon,
    XMarkIcon,
    UserGroupIcon,
    ChartBarIcon,
    FolderIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    ArchiveBoxIcon,
    ShareIcon
} from '@heroicons/react/24/outline';

// Mapeamento de ícones para cada solução
const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
    'crm': UserGroupIcon,
    'erp': ChartBarIcon,
    'projetos': FolderIcon,
    'helpdesk': LifebuoyIcon,
    'pagamentos': CreditCardIcon,
    'contratos': DocumentTextIcon,
    'documentos': ArchiveBoxIcon,
    'social': ShareIcon,
};

interface Solution {
    id: string;
    name: string;
    slug: string;
    icon: string;
    description: string;
    is_active: boolean;
    created_at: string;
    updated_at: string;
}

export default function SolutionsPage() {
    const toast = useToast();
    const [solutions, setSolutions] = useState<Solution[]>([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingSolution, setEditingSolution] = useState<Solution | null>(null);

    const [confirmOpen, setConfirmOpen] = useState(false);
    const [solutionToDelete, setSolutionToDelete] = useState<string | null>(null);

    const [searchTerm, setSearchTerm] = useState('');

    // Form state
    const [formData, setFormData] = useState({
        name: '',
        slug: '',
        icon: '',
        description: '',
        is_active: true,
    });

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

    const fetchSolutions = async () => {
        try {
            const response = await fetch('/api/admin/solutions', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                setSolutions(data.solutions || []);
            }
        } catch (error) {
            console.error('Error fetching solutions:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        const url = editingSolution
            ? `/api/admin/solutions/${editingSolution.id}`
            : '/api/admin/solutions';

        const method = editingSolution ? 'PUT' : 'POST';

        try {
            const response = await fetch(url, {
                method,
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (response.ok) {
                toast.success(
                    editingSolution ? 'Solução atualizada' : 'Solução criada',
                    editingSolution ? 'A solução foi atualizada com sucesso.' : 'A nova solução foi criada com sucesso.'
                );
                fetchSolutions();
                handleCloseModal();
            } else {
                const error = await response.json();
                toast.error('Erro', error.message || 'Não foi possível salvar a solução.');
            }
        } catch (error) {
            console.error('Error saving solution:', error);
            toast.error('Erro', 'Ocorreu um erro ao salvar a solução.');
        }
    };

    const handleEdit = (solution: Solution) => {
        setEditingSolution(solution);
        setFormData({
            name: solution.name,
            slug: solution.slug,
            icon: solution.icon,
            description: solution.description,
            is_active: solution.is_active,
        });
        setIsModalOpen(true);
    };

    const handleDeleteClick = (id: string) => {
        setSolutionToDelete(id);
        setConfirmOpen(true);
    };

    const handleConfirmDelete = async () => {
        if (!solutionToDelete) return;

        try {
            const response = await fetch(`/api/admin/solutions/${solutionToDelete}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });

            if (response.ok) {
                setSolutions(solutions.filter(s => s.id !== solutionToDelete));
                toast.success('Solução excluída', 'A solução foi excluída com sucesso.');
            } else {
                toast.error('Erro ao excluir', 'Não foi possível excluir a solução.');
            }
        } catch (error) {
            console.error('Error deleting solution:', error);
            toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a solução.');
        } finally {
            setConfirmOpen(false);
            setSolutionToDelete(null);
        }
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setEditingSolution(null);
        setFormData({
            name: '',
            slug: '',
            icon: '',
            description: '',
            is_active: true,
        });
    };

    const filteredSolutions = solutions.filter((solution) => {
        const searchLower = searchTerm.toLowerCase();
        return (
            (solution.name?.toLowerCase() || '').includes(searchLower) ||
            (solution.slug?.toLowerCase() || '').includes(searchLower) ||
            (solution.description?.toLowerCase() || '').includes(searchLower)
        );
    });

    return (
        <div className="p-6 max-w-[1600px] mx-auto space-y-6">
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Soluções</h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                        Gerencie as soluções disponíveis na plataforma (CRM, ERP, etc.)
                    </p>
                </div>
                <button
                    onClick={() => setIsModalOpen(true)}
                    className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
                    style={{ background: 'var(--gradient)' }}
                >
                    <PlusIcon className="w-4 h-4" />
                    Nova Solução
                </button>
            </div>

            {/* Search */}
            <div className="relative w-full lg:w-96">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
                </div>
                <input
                    type="text"
                    className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
                    placeholder="Buscar por nome, slug ou descrição..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                />
            </div>

            {/* Table */}
            {loading ? (
                <div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
                </div>
            ) : filteredSolutions.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
                    <div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
                        <SparklesIcon className="w-8 h-8 text-zinc-400" />
                    </div>
                    <h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
                        Nenhuma solução encontrada
                    </h3>
                    <p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
                        {searchTerm ? 'Nenhuma solução corresponde à sua busca.' : 'Comece criando sua primeira solução.'}
                    </p>
                </div>
            ) : (
                <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
                    <div className="overflow-x-auto">
                        <table className="w-full">
                            <thead>
                                <tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Solução</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Slug</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Descrição</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
                                    <th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                                {filteredSolutions.map((solution) => {
                                    const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
                                    return (
                                        <tr key={solution.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer" onClick={() => handleEdit(solution)}>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <div className="flex items-center gap-4">
                                                    <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ background: 'var(--gradient)' }}>
                                                        <Icon className="w-5 h-5 text-white" />
                                                    </div>
                                                    <div className="text-sm font-semibold text-zinc-900 dark:text-white">
                                                        {solution.name}
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
                                                <code className="px-2 py-1 bg-zinc-100 dark:bg-zinc-800 rounded">{solution.slug}</code>
                                            </td>
                                            <td className="px-6 py-4 text-sm text-zinc-600 dark:text-zinc-400">
                                                {solution.description || '-'}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span
                                                    className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${solution.is_active
                                                        ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
                                                        : 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                                                        }`}
                                                >
                                                    <span className={`w-1.5 h-1.5 rounded-full ${solution.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
                                                    {solution.is_active ? 'Ativo' : 'Inativo'}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
                                                <Menu as="div" className="relative inline-block text-left">
                                                    <Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
                                                        <EllipsisVerticalIcon className="w-5 h-5" />
                                                    </Menu.Button>
                                                    <Menu.Items
                                                        transition
                                                        portal
                                                        anchor="bottom end"
                                                        className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
                                                    >
                                                        <div className="px-1 py-1">
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => handleEdit(solution)}
                                                                        className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
                                                                    >
                                                                        <PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
                                                                        Editar
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                        </div>
                                                        <div className="px-1 py-1">
                                                            <Menu.Item>
                                                                {({ active }) => (
                                                                    <button
                                                                        onClick={() => handleDeleteClick(solution.id)}
                                                                        className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
                                                                            } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
                                                                    >
                                                                        <TrashIcon className="mr-2 h-4 w-4" />
                                                                        Excluir
                                                                    </button>
                                                                )}
                                                            </Menu.Item>
                                                        </div>
                                                    </Menu.Items>
                                                </Menu>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 overflow-y-auto">
                    <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
                        <div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity" onClick={handleCloseModal}></div>

                        <div className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-zinc-200 dark:border-zinc-800">
                            <div className="absolute right-0 top-0 pr-6 pt-6">
                                <button
                                    type="button"
                                    className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                    onClick={handleCloseModal}
                                >
                                    <XMarkIcon className="h-5 w-5" />
                                </button>
                            </div>

                            <form onSubmit={handleSubmit} className="p-6 sm:p-8">
                                <div className="flex items-start gap-4 mb-6">
                                    <div
                                        className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
                                        style={{ background: 'var(--gradient)' }}
                                    >
                                        <SparklesIcon className="h-6 w-6 text-white" />
                                    </div>
                                    <div>
                                        <h3 className="text-xl font-bold text-zinc-900 dark:text-white">
                                            {editingSolution ? 'Editar Solução' : 'Nova Solução'}
                                        </h3>
                                        <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                                            {editingSolution ? 'Atualize as informações da solução.' : 'Configure uma nova solução para a plataforma.'}
                                        </p>
                                    </div>
                                </div>

                                <div className="space-y-4">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                Nome *
                                            </label>
                                            <input
                                                type="text"
                                                value={formData.name}
                                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                                placeholder="Ex: CRM"
                                                required
                                                className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                                Slug *
                                            </label>
                                            <input
                                                type="text"
                                                value={formData.slug}
                                                onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                                                placeholder="Ex: crm"
                                                required
                                                className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                            />
                                        </div>
                                    </div>

                                    <div>
                                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                            Ícone
                                        </label>
                                        <input
                                            type="text"
                                            value={formData.icon}
                                            onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
                                            placeholder="Ex: 📊 ou users"
                                            className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                        />
                                    </div>

                                    <div>
                                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                            Descrição
                                        </label>
                                        <textarea
                                            value={formData.description}
                                            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                            placeholder="Descrição breve da solução"
                                            rows={3}
                                            className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent resize-none transition-all"
                                        />
                                    </div>

                                    <div className="flex items-center pt-2">
                                        <input
                                            type="checkbox"
                                            checked={formData.is_active}
                                            onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                                            className="h-4 w-4 rounded border-zinc-300 dark:border-zinc-600 focus:ring-2 focus:ring-[var(--brand-color)]"
                                            style={{ accentColor: 'var(--brand-color)' }}
                                        />
                                        <label className="ml-3 text-sm font-medium text-zinc-700 dark:text-zinc-300">
                                            Solução Ativa
                                        </label>
                                    </div>
                                </div>

                                <div className="mt-8 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
                                    <button
                                        type="button"
                                        onClick={handleCloseModal}
                                        className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                    >
                                        Cancelar
                                    </button>
                                    <button
                                        type="submit"
                                        className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all shadow-lg hover:shadow-xl"
                                        style={{ background: 'var(--gradient)' }}
                                    >
                                        {editingSolution ? 'Atualizar' : 'Criar Solução'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}

            <ConfirmDialog
                isOpen={confirmOpen}
                onClose={() => {
                    setConfirmOpen(false);
                    setSolutionToDelete(null);
                }}
                onConfirm={handleConfirmDelete}
                title="Excluir Solução"
                message="Tem certeza que deseja excluir esta solução? Esta ação não pode ser desfeita e afetará os planos que possuem esta solução."
                confirmText="Excluir"
                cancelText="Cancelar"
                variant="danger"
            />
        </div>
    );
}
